Importing rustc-1.38.0 Bug: 146571186 Change-Id: Idd23b6282b5f216d22a897103cac97284f84b416
diff --git a/src/llvm-project/lldb/source/API/CMakeLists.txt b/src/llvm-project/lldb/source/API/CMakeLists.txt index e4ec64e..d93b8b5 100644 --- a/src/llvm-project/lldb/source/API/CMakeLists.txt +++ b/src/llvm-project/lldb/source/API/CMakeLists.txt
@@ -9,6 +9,10 @@ set(lldb_python_wrapper ${lldb_scripts_dir}/LLDBWrapPython.cpp) endif() +if(LLDB_BUILD_FRAMEWORK) + set(option_install_prefix INSTALL_PREFIX ${LLDB_FRAMEWORK_INSTALL_DIR}) +endif() + add_lldb_library(liblldb SHARED SBAddress.cpp SBAttachInfo.cpp @@ -34,7 +38,6 @@ SBFrame.cpp SBFunction.cpp SBHostOS.cpp - SBInitializerOptions.cpp SBInstruction.cpp SBInstructionList.cpp SBLanguageRuntime.cpp @@ -50,6 +53,7 @@ SBProcessInfo.cpp SBQueue.cpp SBQueueItem.cpp + SBReproducer.cpp SBSection.cpp SBSourceManager.cpp SBStream.cpp @@ -95,7 +99,13 @@ ${LLDB_ALL_PLUGINS} LINK_COMPONENTS Support - ) + + ${option_install_prefix} +) + +if (MSVC) + set_source_files_properties(SBReproducer.cpp PROPERTIES COMPILE_FLAGS /bigobj) +endif() if(lldb_python_wrapper) add_dependencies(liblldb swig_wrapper) @@ -136,6 +146,7 @@ MESSAGE("-- Symbols (liblldb): exporting all symbols from the lldb and lldb_private namespaces") add_llvm_symbol_exports(liblldb ${CMAKE_CURRENT_SOURCE_DIR}/liblldb-private.exports) endif() + set_target_properties(liblldb_exports PROPERTIES FOLDER "lldb misc") endif() if ( CMAKE_SYSTEM_NAME MATCHES "Windows" ) @@ -151,6 +162,10 @@ ) endif() +if (NOT LLDB_BUILT_STANDALONE) + add_dependencies(liblldb clang-resource-headers) +endif() + if(LLDB_BUILD_FRAMEWORK) include(LLDBFramework) endif()
diff --git a/src/llvm-project/lldb/source/API/SBAddress.cpp b/src/llvm-project/lldb/source/API/SBAddress.cpp index 09ec6c3..358cb40 100644 --- a/src/llvm-project/lldb/source/API/SBAddress.cpp +++ b/src/llvm-project/lldb/source/API/SBAddress.cpp
@@ -1,13 +1,14 @@ //===-- SBAddress.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBProcess.h" #include "lldb/API/SBSection.h" #include "lldb/API/SBStream.h" @@ -15,44 +16,51 @@ #include "lldb/Core/Module.h" #include "lldb/Symbol/LineEntry.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" using namespace lldb; using namespace lldb_private; -SBAddress::SBAddress() : m_opaque_ap(new Address()) {} - -SBAddress::SBAddress(const Address *lldb_object_ptr) - : m_opaque_ap(new Address()) { - if (lldb_object_ptr) - ref() = *lldb_object_ptr; +SBAddress::SBAddress() : m_opaque_up(new Address()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBAddress); } -SBAddress::SBAddress(const SBAddress &rhs) : m_opaque_ap(new Address()) { - if (rhs.IsValid()) - ref() = rhs.ref(); +SBAddress::SBAddress(const Address *lldb_object_ptr) + : m_opaque_up(new Address()) { + if (lldb_object_ptr) + m_opaque_up = llvm::make_unique<Address>(*lldb_object_ptr); +} + +SBAddress::SBAddress(const SBAddress &rhs) : m_opaque_up(new Address()) { + LLDB_RECORD_CONSTRUCTOR(SBAddress, (const lldb::SBAddress &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBAddress::SBAddress(lldb::SBSection section, lldb::addr_t offset) - : m_opaque_ap(new Address(section.GetSP(), offset)) {} + : m_opaque_up(new Address(section.GetSP(), offset)) { + LLDB_RECORD_CONSTRUCTOR(SBAddress, (lldb::SBSection, lldb::addr_t), 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_ap(new Address()) { + : m_opaque_up(new Address()) { + LLDB_RECORD_CONSTRUCTOR(SBAddress, (lldb::addr_t, lldb::SBTarget &), + load_addr, target); + SetLoadAddress(load_addr, target); } SBAddress::~SBAddress() {} const SBAddress &SBAddress::operator=(const SBAddress &rhs) { - if (this != &rhs) { - if (rhs.IsValid()) - ref() = rhs.ref(); - else - m_opaque_ap.reset(new Address()); - } - return *this; + LLDB_RECORD_METHOD(const lldb::SBAddress &, + SBAddress, operator=,(const lldb::SBAddress &), rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } bool lldb::operator==(const SBAddress &lhs, const SBAddress &rhs) { @@ -61,13 +69,33 @@ return false; } -bool SBAddress::IsValid() const { - return m_opaque_ap != NULL && m_opaque_ap->IsValid(); +bool SBAddress::operator!=(const SBAddress &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBAddress, operator!=,(const SBAddress &), + &rhs); + + return !(*this == rhs); } -void SBAddress::Clear() { m_opaque_ap.reset(new Address()); } +bool SBAddress::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBAddress, IsValid); + return this->operator bool(); +} +SBAddress::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBAddress, operator bool); + + return m_opaque_up != nullptr && m_opaque_up->IsValid(); +} + +void SBAddress::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBAddress, Clear); + + m_opaque_up.reset(new Address()); +} void SBAddress::SetAddress(lldb::SBSection section, lldb::addr_t offset) { + LLDB_RECORD_METHOD(void, SBAddress, SetAddress, + (lldb::SBSection, lldb::addr_t), section, offset); + Address &addr = ref(); addr.SetSection(section.GetSP()); addr.SetOffset(offset); @@ -77,61 +105,59 @@ if (lldb_object_ptr) ref() = *lldb_object_ptr; else - m_opaque_ap.reset(new Address()); + m_opaque_up.reset(new Address()); } lldb::addr_t SBAddress::GetFileAddress() const { - if (m_opaque_ap->IsValid()) - return m_opaque_ap->GetFileAddress(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBAddress, GetFileAddress); + + if (m_opaque_up->IsValid()) + return m_opaque_up->GetFileAddress(); else return LLDB_INVALID_ADDRESS; } lldb::addr_t SBAddress::GetLoadAddress(const SBTarget &target) const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(lldb::addr_t, SBAddress, GetLoadAddress, + (const lldb::SBTarget &), target); lldb::addr_t addr = LLDB_INVALID_ADDRESS; TargetSP target_sp(target.GetSP()); if (target_sp) { - if (m_opaque_ap->IsValid()) { + if (m_opaque_up->IsValid()) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); - addr = m_opaque_ap->GetLoadAddress(target_sp.get()); + addr = m_opaque_up->GetLoadAddress(target_sp.get()); } } - if (log) { - if (addr == LLDB_INVALID_ADDRESS) - log->Printf( - "SBAddress::GetLoadAddress (SBTarget(%p)) => LLDB_INVALID_ADDRESS", - static_cast<void *>(target_sp.get())); - else - log->Printf("SBAddress::GetLoadAddress (SBTarget(%p)) => 0x%" PRIx64, - static_cast<void *>(target_sp.get()), addr); - } - return addr; } void SBAddress::SetLoadAddress(lldb::addr_t load_addr, lldb::SBTarget &target) { + LLDB_RECORD_METHOD(void, SBAddress, SetLoadAddress, + (lldb::addr_t, lldb::SBTarget &), 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_ap->Clear(); + 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_ap->IsValid()) - m_opaque_ap->SetOffset(load_addr); + if (!m_opaque_up->IsValid()) + m_opaque_up->SetOffset(load_addr); } bool SBAddress::OffsetAddress(addr_t offset) { - if (m_opaque_ap->IsValid()) { - addr_t addr_offset = m_opaque_ap->GetOffset(); + LLDB_RECORD_METHOD(bool, SBAddress, OffsetAddress, (lldb::addr_t), offset); + + if (m_opaque_up->IsValid()) { + addr_t addr_offset = m_opaque_up->GetOffset(); if (addr_offset != LLDB_INVALID_ADDRESS) { - m_opaque_ap->SetOffset(addr_offset + offset); + m_opaque_up->SetOffset(addr_offset + offset); return true; } } @@ -139,46 +165,53 @@ } lldb::SBSection SBAddress::GetSection() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSection, SBAddress, GetSection); + lldb::SBSection sb_section; - if (m_opaque_ap->IsValid()) - sb_section.SetSP(m_opaque_ap->GetSection()); - return sb_section; + if (m_opaque_up->IsValid()) + sb_section.SetSP(m_opaque_up->GetSection()); + return LLDB_RECORD_RESULT(sb_section); } lldb::addr_t SBAddress::GetOffset() { - if (m_opaque_ap->IsValid()) - return m_opaque_ap->GetOffset(); + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBAddress, GetOffset); + + if (m_opaque_up->IsValid()) + return m_opaque_up->GetOffset(); return 0; } -Address *SBAddress::operator->() { return m_opaque_ap.get(); } +Address *SBAddress::operator->() { return m_opaque_up.get(); } -const Address *SBAddress::operator->() const { return m_opaque_ap.get(); } +const Address *SBAddress::operator->() const { return m_opaque_up.get(); } Address &SBAddress::ref() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new Address()); - return *m_opaque_ap; + if (m_opaque_up == nullptr) + m_opaque_up.reset(new 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_ap.get()); - return *m_opaque_ap; + assert(m_opaque_up.get()); + return *m_opaque_up; } -Address *SBAddress::get() { return m_opaque_ap.get(); } +Address *SBAddress::get() { return m_opaque_up.get(); } bool SBAddress::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBAddress, GetDescription, (lldb::SBStream &), + 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_ap->IsValid()) { - m_opaque_ap->Dump(&strm, NULL, Address::DumpStyleResolvedDescription, + if (m_opaque_up->IsValid()) { + m_opaque_up->Dump(&strm, nullptr, Address::DumpStyleResolvedDescription, Address::DumpStyleModuleWithFileAddress, 4); StreamString sstrm; - // m_opaque_ap->Dump (&sstrm, NULL, + // m_opaque_up->Dump (&sstrm, NULL, // Address::DumpStyleResolvedDescription, Address::DumpStyleInvalid, // 4); // if (sstrm.GetData()) @@ -190,54 +223,109 @@ } SBModule SBAddress::GetModule() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBModule, SBAddress, GetModule); + SBModule sb_module; - if (m_opaque_ap->IsValid()) - sb_module.SetSP(m_opaque_ap->GetModule()); - return sb_module; + if (m_opaque_up->IsValid()) + sb_module.SetSP(m_opaque_up->GetModule()); + return LLDB_RECORD_RESULT(sb_module); } SBSymbolContext SBAddress::GetSymbolContext(uint32_t resolve_scope) { + LLDB_RECORD_METHOD(lldb::SBSymbolContext, SBAddress, GetSymbolContext, + (uint32_t), resolve_scope); + SBSymbolContext sb_sc; SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope); - if (m_opaque_ap->IsValid()) - m_opaque_ap->CalculateSymbolContext(&sb_sc.ref(), scope); - return sb_sc; + if (m_opaque_up->IsValid()) + m_opaque_up->CalculateSymbolContext(&sb_sc.ref(), scope); + return LLDB_RECORD_RESULT(sb_sc); } SBCompileUnit SBAddress::GetCompileUnit() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBCompileUnit, SBAddress, GetCompileUnit); + SBCompileUnit sb_comp_unit; - if (m_opaque_ap->IsValid()) - sb_comp_unit.reset(m_opaque_ap->CalculateSymbolContextCompileUnit()); - return sb_comp_unit; + if (m_opaque_up->IsValid()) + sb_comp_unit.reset(m_opaque_up->CalculateSymbolContextCompileUnit()); + return LLDB_RECORD_RESULT(sb_comp_unit); } SBFunction SBAddress::GetFunction() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFunction, SBAddress, GetFunction); + SBFunction sb_function; - if (m_opaque_ap->IsValid()) - sb_function.reset(m_opaque_ap->CalculateSymbolContextFunction()); - return sb_function; + if (m_opaque_up->IsValid()) + sb_function.reset(m_opaque_up->CalculateSymbolContextFunction()); + return LLDB_RECORD_RESULT(sb_function); } SBBlock SBAddress::GetBlock() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBAddress, GetBlock); + SBBlock sb_block; - if (m_opaque_ap->IsValid()) - sb_block.SetPtr(m_opaque_ap->CalculateSymbolContextBlock()); - return sb_block; + if (m_opaque_up->IsValid()) + sb_block.SetPtr(m_opaque_up->CalculateSymbolContextBlock()); + return LLDB_RECORD_RESULT(sb_block); } SBSymbol SBAddress::GetSymbol() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSymbol, SBAddress, GetSymbol); + SBSymbol sb_symbol; - if (m_opaque_ap->IsValid()) - sb_symbol.reset(m_opaque_ap->CalculateSymbolContextSymbol()); - return sb_symbol; + if (m_opaque_up->IsValid()) + sb_symbol.reset(m_opaque_up->CalculateSymbolContextSymbol()); + return LLDB_RECORD_RESULT(sb_symbol); } SBLineEntry SBAddress::GetLineEntry() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBLineEntry, SBAddress, GetLineEntry); + SBLineEntry sb_line_entry; - if (m_opaque_ap->IsValid()) { + if (m_opaque_up->IsValid()) { LineEntry line_entry; - if (m_opaque_ap->CalculateSymbolContextLineEntry(line_entry)) + if (m_opaque_up->CalculateSymbolContextLineEntry(line_entry)) sb_line_entry.SetLineEntry(line_entry); } - return sb_line_entry; + return LLDB_RECORD_RESULT(sb_line_entry); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBAddress>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBAddress, ()); + LLDB_REGISTER_CONSTRUCTOR(SBAddress, (const lldb::SBAddress &)); + LLDB_REGISTER_CONSTRUCTOR(SBAddress, (lldb::SBSection, lldb::addr_t)); + LLDB_REGISTER_CONSTRUCTOR(SBAddress, (lldb::addr_t, lldb::SBTarget &)); + LLDB_REGISTER_METHOD(const lldb::SBAddress &, + SBAddress, operator=,(const lldb::SBAddress &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBAddress, operator!=,(const lldb::SBAddress &)); + LLDB_REGISTER_METHOD_CONST(bool, SBAddress, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBAddress, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBAddress, Clear, ()); + LLDB_REGISTER_METHOD(void, SBAddress, SetAddress, + (lldb::SBSection, lldb::addr_t)); + LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBAddress, GetFileAddress, ()); + LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBAddress, GetLoadAddress, + (const lldb::SBTarget &)); + LLDB_REGISTER_METHOD(void, SBAddress, SetLoadAddress, + (lldb::addr_t, lldb::SBTarget &)); + LLDB_REGISTER_METHOD(bool, SBAddress, OffsetAddress, (lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBSection, SBAddress, GetSection, ()); + LLDB_REGISTER_METHOD(lldb::addr_t, SBAddress, GetOffset, ()); + LLDB_REGISTER_METHOD(bool, SBAddress, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(lldb::SBModule, SBAddress, GetModule, ()); + LLDB_REGISTER_METHOD(lldb::SBSymbolContext, SBAddress, GetSymbolContext, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBCompileUnit, SBAddress, GetCompileUnit, ()); + LLDB_REGISTER_METHOD(lldb::SBFunction, SBAddress, GetFunction, ()); + LLDB_REGISTER_METHOD(lldb::SBBlock, SBAddress, GetBlock, ()); + LLDB_REGISTER_METHOD(lldb::SBSymbol, SBAddress, GetSymbol, ()); + LLDB_REGISTER_METHOD(lldb::SBLineEntry, SBAddress, GetLineEntry, ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBAttachInfo.cpp b/src/llvm-project/lldb/source/API/SBAttachInfo.cpp index a74487a..838385c 100644 --- a/src/llvm-project/lldb/source/API/SBAttachInfo.cpp +++ b/src/llvm-project/lldb/source/API/SBAttachInfo.cpp
@@ -1,14 +1,14 @@ //===-- SBAttachInfo.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBListener.h" #include "lldb/Target/Process.h" @@ -16,15 +16,21 @@ using namespace lldb; using namespace lldb_private; -SBAttachInfo::SBAttachInfo() : m_opaque_sp(new ProcessAttachInfo()) {} +SBAttachInfo::SBAttachInfo() : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBAttachInfo); +} SBAttachInfo::SBAttachInfo(lldb::pid_t pid) : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_RECORD_CONSTRUCTOR(SBAttachInfo, (lldb::pid_t), pid); + m_opaque_sp->SetProcessID(pid); } SBAttachInfo::SBAttachInfo(const char *path, bool wait_for) : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_RECORD_CONSTRUCTOR(SBAttachInfo, (const char *, bool), path, wait_for); + if (path && path[0]) m_opaque_sp->GetExecutableFile().SetFile(path, FileSpec::Style::native); m_opaque_sp->SetWaitForLaunch(wait_for); @@ -32,6 +38,9 @@ SBAttachInfo::SBAttachInfo(const char *path, bool wait_for, bool async) : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_RECORD_CONSTRUCTOR(SBAttachInfo, (const char *, bool, bool), path, + wait_for, async); + if (path && path[0]) m_opaque_sp->GetExecutableFile().SetFile(path, FileSpec::Style::native); m_opaque_sp->SetWaitForLaunch(wait_for); @@ -40,7 +49,9 @@ SBAttachInfo::SBAttachInfo(const SBAttachInfo &rhs) : m_opaque_sp(new ProcessAttachInfo()) { - *m_opaque_sp = *rhs.m_opaque_sp; + LLDB_RECORD_CONSTRUCTOR(SBAttachInfo, (const lldb::SBAttachInfo &), rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); } SBAttachInfo::~SBAttachInfo() {} @@ -48,34 +59,54 @@ lldb_private::ProcessAttachInfo &SBAttachInfo::ref() { return *m_opaque_sp; } SBAttachInfo &SBAttachInfo::operator=(const SBAttachInfo &rhs) { + LLDB_RECORD_METHOD(lldb::SBAttachInfo &, + SBAttachInfo, operator=,(const lldb::SBAttachInfo &), rhs); + if (this != &rhs) - *m_opaque_sp = *rhs.m_opaque_sp; - return *this; + m_opaque_sp = clone(rhs.m_opaque_sp); + return LLDB_RECORD_RESULT(*this); } -lldb::pid_t SBAttachInfo::GetProcessID() { return m_opaque_sp->GetProcessID(); } +lldb::pid_t SBAttachInfo::GetProcessID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::pid_t, SBAttachInfo, GetProcessID); + + return m_opaque_sp->GetProcessID(); +} void SBAttachInfo::SetProcessID(lldb::pid_t pid) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetProcessID, (lldb::pid_t), pid); + m_opaque_sp->SetProcessID(pid); } uint32_t SBAttachInfo::GetResumeCount() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBAttachInfo, GetResumeCount); + return m_opaque_sp->GetResumeCount(); } void SBAttachInfo::SetResumeCount(uint32_t c) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetResumeCount, (uint32_t), c); + m_opaque_sp->SetResumeCount(c); } const char *SBAttachInfo::GetProcessPluginName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBAttachInfo, GetProcessPluginName); + return m_opaque_sp->GetProcessPluginName(); } void SBAttachInfo::SetProcessPluginName(const char *plugin_name) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetProcessPluginName, (const char *), + plugin_name); + return m_opaque_sp->SetProcessPluginName(plugin_name); } void SBAttachInfo::SetExecutable(const char *path) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetExecutable, (const char *), path); + if (path && path[0]) m_opaque_sp->GetExecutableFile().SetFile(path, FileSpec::Style::native); else @@ -83,6 +114,9 @@ } void SBAttachInfo::SetExecutable(SBFileSpec exe_file) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetExecutable, (lldb::SBFileSpec), + exe_file); + if (exe_file.IsValid()) m_opaque_sp->GetExecutableFile() = exe_file.ref(); else @@ -90,78 +124,185 @@ } bool SBAttachInfo::GetWaitForLaunch() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBAttachInfo, GetWaitForLaunch); + return m_opaque_sp->GetWaitForLaunch(); } void SBAttachInfo::SetWaitForLaunch(bool b) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetWaitForLaunch, (bool), b); + m_opaque_sp->SetWaitForLaunch(b); } void SBAttachInfo::SetWaitForLaunch(bool b, bool async) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetWaitForLaunch, (bool, bool), b, + async); + m_opaque_sp->SetWaitForLaunch(b); m_opaque_sp->SetAsync(async); } bool SBAttachInfo::GetIgnoreExisting() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBAttachInfo, GetIgnoreExisting); + return m_opaque_sp->GetIgnoreExisting(); } void SBAttachInfo::SetIgnoreExisting(bool b) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetIgnoreExisting, (bool), b); + m_opaque_sp->SetIgnoreExisting(b); } -uint32_t SBAttachInfo::GetUserID() { return m_opaque_sp->GetUserID(); } +uint32_t SBAttachInfo::GetUserID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBAttachInfo, GetUserID); -uint32_t SBAttachInfo::GetGroupID() { return m_opaque_sp->GetGroupID(); } + return m_opaque_sp->GetUserID(); +} -bool SBAttachInfo::UserIDIsValid() { return m_opaque_sp->UserIDIsValid(); } +uint32_t SBAttachInfo::GetGroupID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBAttachInfo, GetGroupID); -bool SBAttachInfo::GroupIDIsValid() { return m_opaque_sp->GroupIDIsValid(); } + return m_opaque_sp->GetGroupID(); +} -void SBAttachInfo::SetUserID(uint32_t uid) { m_opaque_sp->SetUserID(uid); } +bool SBAttachInfo::UserIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBAttachInfo, UserIDIsValid); -void SBAttachInfo::SetGroupID(uint32_t gid) { m_opaque_sp->SetGroupID(gid); } + return m_opaque_sp->UserIDIsValid(); +} + +bool SBAttachInfo::GroupIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBAttachInfo, GroupIDIsValid); + + return m_opaque_sp->GroupIDIsValid(); +} + +void SBAttachInfo::SetUserID(uint32_t uid) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetUserID, (uint32_t), uid); + + m_opaque_sp->SetUserID(uid); +} + +void SBAttachInfo::SetGroupID(uint32_t gid) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetGroupID, (uint32_t), gid); + + m_opaque_sp->SetGroupID(gid); +} uint32_t SBAttachInfo::GetEffectiveUserID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBAttachInfo, GetEffectiveUserID); + return m_opaque_sp->GetEffectiveUserID(); } uint32_t SBAttachInfo::GetEffectiveGroupID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBAttachInfo, GetEffectiveGroupID); + return m_opaque_sp->GetEffectiveGroupID(); } bool SBAttachInfo::EffectiveUserIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBAttachInfo, EffectiveUserIDIsValid); + return m_opaque_sp->EffectiveUserIDIsValid(); } bool SBAttachInfo::EffectiveGroupIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBAttachInfo, EffectiveGroupIDIsValid); + return m_opaque_sp->EffectiveGroupIDIsValid(); } void SBAttachInfo::SetEffectiveUserID(uint32_t uid) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetEffectiveUserID, (uint32_t), uid); + m_opaque_sp->SetEffectiveUserID(uid); } void SBAttachInfo::SetEffectiveGroupID(uint32_t gid) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetEffectiveGroupID, (uint32_t), gid); + m_opaque_sp->SetEffectiveGroupID(gid); } lldb::pid_t SBAttachInfo::GetParentProcessID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::pid_t, SBAttachInfo, GetParentProcessID); + return m_opaque_sp->GetParentProcessID(); } void SBAttachInfo::SetParentProcessID(lldb::pid_t pid) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetParentProcessID, (lldb::pid_t), + pid); + m_opaque_sp->SetParentProcessID(pid); } bool SBAttachInfo::ParentProcessIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBAttachInfo, ParentProcessIDIsValid); + return m_opaque_sp->ParentProcessIDIsValid(); } SBListener SBAttachInfo::GetListener() { - return SBListener(m_opaque_sp->GetListener()); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBListener, SBAttachInfo, GetListener); + + return LLDB_RECORD_RESULT(SBListener(m_opaque_sp->GetListener())); } void SBAttachInfo::SetListener(SBListener &listener) { + LLDB_RECORD_METHOD(void, SBAttachInfo, SetListener, (lldb::SBListener &), + listener); + m_opaque_sp->SetListener(listener.GetSP()); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBAttachInfo>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBAttachInfo, ()); + LLDB_REGISTER_CONSTRUCTOR(SBAttachInfo, (lldb::pid_t)); + LLDB_REGISTER_CONSTRUCTOR(SBAttachInfo, (const char *, bool)); + LLDB_REGISTER_CONSTRUCTOR(SBAttachInfo, (const char *, bool, bool)); + LLDB_REGISTER_CONSTRUCTOR(SBAttachInfo, (const lldb::SBAttachInfo &)); + LLDB_REGISTER_METHOD(lldb::SBAttachInfo &, + SBAttachInfo, operator=,(const lldb::SBAttachInfo &)); + LLDB_REGISTER_METHOD(lldb::pid_t, SBAttachInfo, GetProcessID, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetProcessID, (lldb::pid_t)); + LLDB_REGISTER_METHOD(uint32_t, SBAttachInfo, GetResumeCount, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetResumeCount, (uint32_t)); + LLDB_REGISTER_METHOD(const char *, SBAttachInfo, GetProcessPluginName, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetProcessPluginName, + (const char *)); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetExecutable, (const char *)); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetExecutable, (lldb::SBFileSpec)); + LLDB_REGISTER_METHOD(bool, SBAttachInfo, GetWaitForLaunch, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetWaitForLaunch, (bool)); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetWaitForLaunch, (bool, bool)); + LLDB_REGISTER_METHOD(bool, SBAttachInfo, GetIgnoreExisting, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetIgnoreExisting, (bool)); + LLDB_REGISTER_METHOD(uint32_t, SBAttachInfo, GetUserID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBAttachInfo, GetGroupID, ()); + LLDB_REGISTER_METHOD(bool, SBAttachInfo, UserIDIsValid, ()); + LLDB_REGISTER_METHOD(bool, SBAttachInfo, GroupIDIsValid, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetUserID, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetGroupID, (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBAttachInfo, GetEffectiveUserID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBAttachInfo, GetEffectiveGroupID, ()); + LLDB_REGISTER_METHOD(bool, SBAttachInfo, EffectiveUserIDIsValid, ()); + LLDB_REGISTER_METHOD(bool, SBAttachInfo, EffectiveGroupIDIsValid, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetEffectiveUserID, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetEffectiveGroupID, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::pid_t, SBAttachInfo, GetParentProcessID, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetParentProcessID, (lldb::pid_t)); + LLDB_REGISTER_METHOD(bool, SBAttachInfo, ParentProcessIDIsValid, ()); + LLDB_REGISTER_METHOD(lldb::SBListener, SBAttachInfo, GetListener, ()); + LLDB_REGISTER_METHOD(void, SBAttachInfo, SetListener, (lldb::SBListener &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBBlock.cpp b/src/llvm-project/lldb/source/API/SBBlock.cpp index cd45387..f333d1d 100644 --- a/src/llvm-project/lldb/source/API/SBBlock.cpp +++ b/src/llvm-project/lldb/source/API/SBBlock.cpp
@@ -1,13 +1,13 @@ //===-- SBBlock.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBFrame.h" @@ -21,34 +21,52 @@ #include "lldb/Symbol/VariableList.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Log.h" using namespace lldb; using namespace lldb_private; -SBBlock::SBBlock() : m_opaque_ptr(NULL) {} +SBBlock::SBBlock() : m_opaque_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBBlock); +} 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) {} - -const SBBlock &SBBlock::operator=(const SBBlock &rhs) { - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; +SBBlock::SBBlock(const SBBlock &rhs) : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBBlock, (const lldb::SBBlock &), rhs); } -SBBlock::~SBBlock() { m_opaque_ptr = NULL; } +const SBBlock &SBBlock::operator=(const SBBlock &rhs) { + LLDB_RECORD_METHOD(const lldb::SBBlock &, + SBBlock, operator=,(const lldb::SBBlock &), rhs); -bool SBBlock::IsValid() const { return m_opaque_ptr != NULL; } + m_opaque_ptr = rhs.m_opaque_ptr; + return LLDB_RECORD_RESULT(*this); +} + +SBBlock::~SBBlock() { m_opaque_ptr = nullptr; } + +bool SBBlock::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBlock, IsValid); + return this->operator bool(); +} +SBBlock::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBlock, operator bool); + + return m_opaque_ptr != nullptr; +} bool SBBlock::IsInlined() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBlock, IsInlined); + if (m_opaque_ptr) - return m_opaque_ptr->GetInlinedFunctionInfo() != NULL; + return m_opaque_ptr->GetInlinedFunctionInfo() != nullptr; return false; } const char *SBBlock::GetInlinedName() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBlock, GetInlinedName); + if (m_opaque_ptr) { const InlineFunctionInfo *inlined_info = m_opaque_ptr->GetInlinedFunctionInfo(); @@ -59,13 +77,16 @@ language = function->GetLanguage(); else language = lldb::eLanguageTypeUnknown; - return inlined_info->GetName(language).AsCString(NULL); + return inlined_info->GetName(language).AsCString(nullptr); } } - return NULL; + return nullptr; } SBFileSpec SBBlock::GetInlinedCallSiteFile() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBBlock, + GetInlinedCallSiteFile); + SBFileSpec sb_file; if (m_opaque_ptr) { const InlineFunctionInfo *inlined_info = @@ -73,10 +94,12 @@ if (inlined_info) sb_file.SetFileSpec(inlined_info->GetCallSite().GetFile()); } - return sb_file; + return LLDB_RECORD_RESULT(sb_file); } uint32_t SBBlock::GetInlinedCallSiteLine() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBlock, GetInlinedCallSiteLine); + if (m_opaque_ptr) { const InlineFunctionInfo *inlined_info = m_opaque_ptr->GetInlinedFunctionInfo(); @@ -87,6 +110,8 @@ } uint32_t SBBlock::GetInlinedCallSiteColumn() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBlock, GetInlinedCallSiteColumn); + if (m_opaque_ptr) { const InlineFunctionInfo *inlined_info = m_opaque_ptr->GetInlinedFunctionInfo(); @@ -106,31 +131,39 @@ } SBBlock SBBlock::GetParent() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBBlock, GetParent); + SBBlock sb_block; if (m_opaque_ptr) sb_block.m_opaque_ptr = m_opaque_ptr->GetParent(); - return sb_block; + return LLDB_RECORD_RESULT(sb_block); } lldb::SBBlock SBBlock::GetContainingInlinedBlock() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBBlock, GetContainingInlinedBlock); + SBBlock sb_block; if (m_opaque_ptr) sb_block.m_opaque_ptr = m_opaque_ptr->GetContainingInlinedBlock(); - return sb_block; + return LLDB_RECORD_RESULT(sb_block); } SBBlock SBBlock::GetSibling() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBBlock, GetSibling); + SBBlock sb_block; if (m_opaque_ptr) sb_block.m_opaque_ptr = m_opaque_ptr->GetSibling(); - return sb_block; + return LLDB_RECORD_RESULT(sb_block); } SBBlock SBBlock::GetFirstChild() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBBlock, GetFirstChild); + SBBlock sb_block; if (m_opaque_ptr) sb_block.m_opaque_ptr = m_opaque_ptr->GetFirstChild(); - return sb_block; + return LLDB_RECORD_RESULT(sb_block); } lldb_private::Block *SBBlock::GetPtr() { return m_opaque_ptr; } @@ -138,6 +171,9 @@ void SBBlock::SetPtr(lldb_private::Block *block) { m_opaque_ptr = block; } bool SBBlock::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBBlock, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); if (m_opaque_ptr) { @@ -160,12 +196,17 @@ } uint32_t SBBlock::GetNumRanges() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBBlock, GetNumRanges); + if (m_opaque_ptr) return m_opaque_ptr->GetNumRanges(); return 0; } lldb::SBAddress SBBlock::GetRangeStartAddress(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBAddress, SBBlock, GetRangeStartAddress, (uint32_t), + idx); + lldb::SBAddress sb_addr; if (m_opaque_ptr) { AddressRange range; @@ -173,10 +214,13 @@ sb_addr.ref() = range.GetBaseAddress(); } } - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); } lldb::SBAddress SBBlock::GetRangeEndAddress(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBAddress, SBBlock, GetRangeEndAddress, (uint32_t), + idx); + lldb::SBAddress sb_addr; if (m_opaque_ptr) { AddressRange range; @@ -185,10 +229,13 @@ sb_addr.ref().Slide(range.GetByteSize()); } } - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); } uint32_t SBBlock::GetRangeIndexForBlockAddress(lldb::SBAddress block_addr) { + LLDB_RECORD_METHOD(uint32_t, SBBlock, GetRangeIndexForBlockAddress, + (lldb::SBAddress), block_addr); + if (m_opaque_ptr && block_addr.IsValid()) { return m_opaque_ptr->GetRangeIndexContainingAddress(block_addr.ref()); } @@ -199,6 +246,11 @@ lldb::SBValueList SBBlock::GetVariables(lldb::SBFrame &frame, bool arguments, bool locals, bool statics, lldb::DynamicValueType use_dynamic) { + LLDB_RECORD_METHOD( + lldb::SBValueList, SBBlock, GetVariables, + (lldb::SBFrame &, bool, bool, bool, lldb::DynamicValueType), frame, + arguments, locals, statics, use_dynamic); + Block *block = GetPtr(); SBValueList value_list; if (block) { @@ -245,11 +297,15 @@ } } } - return value_list; + return LLDB_RECORD_RESULT(value_list); } lldb::SBValueList SBBlock::GetVariables(lldb::SBTarget &target, bool arguments, bool locals, bool statics) { + LLDB_RECORD_METHOD(lldb::SBValueList, SBBlock, GetVariables, + (lldb::SBTarget &, bool, bool, bool), target, arguments, + locals, statics); + Block *block = GetPtr(); SBValueList value_list; @@ -293,5 +349,44 @@ } } } - return value_list; + return LLDB_RECORD_RESULT(value_list); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBBlock>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBBlock, ()); + LLDB_REGISTER_CONSTRUCTOR(SBBlock, (const lldb::SBBlock &)); + LLDB_REGISTER_METHOD(const lldb::SBBlock &, + SBBlock, operator=,(const lldb::SBBlock &)); + LLDB_REGISTER_METHOD_CONST(bool, SBBlock, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBBlock, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBBlock, IsInlined, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBBlock, GetInlinedName, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBBlock, + GetInlinedCallSiteFile, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBlock, GetInlinedCallSiteLine, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBlock, GetInlinedCallSiteColumn, ()); + LLDB_REGISTER_METHOD(lldb::SBBlock, SBBlock, GetParent, ()); + LLDB_REGISTER_METHOD(lldb::SBBlock, SBBlock, GetContainingInlinedBlock, ()); + LLDB_REGISTER_METHOD(lldb::SBBlock, SBBlock, GetSibling, ()); + LLDB_REGISTER_METHOD(lldb::SBBlock, SBBlock, GetFirstChild, ()); + LLDB_REGISTER_METHOD(bool, SBBlock, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(uint32_t, SBBlock, GetNumRanges, ()); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBBlock, GetRangeStartAddress, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBBlock, GetRangeEndAddress, + (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBBlock, GetRangeIndexForBlockAddress, + (lldb::SBAddress)); + LLDB_REGISTER_METHOD( + lldb::SBValueList, SBBlock, GetVariables, + (lldb::SBFrame &, bool, bool, bool, lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBBlock, GetVariables, + (lldb::SBTarget &, bool, bool, bool)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBBreakpoint.cpp b/src/llvm-project/lldb/source/API/SBBreakpoint.cpp index b672007..45eaea6 100644 --- a/src/llvm-project/lldb/source/API/SBBreakpoint.cpp +++ b/src/llvm-project/lldb/source/API/SBBreakpoint.cpp
@@ -1,13 +1,13 @@ //===-- SBBreakpoint.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBBreakpointLocation.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBEvent.h" @@ -32,7 +32,6 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadSpec.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" #include "SBBreakpointOptionCommon.h" @@ -44,42 +43,60 @@ using namespace lldb; using namespace lldb_private; -SBBreakpoint::SBBreakpoint() {} +SBBreakpoint::SBBreakpoint() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBBreakpoint); } SBBreakpoint::SBBreakpoint(const SBBreakpoint &rhs) - : m_opaque_wp(rhs.m_opaque_wp) {} + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_RECORD_CONSTRUCTOR(SBBreakpoint, (const lldb::SBBreakpoint &), rhs); +} SBBreakpoint::SBBreakpoint(const lldb::BreakpointSP &bp_sp) - : m_opaque_wp(bp_sp) {} + : m_opaque_wp(bp_sp) { + LLDB_RECORD_CONSTRUCTOR(SBBreakpoint, (const lldb::BreakpointSP &), bp_sp); +} SBBreakpoint::~SBBreakpoint() = default; const SBBreakpoint &SBBreakpoint::operator=(const SBBreakpoint &rhs) { + LLDB_RECORD_METHOD(const lldb::SBBreakpoint &, + SBBreakpoint, operator=,(const lldb::SBBreakpoint &), rhs); + m_opaque_wp = rhs.m_opaque_wp; - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBBreakpoint::operator==(const lldb::SBBreakpoint &rhs) { + LLDB_RECORD_METHOD( + bool, SBBreakpoint, operator==,(const lldb::SBBreakpoint &), rhs); + return m_opaque_wp.lock() == rhs.m_opaque_wp.lock(); } bool SBBreakpoint::operator!=(const lldb::SBBreakpoint &rhs) { + LLDB_RECORD_METHOD( + bool, SBBreakpoint, operator!=,(const lldb::SBBreakpoint &), rhs); + return m_opaque_wp.lock() != rhs.m_opaque_wp.lock(); } break_id_t SBBreakpoint::GetID() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::break_id_t, SBBreakpoint, GetID); break_id_t break_id = LLDB_INVALID_BREAK_ID; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) break_id = bkpt_sp->GetID(); - LLDB_LOG(log, "breakpoint = {0}, id = {1}", bkpt_sp.get(), break_id); return break_id; } bool SBBreakpoint::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpoint, IsValid); + return this->operator bool(); +} +SBBreakpoint::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpoint, operator bool); + BreakpointSP bkpt_sp = GetSP(); if (!bkpt_sp) return false; @@ -90,6 +107,8 @@ } void SBBreakpoint::ClearAllBreakpointSites() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBBreakpoint, ClearAllBreakpointSites); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -99,6 +118,9 @@ } SBBreakpointLocation SBBreakpoint::FindLocationByAddress(addr_t vm_addr) { + LLDB_RECORD_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, + FindLocationByAddress, (lldb::addr_t), vm_addr); + SBBreakpointLocation sb_bp_location; BreakpointSP bkpt_sp = GetSP(); @@ -114,10 +136,13 @@ sb_bp_location.SetLocation(bkpt_sp->FindLocationByAddress(address)); } } - return sb_bp_location; + return LLDB_RECORD_RESULT(sb_bp_location); } break_id_t SBBreakpoint::FindLocationIDByAddress(addr_t vm_addr) { + LLDB_RECORD_METHOD(lldb::break_id_t, SBBreakpoint, FindLocationIDByAddress, + (lldb::addr_t), vm_addr); + break_id_t break_id = LLDB_INVALID_BREAK_ID; BreakpointSP bkpt_sp = GetSP(); @@ -136,6 +161,9 @@ } SBBreakpointLocation SBBreakpoint::FindLocationByID(break_id_t bp_loc_id) { + LLDB_RECORD_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, FindLocationByID, + (lldb::break_id_t), bp_loc_id); + SBBreakpointLocation sb_bp_location; BreakpointSP bkpt_sp = GetSP(); @@ -145,10 +173,13 @@ sb_bp_location.SetLocation(bkpt_sp->FindLocationByID(bp_loc_id)); } - return sb_bp_location; + return LLDB_RECORD_RESULT(sb_bp_location); } SBBreakpointLocation SBBreakpoint::GetLocationAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, + GetLocationAtIndex, (uint32_t), index); + SBBreakpointLocation sb_bp_location; BreakpointSP bkpt_sp = GetSP(); @@ -158,14 +189,13 @@ sb_bp_location.SetLocation(bkpt_sp->GetLocationAtIndex(index)); } - return sb_bp_location; + return LLDB_RECORD_RESULT(sb_bp_location); } void SBBreakpoint::SetEnabled(bool enable) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - BreakpointSP bkpt_sp = GetSP(); + LLDB_RECORD_METHOD(void, SBBreakpoint, SetEnabled, (bool), enable); - LLDB_LOG(log, "breakpoint = {0}, enable = {1}", bkpt_sp.get(), enable); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -175,6 +205,8 @@ } bool SBBreakpoint::IsEnabled() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpoint, IsEnabled); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -185,10 +217,9 @@ } void SBBreakpoint::SetOneShot(bool one_shot) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - BreakpointSP bkpt_sp = GetSP(); + LLDB_RECORD_METHOD(void, SBBreakpoint, SetOneShot, (bool), one_shot); - LLDB_LOG(log, "breakpoint = {0}, one_shot = {1}", bkpt_sp.get(), one_shot); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -198,6 +229,8 @@ } bool SBBreakpoint::IsOneShot() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpoint, IsOneShot); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -208,6 +241,8 @@ } bool SBBreakpoint::IsInternal() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpoint, IsInternal); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -218,10 +253,9 @@ } void SBBreakpoint::SetIgnoreCount(uint32_t count) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - BreakpointSP bkpt_sp = GetSP(); + LLDB_RECORD_METHOD(void, SBBreakpoint, SetIgnoreCount, (uint32_t), count); - LLDB_LOG(log, "breakpoint = {0}, count = {1}", bkpt_sp.get(), count); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -231,6 +265,9 @@ } void SBBreakpoint::SetCondition(const char *condition) { + LLDB_RECORD_METHOD(void, SBBreakpoint, SetCondition, (const char *), + condition); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -240,6 +277,8 @@ } const char *SBBreakpoint::GetCondition() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBBreakpoint, GetCondition); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -250,6 +289,9 @@ } void SBBreakpoint::SetAutoContinue(bool auto_continue) { + LLDB_RECORD_METHOD(void, SBBreakpoint, SetAutoContinue, (bool), + auto_continue); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -259,6 +301,8 @@ } bool SBBreakpoint::GetAutoContinue() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpoint, GetAutoContinue); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -269,6 +313,8 @@ } uint32_t SBBreakpoint::GetHitCount() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBreakpoint, GetHitCount); + uint32_t count = 0; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { @@ -277,13 +323,12 @@ count = bkpt_sp->GetHitCount(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, count = {1}", bkpt_sp.get(), count); - return count; } uint32_t SBBreakpoint::GetIgnoreCount() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBreakpoint, GetIgnoreCount); + uint32_t count = 0; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { @@ -292,24 +337,23 @@ count = bkpt_sp->GetIgnoreCount(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, count = {1}", bkpt_sp.get(), count); - return count; } void SBBreakpoint::SetThreadID(tid_t tid) { + LLDB_RECORD_METHOD(void, SBBreakpoint, SetThreadID, (lldb::tid_t), tid); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( bkpt_sp->GetTarget().GetAPIMutex()); bkpt_sp->SetThreadID(tid); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, tid = {1:x}", bkpt_sp.get(), tid); } tid_t SBBreakpoint::GetThreadID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::tid_t, SBBreakpoint, GetThreadID); + tid_t tid = LLDB_INVALID_THREAD_ID; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { @@ -318,15 +362,13 @@ tid = bkpt_sp->GetThreadID(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, tid = {1:x}", bkpt_sp.get(), tid); return tid; } void SBBreakpoint::SetThreadIndex(uint32_t index) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpoint, SetThreadIndex, (uint32_t), index); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, index = {1}", bkpt_sp.get(), index); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( bkpt_sp->GetTarget().GetAPIMutex()); @@ -335,6 +377,8 @@ } uint32_t SBBreakpoint::GetThreadIndex() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBreakpoint, GetThreadIndex); + uint32_t thread_idx = UINT32_MAX; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { @@ -345,16 +389,15 @@ if (thread_spec != nullptr) thread_idx = thread_spec->GetIndex(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, index = {1}", bkpt_sp.get(), thread_idx); return thread_idx; } void SBBreakpoint::SetThreadName(const char *thread_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpoint, SetThreadName, (const char *), + thread_name); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, name = {1}", bkpt_sp.get(), thread_name); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -364,6 +407,8 @@ } const char *SBBreakpoint::GetThreadName() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpoint, GetThreadName); + const char *name = nullptr; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { @@ -374,17 +419,15 @@ if (thread_spec != nullptr) name = thread_spec->GetName(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, name = {1}", bkpt_sp.get(), name); return name; } void SBBreakpoint::SetQueueName(const char *queue_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpoint, SetQueueName, (const char *), + queue_name); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, queue_name = {1}", bkpt_sp.get(), - queue_name); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( bkpt_sp->GetTarget().GetAPIMutex()); @@ -393,6 +436,8 @@ } const char *SBBreakpoint::GetQueueName() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpoint, GetQueueName); + const char *name = nullptr; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { @@ -403,13 +448,14 @@ if (thread_spec) name = thread_spec->GetQueueName(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, name = {1}", bkpt_sp.get(), name); return name; } size_t SBBreakpoint::GetNumResolvedLocations() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(size_t, SBBreakpoint, + GetNumResolvedLocations); + size_t num_resolved = 0; BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { @@ -417,13 +463,12 @@ bkpt_sp->GetTarget().GetAPIMutex()); num_resolved = bkpt_sp->GetNumResolvedLocations(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, num_resolved = {1}", bkpt_sp.get(), - num_resolved); return num_resolved; } size_t SBBreakpoint::GetNumLocations() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(size_t, SBBreakpoint, GetNumLocations); + BreakpointSP bkpt_sp = GetSP(); size_t num_locs = 0; if (bkpt_sp) { @@ -431,12 +476,13 @@ bkpt_sp->GetTarget().GetAPIMutex()); num_locs = bkpt_sp->GetNumLocations(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOG(log, "breakpoint = {0}, num_locs = {1}", bkpt_sp.get(), num_locs); return num_locs; } void SBBreakpoint::SetCommandLineCommands(SBStringList &commands) { + LLDB_RECORD_METHOD(void, SBBreakpoint, SetCommandLineCommands, + (lldb::SBStringList &), commands); + BreakpointSP bkpt_sp = GetSP(); if (!bkpt_sp) return; @@ -452,6 +498,9 @@ } bool SBBreakpoint::GetCommandLineCommands(SBStringList &commands) { + LLDB_RECORD_METHOD(bool, SBBreakpoint, GetCommandLineCommands, + (lldb::SBStringList &), commands); + BreakpointSP bkpt_sp = GetSP(); if (!bkpt_sp) return false; @@ -464,10 +513,15 @@ } bool SBBreakpoint::GetDescription(SBStream &s) { + LLDB_RECORD_METHOD(bool, SBBreakpoint, GetDescription, (lldb::SBStream &), s); + return GetDescription(s, true); } bool SBBreakpoint::GetDescription(SBStream &s, bool include_locations) { + LLDB_RECORD_METHOD(bool, SBBreakpoint, GetDescription, + (lldb::SBStream &, bool), s, include_locations); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -485,47 +539,45 @@ return false; } -SBError -SBBreakpoint::AddLocation(SBAddress &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; +SBError SBBreakpoint::AddLocation(SBAddress &address) { + LLDB_RECORD_METHOD(lldb::SBError, SBBreakpoint, AddLocation, + (lldb::SBAddress &), address); + + BreakpointSP bkpt_sp = GetSP(); + SBError error; + + if (!address.IsValid()) { + error.SetErrorString("Can't add an invalid address."); + return LLDB_RECORD_RESULT(error); + } + + if (!bkpt_sp) { + error.SetErrorString("No breakpoint to add a location to."); + return LLDB_RECORD_RESULT(error); + } + + if (!llvm::isa<BreakpointResolverScripted>(bkpt_sp->GetResolver().get())) { + error.SetErrorString("Only a scripted resolver can add locations."); + return LLDB_RECORD_RESULT(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 LLDB_RECORD_RESULT(error); } +void SBBreakpoint ::SetCallback(SBBreakpointHitCallback callback, void *baton) { + LLDB_RECORD_DUMMY(void, SBBreakpoint, SetCallback, + (lldb::SBBreakpointHitCallback, void *), callback, baton); -void SBBreakpoint - ::SetCallback(SBBreakpointHitCallback callback, - void *baton) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, callback = {1}, baton = {2}", bkpt_sp.get(), - callback, baton); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -539,10 +591,10 @@ void SBBreakpoint::SetScriptCallbackFunction( const char *callback_function_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpoint, SetScriptCallbackFunction, + (const char *), callback_function_name); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, callback = {1}", bkpt_sp.get(), - callback_function_name); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -550,7 +602,6 @@ BreakpointOptions *bp_options = bkpt_sp->GetOptions(); bkpt_sp->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter() ->SetBreakpointCommandCallbackFunction(bp_options, callback_function_name); @@ -558,10 +609,10 @@ } SBError SBBreakpoint::SetScriptCallbackBody(const char *callback_body_text) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBError, SBBreakpoint, SetScriptCallbackBody, + (const char *), callback_body_text); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, callback body:\n{1}", bkpt_sp.get(), - callback_body_text); SBError sb_error; if (bkpt_sp) { @@ -571,20 +622,19 @@ Status error = bkpt_sp->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter() ->SetBreakpointCommandCallback(bp_options, callback_body_text); sb_error.SetError(error); } else sb_error.SetErrorString("invalid breakpoint"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } bool SBBreakpoint::AddName(const char *new_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBBreakpoint, AddName, (const char *), new_name); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, name = {1}", bkpt_sp.get(), new_name); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -593,34 +643,30 @@ // probably more annoying to have to provide it. bkpt_sp->GetTarget().AddNameToBreakpoint(bkpt_sp, new_name, error); if (error.Fail()) - { - if (log) - log->Printf("Failed to add name: '%s' to breakpoint: %s", - new_name, error.AsCString()); return false; - } } return true; } void SBBreakpoint::RemoveName(const char *name_to_remove) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpoint, RemoveName, (const char *), + name_to_remove); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, name = {1}", bkpt_sp.get(), name_to_remove); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( bkpt_sp->GetTarget().GetAPIMutex()); - bkpt_sp->GetTarget().RemoveNameFromBreakpoint(bkpt_sp, - ConstString(name_to_remove)); + bkpt_sp->GetTarget().RemoveNameFromBreakpoint(bkpt_sp, + ConstString(name_to_remove)); } } bool SBBreakpoint::MatchesName(const char *name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBBreakpoint, MatchesName, (const char *), name); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}, name = {1}", bkpt_sp.get(), name); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -632,9 +678,10 @@ } void SBBreakpoint::GetNames(SBStringList &names) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpoint, GetNames, (lldb::SBStringList &), + names); + BreakpointSP bkpt_sp = GetSP(); - LLDB_LOG(log, "breakpoint = {0}", bkpt_sp.get()); if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -648,12 +695,19 @@ } bool SBBreakpoint::EventIsBreakpointEvent(const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(bool, SBBreakpoint, EventIsBreakpointEvent, + (const lldb::SBEvent &), event); + return Breakpoint::BreakpointEventData::GetEventDataFromEvent(event.get()) != nullptr; } BreakpointEventType SBBreakpoint::GetBreakpointEventTypeFromEvent(const SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(lldb::BreakpointEventType, SBBreakpoint, + GetBreakpointEventTypeFromEvent, + (const lldb::SBEvent &), event); + if (event.IsValid()) return Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( event.GetSP()); @@ -661,25 +715,38 @@ } SBBreakpoint SBBreakpoint::GetBreakpointFromEvent(const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(lldb::SBBreakpoint, SBBreakpoint, + GetBreakpointFromEvent, (const lldb::SBEvent &), + event); + if (event.IsValid()) - return SBBreakpoint( - Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event.GetSP())); - return SBBreakpoint(); + return LLDB_RECORD_RESULT( + SBBreakpoint(Breakpoint::BreakpointEventData::GetBreakpointFromEvent( + event.GetSP()))); + return LLDB_RECORD_RESULT(SBBreakpoint()); } SBBreakpointLocation SBBreakpoint::GetBreakpointLocationAtIndexFromEvent(const lldb::SBEvent &event, uint32_t loc_idx) { + LLDB_RECORD_STATIC_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, + GetBreakpointLocationAtIndexFromEvent, + (const lldb::SBEvent &, uint32_t), 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; + return LLDB_RECORD_RESULT(sb_breakpoint_loc); } uint32_t SBBreakpoint::GetNumBreakpointLocationsFromEvent(const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(uint32_t, SBBreakpoint, + GetNumBreakpointLocationsFromEvent, + (const lldb::SBEvent &), event); + uint32_t num_locations = 0; if (event.IsValid()) num_locations = @@ -689,6 +756,8 @@ } bool SBBreakpoint::IsHardware() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpoint, IsHardware); + BreakpointSP bkpt_sp = GetSP(); if (bkpt_sp) return bkpt_sp->IsHardware(); @@ -782,11 +851,15 @@ }; SBBreakpointList::SBBreakpointList(SBTarget &target) - : m_opaque_sp(new SBBreakpointListImpl(target.GetSP())) {} + : m_opaque_sp(new SBBreakpointListImpl(target.GetSP())) { + LLDB_RECORD_CONSTRUCTOR(SBBreakpointList, (lldb::SBTarget &), target); +} SBBreakpointList::~SBBreakpointList() {} size_t SBBreakpointList::GetSize() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(size_t, SBBreakpointList, GetSize); + if (!m_opaque_sp) return 0; else @@ -794,21 +867,30 @@ } SBBreakpoint SBBreakpointList::GetBreakpointAtIndex(size_t idx) { + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBBreakpointList, GetBreakpointAtIndex, + (size_t), idx); + if (!m_opaque_sp) - return SBBreakpoint(); + return LLDB_RECORD_RESULT(SBBreakpoint()); BreakpointSP bkpt_sp = m_opaque_sp->GetBreakpointAtIndex(idx); - return SBBreakpoint(bkpt_sp); + return LLDB_RECORD_RESULT(SBBreakpoint(bkpt_sp)); } SBBreakpoint SBBreakpointList::FindBreakpointByID(lldb::break_id_t id) { + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBBreakpointList, FindBreakpointByID, + (lldb::break_id_t), id); + if (!m_opaque_sp) - return SBBreakpoint(); + return LLDB_RECORD_RESULT(SBBreakpoint()); BreakpointSP bkpt_sp = m_opaque_sp->FindBreakpointByID(id); - return SBBreakpoint(bkpt_sp); + return LLDB_RECORD_RESULT(SBBreakpoint(bkpt_sp)); } void SBBreakpointList::Append(const SBBreakpoint &sb_bkpt) { + LLDB_RECORD_METHOD(void, SBBreakpointList, Append, + (const lldb::SBBreakpoint &), sb_bkpt); + if (!sb_bkpt.IsValid()) return; if (!m_opaque_sp) @@ -817,12 +899,18 @@ } void SBBreakpointList::AppendByID(lldb::break_id_t id) { + LLDB_RECORD_METHOD(void, SBBreakpointList, AppendByID, (lldb::break_id_t), + id); + if (!m_opaque_sp) return; m_opaque_sp->AppendByID(id); } bool SBBreakpointList::AppendIfUnique(const SBBreakpoint &sb_bkpt) { + LLDB_RECORD_METHOD(bool, SBBreakpointList, AppendIfUnique, + (const lldb::SBBreakpoint &), sb_bkpt); + if (!sb_bkpt.IsValid()) return false; if (!m_opaque_sp) @@ -831,6 +919,8 @@ } void SBBreakpointList::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBBreakpointList, Clear); + if (m_opaque_sp) m_opaque_sp->Clear(); } @@ -840,3 +930,107 @@ if (m_opaque_sp) m_opaque_sp->CopyToBreakpointIDList(bp_id_list); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBBreakpoint>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBBreakpoint, ()); + LLDB_REGISTER_CONSTRUCTOR(SBBreakpoint, (const lldb::SBBreakpoint &)); + LLDB_REGISTER_CONSTRUCTOR(SBBreakpoint, (const lldb::BreakpointSP &)); + LLDB_REGISTER_METHOD(const lldb::SBBreakpoint &, + SBBreakpoint, operator=,(const lldb::SBBreakpoint &)); + LLDB_REGISTER_METHOD(bool, + SBBreakpoint, operator==,(const lldb::SBBreakpoint &)); + LLDB_REGISTER_METHOD(bool, + SBBreakpoint, operator!=,(const lldb::SBBreakpoint &)); + LLDB_REGISTER_METHOD_CONST(lldb::break_id_t, SBBreakpoint, GetID, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpoint, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpoint, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, ClearAllBreakpointSites, ()); + LLDB_REGISTER_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, + FindLocationByAddress, (lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::break_id_t, SBBreakpoint, + FindLocationIDByAddress, (lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, + FindLocationByID, (lldb::break_id_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, + GetLocationAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetEnabled, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, IsEnabled, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetOneShot, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpoint, IsOneShot, ()); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, IsInternal, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetIgnoreCount, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetCondition, (const char *)); + LLDB_REGISTER_METHOD(const char *, SBBreakpoint, GetCondition, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetAutoContinue, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, GetAutoContinue, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBreakpoint, GetHitCount, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBreakpoint, GetIgnoreCount, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetThreadID, (lldb::tid_t)); + LLDB_REGISTER_METHOD(lldb::tid_t, SBBreakpoint, GetThreadID, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetThreadIndex, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBreakpoint, GetThreadIndex, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetThreadName, (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpoint, GetThreadName, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetQueueName, (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpoint, GetQueueName, ()); + LLDB_REGISTER_METHOD_CONST(size_t, SBBreakpoint, GetNumResolvedLocations, + ()); + LLDB_REGISTER_METHOD_CONST(size_t, SBBreakpoint, GetNumLocations, ()); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetCommandLineCommands, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, GetCommandLineCommands, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, GetDescription, + (lldb::SBStream &, bool)); + LLDB_REGISTER_METHOD(lldb::SBError, SBBreakpoint, AddLocation, + (lldb::SBAddress &)); + LLDB_REGISTER_METHOD(void, SBBreakpoint, SetScriptCallbackFunction, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBBreakpoint, SetScriptCallbackBody, + (const char *)); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, AddName, (const char *)); + LLDB_REGISTER_METHOD(void, SBBreakpoint, RemoveName, (const char *)); + LLDB_REGISTER_METHOD(bool, SBBreakpoint, MatchesName, (const char *)); + LLDB_REGISTER_METHOD(void, SBBreakpoint, GetNames, (lldb::SBStringList &)); + LLDB_REGISTER_STATIC_METHOD(bool, SBBreakpoint, EventIsBreakpointEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::BreakpointEventType, SBBreakpoint, + GetBreakpointEventTypeFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBBreakpoint, SBBreakpoint, + GetBreakpointFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBBreakpointLocation, SBBreakpoint, + GetBreakpointLocationAtIndexFromEvent, + (const lldb::SBEvent &, uint32_t)); + LLDB_REGISTER_STATIC_METHOD(uint32_t, SBBreakpoint, + GetNumBreakpointLocationsFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpoint, IsHardware, ()); +} + +template <> +void RegisterMethods<SBBreakpointList>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointList, (lldb::SBTarget &)); + LLDB_REGISTER_METHOD_CONST(size_t, SBBreakpointList, GetSize, ()); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBBreakpointList, + GetBreakpointAtIndex, (size_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBBreakpointList, + FindBreakpointByID, (lldb::break_id_t)); + LLDB_REGISTER_METHOD(void, SBBreakpointList, Append, + (const lldb::SBBreakpoint &)); + LLDB_REGISTER_METHOD(void, SBBreakpointList, AppendByID, + (lldb::break_id_t)); + LLDB_REGISTER_METHOD(bool, SBBreakpointList, AppendIfUnique, + (const lldb::SBBreakpoint &)); + LLDB_REGISTER_METHOD(void, SBBreakpointList, Clear, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBBreakpointLocation.cpp b/src/llvm-project/lldb/source/API/SBBreakpointLocation.cpp index 99ac0277..640545f 100644 --- a/src/llvm-project/lldb/source/API/SBBreakpointLocation.cpp +++ b/src/llvm-project/lldb/source/API/SBBreakpointLocation.cpp
@@ -1,13 +1,13 @@ //===-- SBBreakpointLocation.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBDefines.h" @@ -22,7 +22,6 @@ #include "lldb/Interpreter/ScriptInterpreter.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadSpec.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" @@ -30,27 +29,32 @@ using namespace lldb; using namespace lldb_private; -SBBreakpointLocation::SBBreakpointLocation() {} +SBBreakpointLocation::SBBreakpointLocation() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBBreakpointLocation); +} SBBreakpointLocation::SBBreakpointLocation( const lldb::BreakpointLocationSP &break_loc_sp) : m_opaque_wp(break_loc_sp) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) { - SBStream sstr; - GetDescription(sstr, lldb::eDescriptionLevelBrief); - LLDB_LOG(log, "location = {0} ({1})", break_loc_sp.get(), sstr.GetData()); - } + LLDB_RECORD_CONSTRUCTOR(SBBreakpointLocation, + (const lldb::BreakpointLocationSP &), break_loc_sp); } SBBreakpointLocation::SBBreakpointLocation(const SBBreakpointLocation &rhs) - : m_opaque_wp(rhs.m_opaque_wp) {} + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_RECORD_CONSTRUCTOR(SBBreakpointLocation, + (const lldb::SBBreakpointLocation &), rhs); +} const SBBreakpointLocation &SBBreakpointLocation:: operator=(const SBBreakpointLocation &rhs) { + LLDB_RECORD_METHOD( + const lldb::SBBreakpointLocation &, + SBBreakpointLocation, operator=,(const lldb::SBBreakpointLocation &), + rhs); + m_opaque_wp = rhs.m_opaque_wp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBBreakpointLocation::~SBBreakpointLocation() {} @@ -59,17 +63,31 @@ return m_opaque_wp.lock(); } -bool SBBreakpointLocation::IsValid() const { return bool(GetSP()); } +bool SBBreakpointLocation::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpointLocation, IsValid); + return this->operator bool(); +} +SBBreakpointLocation::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpointLocation, operator bool); + + return bool(GetSP()); +} SBAddress SBBreakpointLocation::GetAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBAddress, SBBreakpointLocation, GetAddress); + BreakpointLocationSP loc_sp = GetSP(); - if (loc_sp) - return SBAddress(&loc_sp->GetAddress()); - else - return SBAddress(); + if (loc_sp) { + return LLDB_RECORD_RESULT(SBAddress(&loc_sp->GetAddress())); + } + + return LLDB_RECORD_RESULT(SBAddress()); } addr_t SBBreakpointLocation::GetLoadAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBBreakpointLocation, + GetLoadAddress); + addr_t ret_addr = LLDB_INVALID_ADDRESS; BreakpointLocationSP loc_sp = GetSP(); @@ -83,6 +101,8 @@ } void SBBreakpointLocation::SetEnabled(bool enabled) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetEnabled, (bool), enabled); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -92,6 +112,8 @@ } bool SBBreakpointLocation::IsEnabled() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpointLocation, IsEnabled); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -102,6 +124,8 @@ } uint32_t SBBreakpointLocation::GetHitCount() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBBreakpointLocation, GetHitCount); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -112,6 +136,8 @@ } uint32_t SBBreakpointLocation::GetIgnoreCount() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBBreakpointLocation, GetIgnoreCount); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -122,6 +148,8 @@ } void SBBreakpointLocation::SetIgnoreCount(uint32_t n) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetIgnoreCount, (uint32_t), n); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -131,6 +159,9 @@ } void SBBreakpointLocation::SetCondition(const char *condition) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetCondition, (const char *), + condition); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -140,16 +171,21 @@ } const char *SBBreakpointLocation::GetCondition() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBBreakpointLocation, GetCondition); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( loc_sp->GetTarget().GetAPIMutex()); return loc_sp->GetConditionText(); } - return NULL; + return nullptr; } void SBBreakpointLocation::SetAutoContinue(bool auto_continue) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetAutoContinue, (bool), + auto_continue); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -159,6 +195,8 @@ } bool SBBreakpointLocation::GetAutoContinue() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpointLocation, GetAutoContinue); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -170,10 +208,10 @@ void SBBreakpointLocation::SetScriptCallbackFunction( const char *callback_function_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetScriptCallbackFunction, + (const char *), callback_function_name); + BreakpointLocationSP loc_sp = GetSP(); - LLDB_LOG(log, "location = {0}, callback = {1}", loc_sp.get(), - callback_function_name); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -182,7 +220,6 @@ loc_sp->GetBreakpoint() .GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter() ->SetBreakpointCommandCallbackFunction(bp_options, callback_function_name); @@ -191,10 +228,10 @@ SBError SBBreakpointLocation::SetScriptCallbackBody(const char *callback_body_text) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBError, SBBreakpointLocation, SetScriptCallbackBody, + (const char *), callback_body_text); + BreakpointLocationSP loc_sp = GetSP(); - LLDB_LOG(log, "location = {0}: callback body:\n{1}", loc_sp.get(), - callback_body_text); SBError sb_error; if (loc_sp) { @@ -205,17 +242,19 @@ loc_sp->GetBreakpoint() .GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter() ->SetBreakpointCommandCallback(bp_options, callback_body_text); sb_error.SetError(error); } else sb_error.SetErrorString("invalid breakpoint"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } void SBBreakpointLocation::SetCommandLineCommands(SBStringList &commands) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetCommandLineCommands, + (lldb::SBStringList &), commands); + BreakpointLocationSP loc_sp = GetSP(); if (!loc_sp) return; @@ -231,6 +270,9 @@ } bool SBBreakpointLocation::GetCommandLineCommands(SBStringList &commands) { + LLDB_RECORD_METHOD(bool, SBBreakpointLocation, GetCommandLineCommands, + (lldb::SBStringList &), commands); + BreakpointLocationSP loc_sp = GetSP(); if (!loc_sp) return false; @@ -243,6 +285,9 @@ } void SBBreakpointLocation::SetThreadID(tid_t thread_id) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetThreadID, (lldb::tid_t), + thread_id); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -252,6 +297,8 @@ } tid_t SBBreakpointLocation::GetThreadID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::tid_t, SBBreakpointLocation, GetThreadID); + tid_t tid = LLDB_INVALID_THREAD_ID; BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { @@ -263,6 +310,9 @@ } void SBBreakpointLocation::SetThreadIndex(uint32_t index) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetThreadIndex, (uint32_t), + index); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -272,6 +322,9 @@ } uint32_t SBBreakpointLocation::GetThreadIndex() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBreakpointLocation, + GetThreadIndex); + uint32_t thread_idx = UINT32_MAX; BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { @@ -283,6 +336,9 @@ } void SBBreakpointLocation::SetThreadName(const char *thread_name) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetThreadName, (const char *), + thread_name); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -292,16 +348,22 @@ } const char *SBBreakpointLocation::GetThreadName() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpointLocation, + GetThreadName); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( loc_sp->GetTarget().GetAPIMutex()); return loc_sp->GetThreadName(); } - return NULL; + return nullptr; } void SBBreakpointLocation::SetQueueName(const char *queue_name) { + LLDB_RECORD_METHOD(void, SBBreakpointLocation, SetQueueName, (const char *), + queue_name); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -311,16 +373,21 @@ } const char *SBBreakpointLocation::GetQueueName() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpointLocation, + GetQueueName); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( loc_sp->GetTarget().GetAPIMutex()); loc_sp->GetQueueName(); } - return NULL; + return nullptr; } bool SBBreakpointLocation::IsResolved() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpointLocation, IsResolved); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -338,6 +405,10 @@ bool SBBreakpointLocation::GetDescription(SBStream &description, DescriptionLevel level) { + LLDB_RECORD_METHOD(bool, SBBreakpointLocation, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + level); + Stream &strm = description.ref(); BreakpointLocationSP loc_sp = GetSP(); @@ -353,6 +424,8 @@ } break_id_t SBBreakpointLocation::GetID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::break_id_t, SBBreakpointLocation, GetID); + BreakpointLocationSP loc_sp = GetSP(); if (loc_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -363,7 +436,9 @@ } SBBreakpoint SBBreakpointLocation::GetBreakpoint() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBreakpoint, SBBreakpointLocation, + GetBreakpoint); + BreakpointLocationSP loc_sp = GetSP(); SBBreakpoint sb_bp; @@ -373,11 +448,68 @@ sb_bp = loc_sp->GetBreakpoint().shared_from_this(); } - if (log) { - SBStream sstr; - sb_bp.GetDescription(sstr); - LLDB_LOG(log, "location = {0}, breakpoint = {1} ({2})", loc_sp.get(), - sb_bp.GetSP().get(), sstr.GetData()); - } - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBBreakpointLocation>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointLocation, ()); + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointLocation, + (const lldb::BreakpointLocationSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointLocation, + (const lldb::SBBreakpointLocation &)); + LLDB_REGISTER_METHOD( + const lldb::SBBreakpointLocation &, + SBBreakpointLocation, operator=,(const lldb::SBBreakpointLocation &)); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpointLocation, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpointLocation, operator bool, ()); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBBreakpointLocation, GetAddress, ()); + LLDB_REGISTER_METHOD(lldb::addr_t, SBBreakpointLocation, GetLoadAddress, + ()); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetEnabled, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpointLocation, IsEnabled, ()); + LLDB_REGISTER_METHOD(uint32_t, SBBreakpointLocation, GetHitCount, ()); + LLDB_REGISTER_METHOD(uint32_t, SBBreakpointLocation, GetIgnoreCount, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetIgnoreCount, + (uint32_t)); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetCondition, + (const char *)); + LLDB_REGISTER_METHOD(const char *, SBBreakpointLocation, GetCondition, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetAutoContinue, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpointLocation, GetAutoContinue, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetScriptCallbackFunction, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBBreakpointLocation, + SetScriptCallbackBody, (const char *)); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetCommandLineCommands, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD(bool, SBBreakpointLocation, GetCommandLineCommands, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetThreadID, + (lldb::tid_t)); + LLDB_REGISTER_METHOD(lldb::tid_t, SBBreakpointLocation, GetThreadID, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetThreadIndex, + (uint32_t)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBreakpointLocation, GetThreadIndex, + ()); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetThreadName, + (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpointLocation, + GetThreadName, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointLocation, SetQueueName, + (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpointLocation, GetQueueName, + ()); + LLDB_REGISTER_METHOD(bool, SBBreakpointLocation, IsResolved, ()); + LLDB_REGISTER_METHOD(bool, SBBreakpointLocation, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD(lldb::break_id_t, SBBreakpointLocation, GetID, ()); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBBreakpointLocation, + GetBreakpoint, ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBBreakpointName.cpp b/src/llvm-project/lldb/source/API/SBBreakpointName.cpp index 47bddd7..1c794fc 100644 --- a/src/llvm-project/lldb/source/API/SBBreakpointName.cpp +++ b/src/llvm-project/lldb/source/API/SBBreakpointName.cpp
@@ -1,13 +1,13 @@ //===-- SBBreakpointName.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBError.h" #include "lldb/API/SBStream.h" @@ -21,7 +21,6 @@ #include "lldb/Interpreter/ScriptInterpreter.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadSpec.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" #include "SBBreakpointOptionCommon.h" @@ -37,10 +36,10 @@ if (!name || name[0] == '\0') return; m_name.assign(name); - + if (!target_sp) return; - + m_target_wp = target_sp; } @@ -50,15 +49,15 @@ // 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(); } @@ -106,10 +105,14 @@ } // namespace lldb -SBBreakpointName::SBBreakpointName() {} +SBBreakpointName::SBBreakpointName() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBBreakpointName); +} -SBBreakpointName::SBBreakpointName(SBTarget &sb_target, const char *name) -{ +SBBreakpointName::SBBreakpointName(SBTarget &sb_target, const char *name) { + LLDB_RECORD_CONSTRUCTOR(SBBreakpointName, (lldb::SBTarget &, const char *), + sb_target, name); + m_impl_up.reset(new SBBreakpointNameImpl(sb_target, name)); // Call FindBreakpointName here to make sure the name is valid, reset if not: BreakpointName *bp_name = GetBreakpointName(); @@ -117,8 +120,10 @@ m_impl_up.reset(); } -SBBreakpointName::SBBreakpointName(SBBreakpoint &sb_bkpt, const char *name) -{ +SBBreakpointName::SBBreakpointName(SBBreakpoint &sb_bkpt, const char *name) { + LLDB_RECORD_CONSTRUCTOR(SBBreakpointName, + (lldb::SBBreakpoint &, const char *), sb_bkpt, name); + if (!sb_bkpt.IsValid()) { m_impl_up.reset(); return; @@ -127,21 +132,23 @@ Target &target = bkpt_sp->GetTarget(); m_impl_up.reset(new 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) -{ +SBBreakpointName::SBBreakpointName(const SBBreakpointName &rhs) { + LLDB_RECORD_CONSTRUCTOR(SBBreakpointName, (const lldb::SBBreakpointName &), + rhs); + if (!rhs.m_impl_up) return; else @@ -151,46 +158,63 @@ SBBreakpointName::~SBBreakpointName() = default; -const SBBreakpointName &SBBreakpointName::operator=(const SBBreakpointName &rhs) -{ +const SBBreakpointName &SBBreakpointName:: +operator=(const SBBreakpointName &rhs) { + LLDB_RECORD_METHOD( + const lldb::SBBreakpointName &, + SBBreakpointName, operator=,(const lldb::SBBreakpointName &), rhs); + if (!rhs.m_impl_up) { m_impl_up.reset(); - return *this; + return LLDB_RECORD_RESULT(*this); } - + m_impl_up.reset(new SBBreakpointNameImpl(rhs.m_impl_up->GetTarget(), rhs.m_impl_up->GetName())); - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBBreakpointName::operator==(const lldb::SBBreakpointName &rhs) { + LLDB_RECORD_METHOD( + bool, SBBreakpointName, operator==,(const lldb::SBBreakpointName &), rhs); + return *m_impl_up == *rhs.m_impl_up; } bool SBBreakpointName::operator!=(const lldb::SBBreakpointName &rhs) { + LLDB_RECORD_METHOD( + bool, SBBreakpointName, operator!=,(const lldb::SBBreakpointName &), rhs); + return *m_impl_up != *rhs.m_impl_up; } bool SBBreakpointName::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpointName, IsValid); + return this->operator bool(); +} +SBBreakpointName::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpointName, operator bool); + if (!m_impl_up) return false; return m_impl_up->IsValid(); } const char *SBBreakpointName::GetName() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpointName, GetName); + if (!m_impl_up) return "<Invalid Breakpoint Name Object>"; return m_impl_up->GetName(); } void SBBreakpointName::SetEnabled(bool enable) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetEnabled, (bool), enable); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} enabled: {1}\n", bp_name->GetName(), enable); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -209,13 +233,12 @@ } bool SBBreakpointName::IsEnabled() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpointName, IsEnabled); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -223,13 +246,12 @@ } void SBBreakpointName::SetOneShot(bool one_shot) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetOneShot, (bool), one_shot); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} one_shot: {1}\n", bp_name->GetName(), one_shot); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -238,13 +260,12 @@ } bool SBBreakpointName::IsOneShot() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpointName, IsOneShot); + const BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -252,13 +273,12 @@ } void SBBreakpointName::SetIgnoreCount(uint32_t count) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetIgnoreCount, (uint32_t), count); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} one_shot: {1}\n", bp_name->GetName(), count); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -267,13 +287,12 @@ } uint32_t SBBreakpointName::GetIgnoreCount() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBreakpointName, GetIgnoreCount); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -281,15 +300,13 @@ } void SBBreakpointName::SetCondition(const char *condition) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetCondition, (const char *), + condition); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} one_shot: {1}\n", bp_name->GetName(), - condition ? condition : "<NULL>"); - + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -298,13 +315,12 @@ } const char *SBBreakpointName::GetCondition() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBBreakpointName, GetCondition); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return nullptr; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -312,14 +328,13 @@ } void SBBreakpointName::SetAutoContinue(bool auto_continue) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetAutoContinue, (bool), + auto_continue); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} auto-continue: {1}\n", bp_name->GetName(), auto_continue); - + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -328,13 +343,12 @@ } bool SBBreakpointName::GetAutoContinue() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpointName, GetAutoContinue); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -342,14 +356,12 @@ } void SBBreakpointName::SetThreadID(tid_t tid) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetThreadID, (lldb::tid_t), tid); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} tid: {1:x}\n", bp_name->GetName(), tid); - + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -358,13 +370,12 @@ } tid_t SBBreakpointName::GetThreadID() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_NO_ARGS(lldb::tid_t, SBBreakpointName, GetThreadID); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return LLDB_INVALID_THREAD_ID; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -372,14 +383,12 @@ } void SBBreakpointName::SetThreadIndex(uint32_t index) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetThreadIndex, (uint32_t), index); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} thread index: {1}\n", bp_name->GetName(), index); - + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -388,13 +397,12 @@ } uint32_t SBBreakpointName::GetThreadIndex() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBBreakpointName, GetThreadIndex); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return LLDB_INVALID_THREAD_ID; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -402,14 +410,13 @@ } void SBBreakpointName::SetThreadName(const char *thread_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetThreadName, (const char *), + thread_name); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} thread name: {1}\n", bp_name->GetName(), thread_name); - + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -418,13 +425,13 @@ } const char *SBBreakpointName::GetThreadName() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpointName, + GetThreadName); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return nullptr; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -432,14 +439,13 @@ } void SBBreakpointName::SetQueueName(const char *queue_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetQueueName, (const char *), + queue_name); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} queue name: {1}\n", bp_name->GetName(), queue_name); - + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -448,13 +454,13 @@ } const char *SBBreakpointName::GetQueueName() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpointName, + GetQueueName); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return nullptr; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -462,14 +468,15 @@ } void SBBreakpointName::SetCommandLineCommands(SBStringList &commands) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpointName, SetCommandLineCommands, + (lldb::SBStringList &), commands); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; if (commands.GetSize() == 0) return; - LLDB_LOG(log, "Name: {0} commands\n", bp_name->GetName()); std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -481,13 +488,13 @@ } bool SBBreakpointName::GetCommandLineCommands(SBStringList &commands) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(bool, SBBreakpointName, GetCommandLineCommands, + (lldb::SBStringList &), commands); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + StringList command_list; bool has_commands = bp_name->GetOptions().GetCommandLineCallbacks(command_list); @@ -497,23 +504,24 @@ } const char *SBBreakpointName::GetHelpString() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBreakpointName, + GetHelpString); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return ""; - - LLDB_LOG(log, "Help: {0}\n", bp_name->GetHelp()); + return bp_name->GetHelp(); } void SBBreakpointName::SetHelpString(const char *help_string) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBreakpointName, SetHelpString, (const char *), + help_string); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - LLDB_LOG(log, "Name: {0} help: {1}\n", bp_name->GetName(), help_string); std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -521,16 +529,16 @@ } bool SBBreakpointName::GetDescription(SBStream &s) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(bool, SBBreakpointName, GetDescription, (lldb::SBStream &), + s); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) { s.Printf("No value"); return false; } - - LLDB_LOG(log, "Name: {0}\n", bp_name->GetName()); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); bp_name->GetDescription(s.get(), eDescriptionLevelFull); @@ -539,11 +547,12 @@ void SBBreakpointName::SetCallback(SBBreakpointHitCallback callback, void *baton) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_DUMMY(void, SBBreakpointName, SetCallback, + (lldb::SBBreakpointHitCallback, void *), callback, baton); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - LLDB_LOG(log, "callback = {1}, baton = {2}", callback, baton); std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -557,39 +566,35 @@ void SBBreakpointName::SetScriptCallbackFunction( const char *callback_function_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - + LLDB_RECORD_METHOD(void, SBBreakpointName, SetScriptCallbackFunction, + (const char *), callback_function_name); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - - LLDB_LOG(log, "Name: {0} callback: {1}\n", bp_name->GetName(), - callback_function_name); - + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); BreakpointOptions &bp_options = bp_name->GetOptions(); m_impl_up->GetTarget() ->GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter() ->SetBreakpointCommandCallbackFunction(&bp_options, callback_function_name); UpdateName(*bp_name); } -SBError SBBreakpointName::SetScriptCallbackBody(const char *callback_body_text) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +SBError +SBBreakpointName::SetScriptCallbackBody(const char *callback_body_text) { + LLDB_RECORD_METHOD(lldb::SBError, SBBreakpointName, SetScriptCallbackBody, + (const char *), callback_body_text); + SBError sb_error; BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) - return sb_error; - - LLDB_LOG(log, "Name: {0} callback: {1}\n", bp_name->GetName(), - callback_body_text); - + return LLDB_RECORD_RESULT(sb_error); + std::lock_guard<std::recursive_mutex> guard( m_impl_up->GetTarget()->GetAPIMutex()); @@ -597,76 +602,68 @@ Status error = m_impl_up->GetTarget() ->GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter() ->SetBreakpointCommandCallback(&bp_options, callback_body_text); sb_error.SetError(error); if (!sb_error.Fail()) UpdateName(*bp_name); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } -bool SBBreakpointName::GetAllowList() const -{ +bool SBBreakpointName::GetAllowList() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBreakpointName, GetAllowList); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; return bp_name->GetPermissions().GetAllowList(); } -void SBBreakpointName::SetAllowList(bool value) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +void SBBreakpointName::SetAllowList(bool value) { + LLDB_RECORD_METHOD(void, SBBreakpointName, SetAllowList, (bool), value); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - if (log) - log->Printf("Setting allow list to %u for %s.", value, - bp_name->GetName().AsCString()); bp_name->GetPermissions().SetAllowList(value); } - -bool SBBreakpointName::GetAllowDelete() -{ + +bool SBBreakpointName::GetAllowDelete() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpointName, GetAllowDelete); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; return bp_name->GetPermissions().GetAllowDelete(); } -void SBBreakpointName::SetAllowDelete(bool value) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +void SBBreakpointName::SetAllowDelete(bool value) { + LLDB_RECORD_METHOD(void, SBBreakpointName, SetAllowDelete, (bool), value); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - if (log) - log->Printf("Setting allow delete to %u for %s.", value, - bp_name->GetName().AsCString()); bp_name->GetPermissions().SetAllowDelete(value); } - -bool SBBreakpointName::GetAllowDisable() -{ + +bool SBBreakpointName::GetAllowDisable() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBBreakpointName, GetAllowDisable); + BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return false; return bp_name->GetPermissions().GetAllowDisable(); } -void SBBreakpointName::SetAllowDisable(bool value) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +void SBBreakpointName::SetAllowDisable(bool value) { + LLDB_RECORD_METHOD(void, SBBreakpointName, SetAllowDisable, (bool), value); BreakpointName *bp_name = GetBreakpointName(); if (!bp_name) return; - if (log) - log->Printf("Setting allow disable to %u for %s.", value, - bp_name->GetName().AsCString()); bp_name->GetPermissions().SetAllowDisable(value); } @@ -677,3 +674,69 @@ return m_impl_up->GetBreakpointName(); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBBreakpointName>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointName, ()); + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointName, + (lldb::SBTarget &, const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointName, + (lldb::SBBreakpoint &, const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBBreakpointName, + (const lldb::SBBreakpointName &)); + LLDB_REGISTER_METHOD( + const lldb::SBBreakpointName &, + SBBreakpointName, operator=,(const lldb::SBBreakpointName &)); + LLDB_REGISTER_METHOD( + bool, SBBreakpointName, operator==,(const lldb::SBBreakpointName &)); + LLDB_REGISTER_METHOD( + bool, SBBreakpointName, operator!=,(const lldb::SBBreakpointName &)); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpointName, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpointName, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpointName, GetName, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetEnabled, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpointName, IsEnabled, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetOneShot, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpointName, IsOneShot, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetIgnoreCount, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBreakpointName, GetIgnoreCount, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetCondition, (const char *)); + LLDB_REGISTER_METHOD(const char *, SBBreakpointName, GetCondition, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetAutoContinue, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpointName, GetAutoContinue, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetThreadID, (lldb::tid_t)); + LLDB_REGISTER_METHOD(lldb::tid_t, SBBreakpointName, GetThreadID, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetThreadIndex, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBBreakpointName, GetThreadIndex, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetThreadName, (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpointName, GetThreadName, + ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetQueueName, (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpointName, GetQueueName, + ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetCommandLineCommands, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD(bool, SBBreakpointName, GetCommandLineCommands, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBreakpointName, GetHelpString, + ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetHelpString, (const char *)); + LLDB_REGISTER_METHOD(bool, SBBreakpointName, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetScriptCallbackFunction, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBBreakpointName, SetScriptCallbackBody, + (const char *)); + LLDB_REGISTER_METHOD_CONST(bool, SBBreakpointName, GetAllowList, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetAllowList, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpointName, GetAllowDelete, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetAllowDelete, (bool)); + LLDB_REGISTER_METHOD(bool, SBBreakpointName, GetAllowDisable, ()); + LLDB_REGISTER_METHOD(void, SBBreakpointName, SetAllowDisable, (bool)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.cpp b/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.cpp index c0618ad..058b3e0 100644 --- a/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.cpp +++ b/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.cpp
@@ -1,9 +1,8 @@ -//===-- SBBreakpointName.cpp ----------------------------------------*- C++ -*-===// +//===-- SBBreakpointOptionCommon.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.h b/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.h index fe276ac..52049e4 100644 --- a/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.h +++ b/src/llvm-project/lldb/source/API/SBBreakpointOptionCommon.h
@@ -1,9 +1,8 @@ //===-- SBBreakpointOptionCommon.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,7 +24,7 @@ SBBreakpointCallbackBaton(SBBreakpointHitCallback callback, void *baton); - ~SBBreakpointCallbackBaton(); + ~SBBreakpointCallbackBaton() override; static bool PrivateBreakpointHitCallback(void *baton, lldb_private::StoppointCallbackContext *ctx,
diff --git a/src/llvm-project/lldb/source/API/SBBroadcaster.cpp b/src/llvm-project/lldb/source/API/SBBroadcaster.cpp index 7868c38..e1efdf7 100644 --- a/src/llvm-project/lldb/source/API/SBBroadcaster.cpp +++ b/src/llvm-project/lldb/source/API/SBBroadcaster.cpp
@@ -1,14 +1,13 @@ //===-- SBBroadcaster.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/Utility/Broadcaster.h" -#include "lldb/Utility/Log.h" #include "lldb/API/SBBroadcaster.h" #include "lldb/API/SBEvent.h" @@ -17,44 +16,44 @@ using namespace lldb; using namespace lldb_private; -SBBroadcaster::SBBroadcaster() : m_opaque_sp(), m_opaque_ptr(NULL) {} +SBBroadcaster::SBBroadcaster() : m_opaque_sp(), m_opaque_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBBroadcaster); +} SBBroadcaster::SBBroadcaster(const char *name) - : m_opaque_sp(new Broadcaster(NULL, name)), m_opaque_ptr(NULL) { + : m_opaque_sp(new Broadcaster(nullptr, name)), m_opaque_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR(SBBroadcaster, (const char *), name); + m_opaque_ptr = m_opaque_sp.get(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOGV(log, "(name=\"{0}\") => SBBroadcaster({1})", name, m_opaque_ptr); } SBBroadcaster::SBBroadcaster(lldb_private::Broadcaster *broadcaster, bool owns) - : m_opaque_sp(owns ? broadcaster : NULL), m_opaque_ptr(broadcaster) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOGV(log, "(broadcaster={0}, owns={1}) => SBBroadcaster({2})", - broadcaster, owns, m_opaque_ptr); -} + : 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) {} + : m_opaque_sp(rhs.m_opaque_sp), m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBBroadcaster, (const lldb::SBBroadcaster &), rhs); +} const SBBroadcaster &SBBroadcaster::operator=(const SBBroadcaster &rhs) { + LLDB_RECORD_METHOD(const lldb::SBBroadcaster &, + SBBroadcaster, operator=,(const lldb::SBBroadcaster &), + rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; m_opaque_ptr = rhs.m_opaque_ptr; } - return *this; + return LLDB_RECORD_RESULT(*this); } -SBBroadcaster::~SBBroadcaster() { reset(NULL, false); } +SBBroadcaster::~SBBroadcaster() { reset(nullptr, false); } void SBBroadcaster::BroadcastEventByType(uint32_t event_type, bool unique) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBroadcaster, BroadcastEventByType, + (uint32_t, bool), event_type, unique); - if (log) - log->Printf("SBBroadcaster(%p)::BroadcastEventByType (event_type=0x%8.8x, " - "unique=%i)", - static_cast<void *>(m_opaque_ptr), event_type, unique); - - if (m_opaque_ptr == NULL) + if (m_opaque_ptr == nullptr) return; if (unique) @@ -64,15 +63,10 @@ } void SBBroadcaster::BroadcastEvent(const SBEvent &event, bool unique) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBBroadcaster, BroadcastEvent, + (const lldb::SBEvent &, bool), event, unique); - if (log) - log->Printf( - "SBBroadcaster(%p)::BroadcastEventByType (SBEvent(%p), unique=%i)", - static_cast<void *>(m_opaque_ptr), static_cast<void *>(event.get()), - unique); - - if (m_opaque_ptr == NULL) + if (m_opaque_ptr == nullptr) return; EventSP event_sp = event.GetSP(); @@ -84,12 +78,10 @@ void SBBroadcaster::AddInitialEventsToListener(const SBListener &listener, uint32_t requested_events) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBBroadcaster(%p)::AddInitialEventsToListener " - "(SBListener(%p), event_mask=0x%8.8x)", - static_cast<void *>(m_opaque_ptr), - static_cast<void *>(listener.get()), requested_events); + LLDB_RECORD_METHOD(void, SBBroadcaster, AddInitialEventsToListener, + (const lldb::SBListener &, uint32_t), listener, + requested_events); + if (m_opaque_ptr) m_opaque_ptr->AddInitialEventsToListener(listener.m_opaque_sp, requested_events); @@ -97,18 +89,27 @@ uint32_t SBBroadcaster::AddListener(const SBListener &listener, uint32_t event_mask) { + LLDB_RECORD_METHOD(uint32_t, SBBroadcaster, AddListener, + (const lldb::SBListener &, uint32_t), 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_RECORD_METHOD_CONST_NO_ARGS(const char *, SBBroadcaster, GetName); + if (m_opaque_ptr) return m_opaque_ptr->GetBroadcasterName().GetCString(); - return NULL; + return nullptr; } bool SBBroadcaster::EventTypeHasListeners(uint32_t event_type) { + LLDB_RECORD_METHOD(bool, SBBroadcaster, EventTypeHasListeners, (uint32_t), + event_type); + if (m_opaque_ptr) return m_opaque_ptr->EventTypeHasListeners(event_type); return false; @@ -116,6 +117,10 @@ bool SBBroadcaster::RemoveListener(const SBListener &listener, uint32_t event_mask) { + LLDB_RECORD_METHOD(bool, SBBroadcaster, RemoveListener, + (const lldb::SBListener &, uint32_t), listener, + event_mask); + if (m_opaque_ptr) return m_opaque_ptr->RemoveListener(listener.m_opaque_sp, event_mask); return false; @@ -131,21 +136,78 @@ m_opaque_ptr = broadcaster; } -bool SBBroadcaster::IsValid() const { return m_opaque_ptr != NULL; } +bool SBBroadcaster::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBroadcaster, IsValid); + return this->operator bool(); +} +SBBroadcaster::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBBroadcaster, operator bool); + + return m_opaque_ptr != nullptr; +} void SBBroadcaster::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBBroadcaster, Clear); + m_opaque_sp.reset(); - m_opaque_ptr = NULL; + m_opaque_ptr = nullptr; } bool SBBroadcaster::operator==(const SBBroadcaster &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBBroadcaster, operator==,(const lldb::SBBroadcaster &), rhs); + return m_opaque_ptr == rhs.m_opaque_ptr; } bool SBBroadcaster::operator!=(const SBBroadcaster &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBBroadcaster, operator!=,(const lldb::SBBroadcaster &), rhs); + return m_opaque_ptr != rhs.m_opaque_ptr; } bool SBBroadcaster::operator<(const SBBroadcaster &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBBroadcaster, operator<,(const lldb::SBBroadcaster &), rhs); + return m_opaque_ptr < rhs.m_opaque_ptr; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBBroadcaster>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBBroadcaster, ()); + LLDB_REGISTER_CONSTRUCTOR(SBBroadcaster, (const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBBroadcaster, (const lldb::SBBroadcaster &)); + LLDB_REGISTER_METHOD( + const lldb::SBBroadcaster &, + SBBroadcaster, operator=,(const lldb::SBBroadcaster &)); + LLDB_REGISTER_METHOD(void, SBBroadcaster, BroadcastEventByType, + (uint32_t, bool)); + LLDB_REGISTER_METHOD(void, SBBroadcaster, BroadcastEvent, + (const lldb::SBEvent &, bool)); + LLDB_REGISTER_METHOD(void, SBBroadcaster, AddInitialEventsToListener, + (const lldb::SBListener &, uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBBroadcaster, AddListener, + (const lldb::SBListener &, uint32_t)); + LLDB_REGISTER_METHOD_CONST(const char *, SBBroadcaster, GetName, ()); + LLDB_REGISTER_METHOD(bool, SBBroadcaster, EventTypeHasListeners, + (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBBroadcaster, RemoveListener, + (const lldb::SBListener &, uint32_t)); + LLDB_REGISTER_METHOD_CONST(bool, SBBroadcaster, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBBroadcaster, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBBroadcaster, Clear, ()); + LLDB_REGISTER_METHOD_CONST( + bool, SBBroadcaster, operator==,(const lldb::SBBroadcaster &)); + LLDB_REGISTER_METHOD_CONST( + bool, SBBroadcaster, operator!=,(const lldb::SBBroadcaster &)); + LLDB_REGISTER_METHOD_CONST( + bool, SBBroadcaster, operator<,(const lldb::SBBroadcaster &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBCommandInterpreter.cpp b/src/llvm-project/lldb/source/API/SBCommandInterpreter.cpp index 2a06e60..c07dffc 100644 --- a/src/llvm-project/lldb/source/API/SBCommandInterpreter.cpp +++ b/src/llvm-project/lldb/source/API/SBCommandInterpreter.cpp
@@ -1,14 +1,14 @@ //===-- SBCommandInterpreter.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Interpreter/CommandReturnObject.h" @@ -26,68 +26,114 @@ #include "lldb/API/SBStringList.h" #include "lldb/API/SBTarget.h" +#include <memory> + using namespace lldb; using namespace lldb_private; SBCommandInterpreterRunOptions::SBCommandInterpreterRunOptions() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBCommandInterpreterRunOptions); + m_opaque_up.reset(new CommandInterpreterRunOptions()); } SBCommandInterpreterRunOptions::~SBCommandInterpreterRunOptions() = default; bool SBCommandInterpreterRunOptions::GetStopOnContinue() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreterRunOptions, + GetStopOnContinue); + return m_opaque_up->GetStopOnContinue(); } void SBCommandInterpreterRunOptions::SetStopOnContinue(bool stop_on_continue) { + LLDB_RECORD_METHOD(void, SBCommandInterpreterRunOptions, SetStopOnContinue, + (bool), stop_on_continue); + m_opaque_up->SetStopOnContinue(stop_on_continue); } bool SBCommandInterpreterRunOptions::GetStopOnError() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreterRunOptions, + GetStopOnError); + return m_opaque_up->GetStopOnError(); } void SBCommandInterpreterRunOptions::SetStopOnError(bool stop_on_error) { + LLDB_RECORD_METHOD(void, SBCommandInterpreterRunOptions, SetStopOnError, + (bool), stop_on_error); + m_opaque_up->SetStopOnError(stop_on_error); } bool SBCommandInterpreterRunOptions::GetStopOnCrash() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreterRunOptions, + GetStopOnCrash); + return m_opaque_up->GetStopOnCrash(); } void SBCommandInterpreterRunOptions::SetStopOnCrash(bool stop_on_crash) { + LLDB_RECORD_METHOD(void, SBCommandInterpreterRunOptions, SetStopOnCrash, + (bool), stop_on_crash); + m_opaque_up->SetStopOnCrash(stop_on_crash); } bool SBCommandInterpreterRunOptions::GetEchoCommands() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreterRunOptions, + GetEchoCommands); + return m_opaque_up->GetEchoCommands(); } void SBCommandInterpreterRunOptions::SetEchoCommands(bool echo_commands) { + LLDB_RECORD_METHOD(void, SBCommandInterpreterRunOptions, SetEchoCommands, + (bool), echo_commands); + m_opaque_up->SetEchoCommands(echo_commands); } bool SBCommandInterpreterRunOptions::GetEchoCommentCommands() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreterRunOptions, + GetEchoCommentCommands); + return m_opaque_up->GetEchoCommentCommands(); } void SBCommandInterpreterRunOptions::SetEchoCommentCommands(bool echo) { + LLDB_RECORD_METHOD(void, SBCommandInterpreterRunOptions, + SetEchoCommentCommands, (bool), echo); + m_opaque_up->SetEchoCommentCommands(echo); } bool SBCommandInterpreterRunOptions::GetPrintResults() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreterRunOptions, + GetPrintResults); + return m_opaque_up->GetPrintResults(); } void SBCommandInterpreterRunOptions::SetPrintResults(bool print_results) { + LLDB_RECORD_METHOD(void, SBCommandInterpreterRunOptions, SetPrintResults, + (bool), print_results); + m_opaque_up->SetPrintResults(print_results); } bool SBCommandInterpreterRunOptions::GetAddToHistory() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreterRunOptions, + GetAddToHistory); + return m_opaque_up->GetAddToHistory(); } void SBCommandInterpreterRunOptions::SetAddToHistory(bool add_to_history) { + LLDB_RECORD_METHOD(void, SBCommandInterpreterRunOptions, SetAddToHistory, + (bool), add_to_history); + m_opaque_up->SetAddToHistory(add_to_history); } @@ -129,47 +175,72 @@ SBCommandInterpreter::SBCommandInterpreter(CommandInterpreter *interpreter) : m_opaque_ptr(interpreter) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_CONSTRUCTOR(SBCommandInterpreter, + (lldb_private::CommandInterpreter *), interpreter); - if (log) - log->Printf("SBCommandInterpreter::SBCommandInterpreter (interpreter=%p)" - " => SBCommandInterpreter(%p)", - static_cast<void *>(interpreter), - static_cast<void *>(m_opaque_ptr)); } SBCommandInterpreter::SBCommandInterpreter(const SBCommandInterpreter &rhs) - : m_opaque_ptr(rhs.m_opaque_ptr) {} + : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBCommandInterpreter, + (const lldb::SBCommandInterpreter &), rhs); +} SBCommandInterpreter::~SBCommandInterpreter() = default; const SBCommandInterpreter &SBCommandInterpreter:: operator=(const SBCommandInterpreter &rhs) { + LLDB_RECORD_METHOD( + const lldb::SBCommandInterpreter &, + SBCommandInterpreter, operator=,(const lldb::SBCommandInterpreter &), + rhs); + m_opaque_ptr = rhs.m_opaque_ptr; - return *this; + return LLDB_RECORD_RESULT(*this); } -bool SBCommandInterpreter::IsValid() const { return m_opaque_ptr != nullptr; } +bool SBCommandInterpreter::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreter, IsValid); + return this->operator bool(); +} +SBCommandInterpreter::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreter, operator bool); + + return m_opaque_ptr != nullptr; +} bool SBCommandInterpreter::CommandExists(const char *cmd) { + LLDB_RECORD_METHOD(bool, SBCommandInterpreter, CommandExists, (const char *), + cmd); + return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->CommandExists(cmd) : false); } bool SBCommandInterpreter::AliasExists(const char *cmd) { + LLDB_RECORD_METHOD(bool, SBCommandInterpreter, AliasExists, (const char *), + cmd); + return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->AliasExists(cmd) : false); } bool SBCommandInterpreter::IsActive() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandInterpreter, IsActive); + return (IsValid() ? m_opaque_ptr->IsActive() : false); } bool SBCommandInterpreter::WasInterrupted() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandInterpreter, WasInterrupted); + return (IsValid() ? m_opaque_ptr->WasInterrupted() : false); } const char *SBCommandInterpreter::GetIOHandlerControlSequence(char ch) { + LLDB_RECORD_METHOD(const char *, SBCommandInterpreter, + GetIOHandlerControlSequence, (char), ch); + return (IsValid() ? m_opaque_ptr->GetDebugger() .GetTopIOHandlerControlSequence(ch) @@ -181,6 +252,10 @@ SBCommandInterpreter::HandleCommand(const char *command_line, SBCommandReturnObject &result, bool add_to_history) { + LLDB_RECORD_METHOD(lldb::ReturnStatus, SBCommandInterpreter, HandleCommand, + (const char *, lldb::SBCommandReturnObject &, bool), + command_line, result, add_to_history); + SBExecutionContext sb_exe_ctx; return HandleCommand(command_line, sb_exe_ctx, result, add_to_history); } @@ -188,13 +263,11 @@ lldb::ReturnStatus SBCommandInterpreter::HandleCommand( const char *command_line, SBExecutionContext &override_context, SBCommandReturnObject &result, bool add_to_history) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::ReturnStatus, SBCommandInterpreter, HandleCommand, + (const char *, lldb::SBExecutionContext &, + lldb::SBCommandReturnObject &, bool), + command_line, override_context, result, add_to_history); - if (log) - log->Printf("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", " - "SBCommandReturnObject(%p), add_to_history=%i)", - static_cast<void *>(m_opaque_ptr), command_line, - static_cast<void *>(result.get()), add_to_history); ExecutionContext ctx, *ctx_ptr; if (override_context.get()) { @@ -215,17 +288,6 @@ result->SetStatus(eReturnStatusFailed); } - // We need to get the value again, in case the command disabled the log! - log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); - if (log) { - SBStream sstr; - result.GetDescription(sstr); - log->Printf("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", " - "SBCommandReturnObject(%p): %s, add_to_history=%i) => %i", - static_cast<void *>(m_opaque_ptr), command_line, - static_cast<void *>(result.get()), sstr.GetData(), - add_to_history, result.GetStatus()); - } return result.GetStatus(); } @@ -234,16 +296,11 @@ lldb::SBFileSpec &file, lldb::SBExecutionContext &override_context, lldb::SBCommandInterpreterRunOptions &options, lldb::SBCommandReturnObject result) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) { - SBStream s; - file.GetDescription(s); - log->Printf("SBCommandInterpreter(%p)::HandleCommandsFromFile " - "(file=\"%s\", SBCommandReturnObject(%p))", - static_cast<void *>(m_opaque_ptr), s.GetData(), - static_cast<void *>(result.get())); - } + LLDB_RECORD_METHOD(void, SBCommandInterpreter, HandleCommandsFromFile, + (lldb::SBFileSpec &, lldb::SBExecutionContext &, + lldb::SBCommandInterpreterRunOptions &, + lldb::SBCommandReturnObject), + file, override_context, options, result); if (!IsValid()) { result->AppendError("SBCommandInterpreter is not valid."); @@ -273,6 +330,12 @@ 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_RECORD_METHOD(int, SBCommandInterpreter, HandleCompletion, + (const char *, const char *, const char *, int, int, + lldb::SBStringList &), + 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, @@ -283,7 +346,13 @@ const char *current_line, const char *cursor, const char *last_char, int match_start_point, int max_return_elements, SBStringList &matches, SBStringList &descriptions) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(int, SBCommandInterpreter, + HandleCompletionWithDescriptions, + (const char *, const char *, const char *, int, int, + lldb::SBStringList &, lldb::SBStringList &), + current_line, cursor, last_char, match_start_point, + max_return_elements, matches, descriptions); + int num_completions = 0; // Sanity check the arguments that are passed in: cursor & last_char have to @@ -299,15 +368,6 @@ last_char - current_line > static_cast<ptrdiff_t>(current_line_size)) return 0; - if (log) - log->Printf("SBCommandInterpreter(%p)::HandleCompletion " - "(current_line=\"%s\", cursor at: %" PRId64 - ", last char at: %" PRId64 - ", match_start_point: %d, max_return_elements: %d)", - static_cast<void *>(m_opaque_ptr), current_line, - static_cast<uint64_t>(cursor - current_line), - static_cast<uint64_t>(last_char - current_line), - match_start_point, max_return_elements); if (IsValid()) { lldb_private::StringList lldb_matches, lldb_descriptions; @@ -320,10 +380,6 @@ SBStringList temp_descriptions_list(&lldb_descriptions); descriptions.AppendList(temp_descriptions_list); } - if (log) - log->Printf( - "SBCommandInterpreter(%p)::HandleCompletion - Found %d completions.", - static_cast<void *>(m_opaque_ptr), num_completions); return num_completions; } @@ -332,6 +388,13 @@ const char *current_line, uint32_t cursor_pos, int match_start_point, int max_return_elements, SBStringList &matches, SBStringList &descriptions) { + LLDB_RECORD_METHOD(int, SBCommandInterpreter, + HandleCompletionWithDescriptions, + (const char *, uint32_t, int, int, lldb::SBStringList &, + lldb::SBStringList &), + 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( @@ -344,6 +407,11 @@ int match_start_point, int max_return_elements, lldb::SBStringList &matches) { + LLDB_RECORD_METHOD(int, SBCommandInterpreter, HandleCompletion, + (const char *, uint32_t, int, int, lldb::SBStringList &), + 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, @@ -351,18 +419,26 @@ } bool SBCommandInterpreter::HasCommands() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandInterpreter, HasCommands); + return (IsValid() ? m_opaque_ptr->HasCommands() : false); } bool SBCommandInterpreter::HasAliases() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandInterpreter, HasAliases); + return (IsValid() ? m_opaque_ptr->HasAliases() : false); } bool SBCommandInterpreter::HasAliasOptions() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandInterpreter, HasAliasOptions); + return (IsValid() ? m_opaque_ptr->HasAliasOptions() : false); } SBProcess SBCommandInterpreter::GetProcess() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBProcess, SBCommandInterpreter, GetProcess); + SBProcess sb_process; ProcessSP process_sp; if (IsValid()) { @@ -373,45 +449,45 @@ sb_process.SetSP(process_sp); } } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBCommandInterpreter(%p)::GetProcess () => SBProcess(%p)", - static_cast<void *>(m_opaque_ptr), - static_cast<void *>(process_sp.get())); - - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } SBDebugger SBCommandInterpreter::GetDebugger() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBDebugger, SBCommandInterpreter, + GetDebugger); + SBDebugger sb_debugger; if (IsValid()) sb_debugger.reset(m_opaque_ptr->GetDebugger().shared_from_this()); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBCommandInterpreter(%p)::GetDebugger () => SBDebugger(%p)", - static_cast<void *>(m_opaque_ptr), - static_cast<void *>(sb_debugger.get())); - - return sb_debugger; + return LLDB_RECORD_RESULT(sb_debugger); } bool SBCommandInterpreter::GetPromptOnQuit() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandInterpreter, GetPromptOnQuit); + return (IsValid() ? m_opaque_ptr->GetPromptOnQuit() : false); } void SBCommandInterpreter::SetPromptOnQuit(bool b) { + LLDB_RECORD_METHOD(void, SBCommandInterpreter, SetPromptOnQuit, (bool), b); + if (IsValid()) m_opaque_ptr->SetPromptOnQuit(b); } void SBCommandInterpreter::AllowExitCodeOnQuit(bool allow) { + LLDB_RECORD_METHOD(void, SBCommandInterpreter, AllowExitCodeOnQuit, (bool), + allow); + if (m_opaque_ptr) m_opaque_ptr->AllowExitCodeOnQuit(allow); } bool SBCommandInterpreter::HasCustomQuitExitCode() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandInterpreter, HasCustomQuitExitCode); + bool exited = false; if (m_opaque_ptr) m_opaque_ptr->GetQuitExitCode(exited); @@ -419,12 +495,18 @@ } int SBCommandInterpreter::GetQuitStatus() { + LLDB_RECORD_METHOD_NO_ARGS(int, SBCommandInterpreter, GetQuitStatus); + bool exited = false; return (m_opaque_ptr ? m_opaque_ptr->GetQuitExitCode(exited) : 0); } void SBCommandInterpreter::ResolveCommand(const char *command_line, SBCommandReturnObject &result) { + LLDB_RECORD_METHOD(void, SBCommandInterpreter, ResolveCommand, + (const char *, lldb::SBCommandReturnObject &), + command_line, result); + result.Clear(); if (command_line && IsValid()) { m_opaque_ptr->ResolveCommand(command_line, result.ref()); @@ -449,78 +531,83 @@ void SBCommandInterpreter::SourceInitFileInHomeDirectory( SBCommandReturnObject &result) { + LLDB_RECORD_METHOD(void, SBCommandInterpreter, SourceInitFileInHomeDirectory, + (lldb::SBCommandReturnObject &), 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->SourceInitFile(false, result.ref()); + m_opaque_ptr->SourceInitFileHome(result.ref()); } else { result->AppendError("SBCommandInterpreter is not valid"); result->SetStatus(eReturnStatusFailed); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf("SBCommandInterpreter(%p)::SourceInitFileInHomeDirectory " - "(&SBCommandReturnObject(%p))", - static_cast<void *>(m_opaque_ptr), - static_cast<void *>(result.get())); } void SBCommandInterpreter::SourceInitFileInCurrentWorkingDirectory( SBCommandReturnObject &result) { + LLDB_RECORD_METHOD(void, SBCommandInterpreter, + SourceInitFileInCurrentWorkingDirectory, + (lldb::SBCommandReturnObject &), 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->SourceInitFile(true, result.ref()); + m_opaque_ptr->SourceInitFileCwd(result.ref()); } else { result->AppendError("SBCommandInterpreter is not valid"); result->SetStatus(eReturnStatusFailed); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf( - "SBCommandInterpreter(%p)::SourceInitFileInCurrentWorkingDirectory " - "(&SBCommandReturnObject(%p))", - static_cast<void *>(m_opaque_ptr), static_cast<void *>(result.get())); } SBBroadcaster SBCommandInterpreter::GetBroadcaster() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBroadcaster, SBCommandInterpreter, + GetBroadcaster); + SBBroadcaster broadcaster(m_opaque_ptr, false); - if (log) - log->Printf( - "SBCommandInterpreter(%p)::GetBroadcaster() => SBBroadcaster(%p)", - static_cast<void *>(m_opaque_ptr), - static_cast<void *>(broadcaster.get())); - return broadcaster; + return LLDB_RECORD_RESULT(broadcaster); } const char *SBCommandInterpreter::GetBroadcasterClass() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBCommandInterpreter, + GetBroadcasterClass); + return CommandInterpreter::GetStaticBroadcasterClass().AsCString(); } const char *SBCommandInterpreter::GetArgumentTypeAsCString( const lldb::CommandArgumentType arg_type) { + LLDB_RECORD_STATIC_METHOD(const char *, SBCommandInterpreter, + GetArgumentTypeAsCString, + (const lldb::CommandArgumentType), arg_type); + return CommandObject::GetArgumentTypeAsCString(arg_type); } const char *SBCommandInterpreter::GetArgumentDescriptionAsCString( const lldb::CommandArgumentType arg_type) { + LLDB_RECORD_STATIC_METHOD(const char *, SBCommandInterpreter, + GetArgumentDescriptionAsCString, + (const lldb::CommandArgumentType), arg_type); + return CommandObject::GetArgumentDescriptionAsCString(arg_type); } bool SBCommandInterpreter::EventIsCommandInterpreterEvent( const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(bool, SBCommandInterpreter, + EventIsCommandInterpreterEvent, + (const lldb::SBEvent &), event); + return event.GetBroadcasterClass() == SBCommandInterpreter::GetBroadcasterClass(); } @@ -528,6 +615,10 @@ bool SBCommandInterpreter::SetCommandOverrideCallback( const char *command_name, lldb::CommandOverrideCallback callback, void *baton) { + LLDB_RECORD_DUMMY(bool, SBCommandInterpreter, SetCommandOverrideCallback, + (const char *, lldb::CommandOverrideCallback, void *), + command_name, callback, baton); + if (command_name && command_name[0] && IsValid()) { llvm::StringRef command_name_str = command_name; CommandObject *cmd_obj = @@ -543,122 +634,310 @@ lldb::SBCommand SBCommandInterpreter::AddMultiwordCommand(const char *name, const char *help) { + LLDB_RECORD_METHOD(lldb::SBCommand, SBCommandInterpreter, AddMultiwordCommand, + (const char *, const char *), name, help); + CommandObjectMultiword *new_command = new CommandObjectMultiword(*m_opaque_ptr, name, help); new_command->SetRemovable(true); lldb::CommandObjectSP new_command_sp(new_command); if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand(new_command_sp)); + return LLDB_RECORD_RESULT(lldb::SBCommand()); } lldb::SBCommand SBCommandInterpreter::AddCommand( const char *name, lldb::SBCommandPluginInterface *impl, const char *help) { + LLDB_RECORD_METHOD( + lldb::SBCommand, SBCommandInterpreter, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, const char *), name, + impl, help); + lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation( - *m_opaque_ptr, name, impl, help)); + new_command_sp = std::make_shared<CommandPluginInterfaceImplementation>( + *m_opaque_ptr, name, impl, help); if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand(new_command_sp)); + return LLDB_RECORD_RESULT(lldb::SBCommand()); } lldb::SBCommand SBCommandInterpreter::AddCommand(const char *name, lldb::SBCommandPluginInterface *impl, const char *help, const char *syntax) { + LLDB_RECORD_METHOD(lldb::SBCommand, SBCommandInterpreter, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, + const char *, const char *), + name, impl, help, syntax); + lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation( - *m_opaque_ptr, name, impl, help, syntax)); + new_command_sp = std::make_shared<CommandPluginInterfaceImplementation>( + *m_opaque_ptr, name, impl, help, syntax); if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand(new_command_sp)); + return LLDB_RECORD_RESULT(lldb::SBCommand()); } -SBCommand::SBCommand() = default; +SBCommand::SBCommand() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBCommand); } SBCommand::SBCommand(lldb::CommandObjectSP cmd_sp) : m_opaque_sp(cmd_sp) {} -bool SBCommand::IsValid() { return m_opaque_sp.get() != nullptr; } +bool SBCommand::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommand, IsValid); + return this->operator bool(); +} +SBCommand::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommand, operator bool); + + return m_opaque_sp.get() != nullptr; +} const char *SBCommand::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBCommand, GetName); + return (IsValid() ? ConstString(m_opaque_sp->GetCommandName()).AsCString() : nullptr); } const char *SBCommand::GetHelp() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBCommand, GetHelp); + return (IsValid() ? ConstString(m_opaque_sp->GetHelp()).AsCString() : nullptr); } const char *SBCommand::GetHelpLong() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBCommand, GetHelpLong); + return (IsValid() ? ConstString(m_opaque_sp->GetHelpLong()).AsCString() : nullptr); } void SBCommand::SetHelp(const char *help) { + LLDB_RECORD_METHOD(void, SBCommand, SetHelp, (const char *), help); + if (IsValid()) m_opaque_sp->SetHelp(help); } void SBCommand::SetHelpLong(const char *help) { + LLDB_RECORD_METHOD(void, SBCommand, SetHelpLong, (const char *), help); + if (IsValid()) m_opaque_sp->SetHelpLong(help); } lldb::SBCommand SBCommand::AddMultiwordCommand(const char *name, const char *help) { + LLDB_RECORD_METHOD(lldb::SBCommand, SBCommand, AddMultiwordCommand, + (const char *, const char *), name, help); + if (!IsValid()) - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand()); if (!m_opaque_sp->IsMultiwordObject()) - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(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(); + return LLDB_RECORD_RESULT(lldb::SBCommand(new_command_sp)); + return LLDB_RECORD_RESULT(lldb::SBCommand()); } lldb::SBCommand SBCommand::AddCommand(const char *name, lldb::SBCommandPluginInterface *impl, const char *help) { + LLDB_RECORD_METHOD( + lldb::SBCommand, SBCommand, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, const char *), name, + impl, help); + if (!IsValid()) - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand()); if (!m_opaque_sp->IsMultiwordObject()) - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand()); lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation( - m_opaque_sp->GetCommandInterpreter(), name, impl, help)); + new_command_sp = std::make_shared<CommandPluginInterfaceImplementation>( + m_opaque_sp->GetCommandInterpreter(), name, impl, help); if (new_command_sp && m_opaque_sp->LoadSubCommand(name, new_command_sp)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand(new_command_sp)); + return LLDB_RECORD_RESULT(lldb::SBCommand()); } lldb::SBCommand SBCommand::AddCommand(const char *name, lldb::SBCommandPluginInterface *impl, const char *help, const char *syntax) { + LLDB_RECORD_METHOD(lldb::SBCommand, SBCommand, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, + const char *, const char *), + name, impl, help, syntax); + if (!IsValid()) - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand()); if (!m_opaque_sp->IsMultiwordObject()) - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand()); lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation( - m_opaque_sp->GetCommandInterpreter(), name, impl, help, syntax)); + new_command_sp = std::make_shared<CommandPluginInterfaceImplementation>( + m_opaque_sp->GetCommandInterpreter(), name, impl, help, syntax); if (new_command_sp && m_opaque_sp->LoadSubCommand(name, new_command_sp)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); + return LLDB_RECORD_RESULT(lldb::SBCommand(new_command_sp)); + return LLDB_RECORD_RESULT(lldb::SBCommand()); } uint32_t SBCommand::GetFlags() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBCommand, GetFlags); + return (IsValid() ? m_opaque_sp->GetFlags().Get() : 0); } void SBCommand::SetFlags(uint32_t flags) { + LLDB_RECORD_METHOD(void, SBCommand, SetFlags, (uint32_t), flags); + if (IsValid()) m_opaque_sp->GetFlags().Set(flags); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBCommandInterpreterRunOptions>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBCommandInterpreterRunOptions, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreterRunOptions, + GetStopOnContinue, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreterRunOptions, + SetStopOnContinue, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreterRunOptions, + GetStopOnError, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreterRunOptions, SetStopOnError, + (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreterRunOptions, + GetStopOnCrash, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreterRunOptions, SetStopOnCrash, + (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreterRunOptions, + GetEchoCommands, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreterRunOptions, SetEchoCommands, + (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreterRunOptions, + GetEchoCommentCommands, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreterRunOptions, + SetEchoCommentCommands, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreterRunOptions, + GetPrintResults, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreterRunOptions, SetPrintResults, + (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreterRunOptions, + GetAddToHistory, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreterRunOptions, SetAddToHistory, + (bool)); + LLDB_REGISTER_CONSTRUCTOR(SBCommandInterpreter, + (lldb_private::CommandInterpreter *)); + LLDB_REGISTER_CONSTRUCTOR(SBCommandInterpreter, + (const lldb::SBCommandInterpreter &)); + LLDB_REGISTER_METHOD( + const lldb::SBCommandInterpreter &, + SBCommandInterpreter, operator=,(const lldb::SBCommandInterpreter &)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreter, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreter, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, CommandExists, + (const char *)); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, AliasExists, + (const char *)); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, IsActive, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandInterpreter, WasInterrupted, ()); + LLDB_REGISTER_METHOD(const char *, SBCommandInterpreter, + GetIOHandlerControlSequence, (char)); + LLDB_REGISTER_METHOD(lldb::ReturnStatus, SBCommandInterpreter, + HandleCommand, + (const char *, lldb::SBCommandReturnObject &, bool)); + LLDB_REGISTER_METHOD(lldb::ReturnStatus, SBCommandInterpreter, + HandleCommand, + (const char *, lldb::SBExecutionContext &, + lldb::SBCommandReturnObject &, bool)); + LLDB_REGISTER_METHOD(void, SBCommandInterpreter, HandleCommandsFromFile, + (lldb::SBFileSpec &, lldb::SBExecutionContext &, + lldb::SBCommandInterpreterRunOptions &, + lldb::SBCommandReturnObject)); + LLDB_REGISTER_METHOD(int, SBCommandInterpreter, HandleCompletion, + (const char *, const char *, const char *, int, int, + lldb::SBStringList &)); + LLDB_REGISTER_METHOD(int, SBCommandInterpreter, + HandleCompletionWithDescriptions, + (const char *, const char *, const char *, int, int, + lldb::SBStringList &, lldb::SBStringList &)); + LLDB_REGISTER_METHOD(int, SBCommandInterpreter, + HandleCompletionWithDescriptions, + (const char *, uint32_t, int, int, + lldb::SBStringList &, lldb::SBStringList &)); + LLDB_REGISTER_METHOD( + int, SBCommandInterpreter, HandleCompletion, + (const char *, uint32_t, int, int, lldb::SBStringList &)); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, HasCommands, ()); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, HasAliases, ()); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, HasAliasOptions, ()); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBCommandInterpreter, GetProcess, ()); + LLDB_REGISTER_METHOD(lldb::SBDebugger, SBCommandInterpreter, GetDebugger, + ()); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, GetPromptOnQuit, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreter, SetPromptOnQuit, (bool)); + LLDB_REGISTER_METHOD(void, SBCommandInterpreter, AllowExitCodeOnQuit, + (bool)); + LLDB_REGISTER_METHOD(bool, SBCommandInterpreter, HasCustomQuitExitCode, ()); + LLDB_REGISTER_METHOD(int, SBCommandInterpreter, GetQuitStatus, ()); + LLDB_REGISTER_METHOD(void, SBCommandInterpreter, ResolveCommand, + (const char *, lldb::SBCommandReturnObject &)); + LLDB_REGISTER_METHOD(void, SBCommandInterpreter, + SourceInitFileInHomeDirectory, + (lldb::SBCommandReturnObject &)); + LLDB_REGISTER_METHOD(void, SBCommandInterpreter, + SourceInitFileInCurrentWorkingDirectory, + (lldb::SBCommandReturnObject &)); + LLDB_REGISTER_METHOD(lldb::SBBroadcaster, SBCommandInterpreter, + GetBroadcaster, ()); + LLDB_REGISTER_STATIC_METHOD(const char *, SBCommandInterpreter, + GetBroadcasterClass, ()); + LLDB_REGISTER_STATIC_METHOD(const char *, SBCommandInterpreter, + GetArgumentTypeAsCString, + (const lldb::CommandArgumentType)); + LLDB_REGISTER_STATIC_METHOD(const char *, SBCommandInterpreter, + GetArgumentDescriptionAsCString, + (const lldb::CommandArgumentType)); + LLDB_REGISTER_STATIC_METHOD(bool, SBCommandInterpreter, + EventIsCommandInterpreterEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_METHOD(lldb::SBCommand, SBCommandInterpreter, + AddMultiwordCommand, (const char *, const char *)); + LLDB_REGISTER_METHOD( + lldb::SBCommand, SBCommandInterpreter, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, const char *)); + LLDB_REGISTER_METHOD(lldb::SBCommand, SBCommandInterpreter, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, + const char *, const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBCommand, ()); + LLDB_REGISTER_METHOD(bool, SBCommand, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCommand, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBCommand, GetName, ()); + LLDB_REGISTER_METHOD(const char *, SBCommand, GetHelp, ()); + LLDB_REGISTER_METHOD(const char *, SBCommand, GetHelpLong, ()); + LLDB_REGISTER_METHOD(void, SBCommand, SetHelp, (const char *)); + LLDB_REGISTER_METHOD(void, SBCommand, SetHelpLong, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBCommand, SBCommand, AddMultiwordCommand, + (const char *, const char *)); + LLDB_REGISTER_METHOD( + lldb::SBCommand, SBCommand, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, const char *)); + LLDB_REGISTER_METHOD(lldb::SBCommand, SBCommand, AddCommand, + (const char *, lldb::SBCommandPluginInterface *, + const char *, const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBCommand, GetFlags, ()); + LLDB_REGISTER_METHOD(void, SBCommand, SetFlags, (uint32_t)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBCommandReturnObject.cpp b/src/llvm-project/lldb/source/API/SBCommandReturnObject.cpp index 7bc0298..94e8991 100644 --- a/src/llvm-project/lldb/source/API/SBCommandReturnObject.cpp +++ b/src/llvm-project/lldb/source/API/SBCommandReturnObject.cpp
@@ -1,105 +1,113 @@ //===-- SBCommandReturnObject.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBError.h" #include "lldb/API/SBStream.h" - #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; SBCommandReturnObject::SBCommandReturnObject() - : m_opaque_ap(new CommandReturnObject()) {} + : m_opaque_up(new CommandReturnObject()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBCommandReturnObject); +} SBCommandReturnObject::SBCommandReturnObject(const SBCommandReturnObject &rhs) - : m_opaque_ap() { - if (rhs.m_opaque_ap) - m_opaque_ap.reset(new CommandReturnObject(*rhs.m_opaque_ap)); + : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBCommandReturnObject, + (const lldb::SBCommandReturnObject &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBCommandReturnObject::SBCommandReturnObject(CommandReturnObject *ptr) - : m_opaque_ap(ptr) {} + : m_opaque_up(ptr) { + LLDB_RECORD_CONSTRUCTOR(SBCommandReturnObject, + (lldb_private::CommandReturnObject *), ptr); +} SBCommandReturnObject::~SBCommandReturnObject() = default; CommandReturnObject *SBCommandReturnObject::Release() { - return m_opaque_ap.release(); + LLDB_RECORD_METHOD_NO_ARGS(lldb_private::CommandReturnObject *, + SBCommandReturnObject, Release); + + return LLDB_RECORD_RESULT(m_opaque_up.release()); } const SBCommandReturnObject &SBCommandReturnObject:: operator=(const SBCommandReturnObject &rhs) { - if (this != &rhs) { - if (rhs.m_opaque_ap) - m_opaque_ap.reset(new CommandReturnObject(*rhs.m_opaque_ap)); - else - m_opaque_ap.reset(); - } - return *this; + LLDB_RECORD_METHOD( + const lldb::SBCommandReturnObject &, + SBCommandReturnObject, operator=,(const lldb::SBCommandReturnObject &), + rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } -bool SBCommandReturnObject::IsValid() const { return m_opaque_ap != nullptr; } +bool SBCommandReturnObject::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandReturnObject, IsValid); + return this->operator bool(); +} +SBCommandReturnObject::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommandReturnObject, operator bool); + + return m_opaque_up != nullptr; +} const char *SBCommandReturnObject::GetOutput() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBCommandReturnObject, GetOutput); - if (m_opaque_ap) { - llvm::StringRef output = m_opaque_ap->GetOutputData(); + if (m_opaque_up) { + llvm::StringRef output = m_opaque_up->GetOutputData(); ConstString result(output.empty() ? llvm::StringRef("") : output); - if (log) - log->Printf("SBCommandReturnObject(%p)::GetOutput () => \"%s\"", - static_cast<void *>(m_opaque_ap.get()), result.AsCString()); - return result.AsCString(); } - if (log) - log->Printf("SBCommandReturnObject(%p)::GetOutput () => nullptr", - static_cast<void *>(m_opaque_ap.get())); - return nullptr; } const char *SBCommandReturnObject::GetError() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBCommandReturnObject, GetError); - if (m_opaque_ap) { - llvm::StringRef output = m_opaque_ap->GetErrorData(); + if (m_opaque_up) { + llvm::StringRef output = m_opaque_up->GetErrorData(); ConstString result(output.empty() ? llvm::StringRef("") : output); - if (log) - log->Printf("SBCommandReturnObject(%p)::GetError () => \"%s\"", - static_cast<void *>(m_opaque_ap.get()), result.AsCString()); - return result.AsCString(); } - if (log) - log->Printf("SBCommandReturnObject(%p)::GetError () => nullptr", - static_cast<void *>(m_opaque_ap.get())); - return nullptr; } size_t SBCommandReturnObject::GetOutputSize() { - return (m_opaque_ap ? m_opaque_ap->GetOutputData().size() : 0); + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBCommandReturnObject, GetOutputSize); + + return (m_opaque_up ? m_opaque_up->GetOutputData().size() : 0); } size_t SBCommandReturnObject::GetErrorSize() { - return (m_opaque_ap ? m_opaque_ap->GetErrorData().size() : 0); + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBCommandReturnObject, GetErrorSize); + + return (m_opaque_up ? m_opaque_up->GetErrorData().size() : 0); } size_t SBCommandReturnObject::PutOutput(FILE *fh) { + LLDB_RECORD_METHOD(size_t, SBCommandReturnObject, PutOutput, (FILE *), fh); + if (fh) { size_t num_bytes = GetOutputSize(); if (num_bytes) @@ -109,6 +117,8 @@ } size_t SBCommandReturnObject::PutError(FILE *fh) { + LLDB_RECORD_METHOD(size_t, SBCommandReturnObject, PutError, (FILE *), fh); + if (fh) { size_t num_bytes = GetErrorSize(); if (num_bytes) @@ -118,71 +128,92 @@ } void SBCommandReturnObject::Clear() { - if (m_opaque_ap) - m_opaque_ap->Clear(); + LLDB_RECORD_METHOD_NO_ARGS(void, SBCommandReturnObject, Clear); + + if (m_opaque_up) + m_opaque_up->Clear(); } lldb::ReturnStatus SBCommandReturnObject::GetStatus() { - return (m_opaque_ap ? m_opaque_ap->GetStatus() : lldb::eReturnStatusInvalid); + LLDB_RECORD_METHOD_NO_ARGS(lldb::ReturnStatus, SBCommandReturnObject, + GetStatus); + + return (m_opaque_up ? m_opaque_up->GetStatus() : lldb::eReturnStatusInvalid); } void SBCommandReturnObject::SetStatus(lldb::ReturnStatus status) { - if (m_opaque_ap) - m_opaque_ap->SetStatus(status); + LLDB_RECORD_METHOD(void, SBCommandReturnObject, SetStatus, + (lldb::ReturnStatus), status); + + if (m_opaque_up) + m_opaque_up->SetStatus(status); } bool SBCommandReturnObject::Succeeded() { - return (m_opaque_ap ? m_opaque_ap->Succeeded() : false); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandReturnObject, Succeeded); + + return (m_opaque_up ? m_opaque_up->Succeeded() : false); } bool SBCommandReturnObject::HasResult() { - return (m_opaque_ap ? m_opaque_ap->HasResult() : false); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommandReturnObject, HasResult); + + return (m_opaque_up ? m_opaque_up->HasResult() : false); } void SBCommandReturnObject::AppendMessage(const char *message) { - if (m_opaque_ap) - m_opaque_ap->AppendMessage(message); + LLDB_RECORD_METHOD(void, SBCommandReturnObject, AppendMessage, (const char *), + message); + + if (m_opaque_up) + m_opaque_up->AppendMessage(message); } void SBCommandReturnObject::AppendWarning(const char *message) { - if (m_opaque_ap) - m_opaque_ap->AppendWarning(message); + LLDB_RECORD_METHOD(void, SBCommandReturnObject, AppendWarning, (const char *), + message); + + if (m_opaque_up) + m_opaque_up->AppendWarning(message); } CommandReturnObject *SBCommandReturnObject::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } CommandReturnObject *SBCommandReturnObject::get() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } CommandReturnObject &SBCommandReturnObject::operator*() const { - assert(m_opaque_ap.get()); - return *(m_opaque_ap.get()); + assert(m_opaque_up.get()); + return *(m_opaque_up.get()); } CommandReturnObject &SBCommandReturnObject::ref() const { - assert(m_opaque_ap.get()); - return *(m_opaque_ap.get()); + assert(m_opaque_up.get()); + return *(m_opaque_up.get()); } void SBCommandReturnObject::SetLLDBObjectPtr(CommandReturnObject *ptr) { - if (m_opaque_ap) - m_opaque_ap.reset(ptr); + if (m_opaque_up) + m_opaque_up.reset(ptr); } bool SBCommandReturnObject::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBCommandReturnObject, GetDescription, + (lldb::SBStream &), description); + Stream &strm = description.ref(); - if (m_opaque_ap) { + if (m_opaque_up) { description.Printf("Error: "); - lldb::ReturnStatus status = m_opaque_ap->GetStatus(); + lldb::ReturnStatus status = m_opaque_up->GetStatus(); if (status == lldb::eReturnStatusStarted) strm.PutCString("Started"); else if (status == lldb::eReturnStatusInvalid) strm.PutCString("Invalid"); - else if (m_opaque_ap->Succeeded()) + else if (m_opaque_up->Succeeded()) strm.PutCString("Success"); else strm.PutCString("Fail"); @@ -199,60 +230,81 @@ } void SBCommandReturnObject::SetImmediateOutputFile(FILE *fh) { + LLDB_RECORD_METHOD(void, SBCommandReturnObject, SetImmediateOutputFile, + (FILE *), fh); + SetImmediateOutputFile(fh, false); } void SBCommandReturnObject::SetImmediateErrorFile(FILE *fh) { + LLDB_RECORD_METHOD(void, SBCommandReturnObject, SetImmediateErrorFile, + (FILE *), fh); + SetImmediateErrorFile(fh, false); } void SBCommandReturnObject::SetImmediateOutputFile(FILE *fh, bool transfer_ownership) { - if (m_opaque_ap) - m_opaque_ap->SetImmediateOutputFile(fh, transfer_ownership); + LLDB_RECORD_METHOD(void, SBCommandReturnObject, SetImmediateOutputFile, + (FILE *, bool), fh, transfer_ownership); + + if (m_opaque_up) + m_opaque_up->SetImmediateOutputFile(fh, transfer_ownership); } void SBCommandReturnObject::SetImmediateErrorFile(FILE *fh, bool transfer_ownership) { - if (m_opaque_ap) - m_opaque_ap->SetImmediateErrorFile(fh, transfer_ownership); + LLDB_RECORD_METHOD(void, SBCommandReturnObject, SetImmediateErrorFile, + (FILE *, bool), fh, transfer_ownership); + + if (m_opaque_up) + m_opaque_up->SetImmediateErrorFile(fh, transfer_ownership); } void SBCommandReturnObject::PutCString(const char *string, int len) { - if (m_opaque_ap) { + LLDB_RECORD_METHOD(void, SBCommandReturnObject, PutCString, + (const char *, int), string, len); + + if (m_opaque_up) { if (len == 0 || string == nullptr || *string == 0) { return; } else if (len > 0) { std::string buffer(string, len); - m_opaque_ap->AppendMessage(buffer.c_str()); + m_opaque_up->AppendMessage(buffer.c_str()); } else - m_opaque_ap->AppendMessage(string); + m_opaque_up->AppendMessage(string); } } const char *SBCommandReturnObject::GetOutput(bool only_if_no_immediate) { - if (!m_opaque_ap) + LLDB_RECORD_METHOD(const char *, SBCommandReturnObject, GetOutput, (bool), + only_if_no_immediate); + + if (!m_opaque_up) return nullptr; if (!only_if_no_immediate || - m_opaque_ap->GetImmediateOutputStream().get() == nullptr) + m_opaque_up->GetImmediateOutputStream().get() == nullptr) return GetOutput(); return nullptr; } const char *SBCommandReturnObject::GetError(bool only_if_no_immediate) { - if (!m_opaque_ap) + LLDB_RECORD_METHOD(const char *, SBCommandReturnObject, GetError, (bool), + only_if_no_immediate); + + if (!m_opaque_up) return nullptr; if (!only_if_no_immediate || - m_opaque_ap->GetImmediateErrorStream().get() == nullptr) + m_opaque_up->GetImmediateErrorStream().get() == nullptr) return GetError(); return nullptr; } size_t SBCommandReturnObject::Printf(const char *format, ...) { - if (m_opaque_ap) { + if (m_opaque_up) { va_list args; va_start(args, format); - size_t result = m_opaque_ap->GetOutputStream().PrintfVarArg(format, args); + size_t result = m_opaque_up->GetOutputStream().PrintfVarArg(format, args); va_end(args); return result; } @@ -261,15 +313,79 @@ void SBCommandReturnObject::SetError(lldb::SBError &error, const char *fallback_error_cstr) { - if (m_opaque_ap) { + LLDB_RECORD_METHOD(void, SBCommandReturnObject, SetError, + (lldb::SBError &, const char *), error, + fallback_error_cstr); + + if (m_opaque_up) { if (error.IsValid()) - m_opaque_ap->SetError(error.ref(), fallback_error_cstr); + m_opaque_up->SetError(error.ref(), fallback_error_cstr); else if (fallback_error_cstr) - m_opaque_ap->SetError(Status(), fallback_error_cstr); + m_opaque_up->SetError(Status(), fallback_error_cstr); } } void SBCommandReturnObject::SetError(const char *error_cstr) { - if (m_opaque_ap && error_cstr) - m_opaque_ap->SetError(error_cstr); + LLDB_RECORD_METHOD(void, SBCommandReturnObject, SetError, (const char *), + error_cstr); + + if (m_opaque_up && error_cstr) + m_opaque_up->SetError(error_cstr); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBCommandReturnObject>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBCommandReturnObject, ()); + LLDB_REGISTER_CONSTRUCTOR(SBCommandReturnObject, + (const lldb::SBCommandReturnObject &)); + LLDB_REGISTER_CONSTRUCTOR(SBCommandReturnObject, + (lldb_private::CommandReturnObject *)); + LLDB_REGISTER_METHOD(lldb_private::CommandReturnObject *, + SBCommandReturnObject, Release, ()); + LLDB_REGISTER_METHOD( + const lldb::SBCommandReturnObject &, + SBCommandReturnObject, operator=,(const lldb::SBCommandReturnObject &)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandReturnObject, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCommandReturnObject, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBCommandReturnObject, GetOutput, ()); + LLDB_REGISTER_METHOD(const char *, SBCommandReturnObject, GetError, ()); + LLDB_REGISTER_METHOD(size_t, SBCommandReturnObject, GetOutputSize, ()); + LLDB_REGISTER_METHOD(size_t, SBCommandReturnObject, GetErrorSize, ()); + LLDB_REGISTER_METHOD(size_t, SBCommandReturnObject, PutOutput, (FILE *)); + LLDB_REGISTER_METHOD(size_t, SBCommandReturnObject, PutError, (FILE *)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, Clear, ()); + LLDB_REGISTER_METHOD(lldb::ReturnStatus, SBCommandReturnObject, GetStatus, + ()); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, SetStatus, + (lldb::ReturnStatus)); + LLDB_REGISTER_METHOD(bool, SBCommandReturnObject, Succeeded, ()); + LLDB_REGISTER_METHOD(bool, SBCommandReturnObject, HasResult, ()); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, AppendMessage, + (const char *)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, AppendWarning, + (const char *)); + LLDB_REGISTER_METHOD(bool, SBCommandReturnObject, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, SetImmediateOutputFile, + (FILE *)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, SetImmediateErrorFile, + (FILE *)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, SetImmediateOutputFile, + (FILE *, bool)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, SetImmediateErrorFile, + (FILE *, bool)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, PutCString, + (const char *, int)); + LLDB_REGISTER_METHOD(const char *, SBCommandReturnObject, GetOutput, + (bool)); + LLDB_REGISTER_METHOD(const char *, SBCommandReturnObject, GetError, (bool)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, SetError, + (lldb::SBError &, const char *)); + LLDB_REGISTER_METHOD(void, SBCommandReturnObject, SetError, (const char *)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBCommunication.cpp b/src/llvm-project/lldb/source/API/SBCommunication.cpp index 63b672e..90df70b 100644 --- a/src/llvm-project/lldb/source/API/SBCommunication.cpp +++ b/src/llvm-project/lldb/source/API/SBCommunication.cpp
@@ -1,65 +1,77 @@ //===-- SBCommunication.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBBroadcaster.h" #include "lldb/Core/Communication.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/Host.h" -#include "lldb/Utility/Log.h" using namespace lldb; using namespace lldb_private; -SBCommunication::SBCommunication() : m_opaque(NULL), m_opaque_owned(false) {} +SBCommunication::SBCommunication() : m_opaque(nullptr), m_opaque_owned(false) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBCommunication); +} SBCommunication::SBCommunication(const char *broadcaster_name) : m_opaque(new Communication(broadcaster_name)), m_opaque_owned(true) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf("SBCommunication::SBCommunication (broadcaster_name=\"%s\") => " - "SBCommunication(%p)", - broadcaster_name, static_cast<void *>(m_opaque)); + LLDB_RECORD_CONSTRUCTOR(SBCommunication, (const char *), broadcaster_name); } SBCommunication::~SBCommunication() { if (m_opaque && m_opaque_owned) delete m_opaque; - m_opaque = NULL; + m_opaque = nullptr; m_opaque_owned = false; } -bool SBCommunication::IsValid() const { return m_opaque != NULL; } +bool SBCommunication::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommunication, IsValid); + return this->operator bool(); +} +SBCommunication::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommunication, operator bool); + + return m_opaque != nullptr; +} bool SBCommunication::GetCloseOnEOF() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommunication, GetCloseOnEOF); + if (m_opaque) return m_opaque->GetCloseOnEOF(); return false; } void SBCommunication::SetCloseOnEOF(bool b) { + LLDB_RECORD_METHOD(void, SBCommunication, SetCloseOnEOF, (bool), b); + if (m_opaque) m_opaque->SetCloseOnEOF(b); } ConnectionStatus SBCommunication::Connect(const char *url) { + LLDB_RECORD_METHOD(lldb::ConnectionStatus, SBCommunication, Connect, + (const char *), url); + if (m_opaque) { if (!m_opaque->HasConnection()) m_opaque->SetConnection(Host::CreateDefaultConnection(url).release()); - return m_opaque->Connect(url, NULL); + return m_opaque->Connect(url, nullptr); } return eConnectionStatusNoConnection; } ConnectionStatus SBCommunication::AdoptFileDesriptor(int fd, bool owns_fd) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::ConnectionStatus, SBCommunication, + AdoptFileDesriptor, (int, bool), fd, owns_fd); ConnectionStatus status = eConnectionStatusNoConnection; if (m_opaque) { @@ -73,183 +85,131 @@ else status = eConnectionStatusLostConnection; } - - if (log) - log->Printf( - "SBCommunication(%p)::AdoptFileDescriptor (fd=%d, ownd_fd=%i) => %s", - static_cast<void *>(m_opaque), fd, owns_fd, - Communication::ConnectionStatusAsCString(status)); - return status; } ConnectionStatus SBCommunication::Disconnect() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::ConnectionStatus, SBCommunication, + Disconnect); ConnectionStatus status = eConnectionStatusNoConnection; if (m_opaque) status = m_opaque->Disconnect(); - - if (log) - log->Printf("SBCommunication(%p)::Disconnect () => %s", - static_cast<void *>(m_opaque), - Communication::ConnectionStatusAsCString(status)); - return status; } bool SBCommunication::IsConnected() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - bool result = false; - if (m_opaque) - result = m_opaque->IsConnected(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCommunication, IsConnected); - if (log) - log->Printf("SBCommunication(%p)::IsConnected () => %i", - static_cast<void *>(m_opaque), result); - - return false; + return m_opaque ? m_opaque->IsConnected() : false; } size_t SBCommunication::Read(void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBCommunication(%p)::Read (dst=%p, dst_len=%" PRIu64 - ", timeout_usec=%u, &status)...", - static_cast<void *>(m_opaque), static_cast<void *>(dst), - static_cast<uint64_t>(dst_len), timeout_usec); + LLDB_RECORD_DUMMY(size_t, SBCommunication, Read, + (void *, size_t, uint32_t, lldb::ConnectionStatus &), dst, + dst_len, timeout_usec, status); + size_t bytes_read = 0; Timeout<std::micro> timeout = timeout_usec == UINT32_MAX ? Timeout<std::micro>(llvm::None) : std::chrono::microseconds(timeout_usec); if (m_opaque) - bytes_read = m_opaque->Read(dst, dst_len, timeout, status, NULL); + bytes_read = m_opaque->Read(dst, dst_len, timeout, status, nullptr); else status = eConnectionStatusNoConnection; - if (log) - log->Printf("SBCommunication(%p)::Read (dst=%p, dst_len=%" PRIu64 - ", timeout_usec=%u, &status=%s) => %" PRIu64, - static_cast<void *>(m_opaque), static_cast<void *>(dst), - static_cast<uint64_t>(dst_len), timeout_usec, - Communication::ConnectionStatusAsCString(status), - static_cast<uint64_t>(bytes_read)); return bytes_read; } size_t SBCommunication::Write(const void *src, size_t src_len, ConnectionStatus &status) { + LLDB_RECORD_DUMMY(size_t, SBCommunication, Write, + (const void *, size_t, lldb::ConnectionStatus &), src, + src_len, status); + size_t bytes_written = 0; if (m_opaque) - bytes_written = m_opaque->Write(src, src_len, status, NULL); + bytes_written = m_opaque->Write(src, src_len, status, nullptr); else status = eConnectionStatusNoConnection; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBCommunication(%p)::Write (src=%p, src_len=%" PRIu64 - ", &status=%s) => %" PRIu64, - static_cast<void *>(m_opaque), static_cast<const void *>(src), - static_cast<uint64_t>(src_len), - Communication::ConnectionStatusAsCString(status), - static_cast<uint64_t>(bytes_written)); - - return 0; + return bytes_written; } bool SBCommunication::ReadThreadStart() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommunication, ReadThreadStart); - bool success = false; - if (m_opaque) - success = m_opaque->StartReadThread(); - - if (log) - log->Printf("SBCommunication(%p)::ReadThreadStart () => %i", - static_cast<void *>(m_opaque), success); - - return success; + return m_opaque ? m_opaque->StartReadThread() : false; } bool SBCommunication::ReadThreadStop() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBCommunication(%p)::ReadThreadStop ()...", - static_cast<void *>(m_opaque)); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommunication, ReadThreadStop); - bool success = false; - if (m_opaque) - success = m_opaque->StopReadThread(); - - if (log) - log->Printf("SBCommunication(%p)::ReadThreadStop () => %i", - static_cast<void *>(m_opaque), success); - - return success; + return m_opaque ? m_opaque->StopReadThread() : false; } bool SBCommunication::ReadThreadIsRunning() { - bool result = false; - if (m_opaque) - result = m_opaque->ReadThreadIsRunning(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBCommunication(%p)::ReadThreadIsRunning () => %i", - static_cast<void *>(m_opaque), result); - return result; + LLDB_RECORD_METHOD_NO_ARGS(bool, SBCommunication, ReadThreadIsRunning); + + return m_opaque ? m_opaque->ReadThreadIsRunning() : false; } bool SBCommunication::SetReadThreadBytesReceivedCallback( ReadThreadBytesReceived callback, void *callback_baton) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_DUMMY(bool, SBCommunication, SetReadThreadBytesReceivedCallback, + (lldb::SBCommunication::ReadThreadBytesReceived, void *), + callback, callback_baton); bool result = false; if (m_opaque) { m_opaque->SetReadThreadBytesReceivedCallback(callback, callback_baton); result = true; } - - if (log) - log->Printf("SBCommunication(%p)::SetReadThreadBytesReceivedCallback " - "(callback=%p, baton=%p) => %i", - static_cast<void *>(m_opaque), - reinterpret_cast<void *>(reinterpret_cast<intptr_t>(callback)), - static_cast<void *>(callback_baton), result); - return result; } SBBroadcaster SBCommunication::GetBroadcaster() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBroadcaster, SBCommunication, + GetBroadcaster); + SBBroadcaster broadcaster(m_opaque, false); - - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf("SBCommunication(%p)::GetBroadcaster () => SBBroadcaster (%p)", - static_cast<void *>(m_opaque), - static_cast<void *>(broadcaster.get())); - - return broadcaster; + return LLDB_RECORD_RESULT(broadcaster); } const char *SBCommunication::GetBroadcasterClass() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBCommunication, + GetBroadcasterClass); + return Communication::GetStaticBroadcasterClass().AsCString(); } -// -// void -// SBCommunication::CreateIfNeeded () -//{ -// if (m_opaque == NULL) -// { -// static uint32_t g_broadcaster_num; -// char broadcaster_name[256]; -// ::snprintf (name, broadcaster_name, "%p SBCommunication", this); -// m_opaque = new Communication (broadcaster_name); -// m_opaque_owned = true; -// } -// assert (m_opaque); -//} -// -// +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBCommunication>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBCommunication, ()); + LLDB_REGISTER_CONSTRUCTOR(SBCommunication, (const char *)); + LLDB_REGISTER_METHOD_CONST(bool, SBCommunication, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCommunication, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBCommunication, GetCloseOnEOF, ()); + LLDB_REGISTER_METHOD(void, SBCommunication, SetCloseOnEOF, (bool)); + LLDB_REGISTER_METHOD(lldb::ConnectionStatus, SBCommunication, Connect, + (const char *)); + LLDB_REGISTER_METHOD(lldb::ConnectionStatus, SBCommunication, + AdoptFileDesriptor, (int, bool)); + LLDB_REGISTER_METHOD(lldb::ConnectionStatus, SBCommunication, Disconnect, + ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCommunication, IsConnected, ()); + LLDB_REGISTER_METHOD(bool, SBCommunication, ReadThreadStart, ()); + LLDB_REGISTER_METHOD(bool, SBCommunication, ReadThreadStop, ()); + LLDB_REGISTER_METHOD(bool, SBCommunication, ReadThreadIsRunning, ()); + LLDB_REGISTER_METHOD(lldb::SBBroadcaster, SBCommunication, GetBroadcaster, + ()); + LLDB_REGISTER_STATIC_METHOD(const char *, SBCommunication, + GetBroadcasterClass, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBCompileUnit.cpp b/src/llvm-project/lldb/source/API/SBCompileUnit.cpp index 4e2fc6a..c9ca706 100644 --- a/src/llvm-project/lldb/source/API/SBCompileUnit.cpp +++ b/src/llvm-project/lldb/source/API/SBCompileUnit.cpp
@@ -1,13 +1,13 @@ //===-- SBCompileUnit.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBLineEntry.h" #include "lldb/API/SBStream.h" #include "lldb/Core/Module.h" @@ -16,44 +16,58 @@ #include "lldb/Symbol/LineTable.h" #include "lldb/Symbol/SymbolVendor.h" #include "lldb/Symbol/Type.h" -#include "lldb/Utility/Log.h" using namespace lldb; using namespace lldb_private; -SBCompileUnit::SBCompileUnit() : m_opaque_ptr(NULL) {} +SBCompileUnit::SBCompileUnit() : m_opaque_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBCompileUnit); +} 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) {} - -const SBCompileUnit &SBCompileUnit::operator=(const SBCompileUnit &rhs) { - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; + : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBCompileUnit, (const lldb::SBCompileUnit &), rhs); } -SBCompileUnit::~SBCompileUnit() { m_opaque_ptr = NULL; } +const SBCompileUnit &SBCompileUnit::operator=(const SBCompileUnit &rhs) { + LLDB_RECORD_METHOD(const lldb::SBCompileUnit &, + SBCompileUnit, operator=,(const lldb::SBCompileUnit &), + rhs); + + m_opaque_ptr = rhs.m_opaque_ptr; + return LLDB_RECORD_RESULT(*this); +} + +SBCompileUnit::~SBCompileUnit() { m_opaque_ptr = nullptr; } SBFileSpec SBCompileUnit::GetFileSpec() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBCompileUnit, + GetFileSpec); + SBFileSpec file_spec; if (m_opaque_ptr) file_spec.SetFileSpec(*m_opaque_ptr); - return file_spec; + return LLDB_RECORD_RESULT(file_spec); } uint32_t SBCompileUnit::GetNumLineEntries() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBCompileUnit, GetNumLineEntries); + if (m_opaque_ptr) { LineTable *line_table = m_opaque_ptr->GetLineTable(); - if (line_table) + if (line_table) { return line_table->GetSize(); + } } return 0; } SBLineEntry SBCompileUnit::GetLineEntryAtIndex(uint32_t idx) const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(lldb::SBLineEntry, SBCompileUnit, + GetLineEntryAtIndex, (uint32_t), idx); SBLineEntry sb_line_entry; if (m_opaque_ptr) { @@ -65,20 +79,15 @@ } } - if (log) { - SBStream sstr; - sb_line_entry.GetDescription(sstr); - log->Printf("SBCompileUnit(%p)::GetLineEntryAtIndex (idx=%u) => " - "SBLineEntry(%p): '%s'", - static_cast<void *>(m_opaque_ptr), idx, - static_cast<void *>(sb_line_entry.get()), sstr.GetData()); - } - - return sb_line_entry; + return LLDB_RECORD_RESULT(sb_line_entry); } uint32_t SBCompileUnit::FindLineEntryIndex(uint32_t start_idx, uint32_t line, SBFileSpec *inline_file_spec) const { + LLDB_RECORD_METHOD_CONST(uint32_t, SBCompileUnit, FindLineEntryIndex, + (uint32_t, uint32_t, lldb::SBFileSpec *), start_idx, + line, inline_file_spec); + const bool exact = true; return FindLineEntryIndex(start_idx, line, inline_file_spec, exact); } @@ -86,7 +95,9 @@ uint32_t SBCompileUnit::FindLineEntryIndex(uint32_t start_idx, uint32_t line, SBFileSpec *inline_file_spec, bool exact) const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(uint32_t, SBCompileUnit, FindLineEntryIndex, + (uint32_t, uint32_t, lldb::SBFileSpec *, bool), + start_idx, line, inline_file_spec, exact); uint32_t index = UINT32_MAX; if (m_opaque_ptr) { @@ -97,107 +108,103 @@ file_spec = *m_opaque_ptr; index = m_opaque_ptr->FindLineEntry( - start_idx, line, inline_file_spec ? inline_file_spec->get() : NULL, - exact, NULL); - } - - if (log) { - SBStream sstr; - if (index == UINT32_MAX) { - log->Printf("SBCompileUnit(%p)::FindLineEntryIndex (start_idx=%u, " - "line=%u, SBFileSpec(%p)) => NOT FOUND", - static_cast<void *>(m_opaque_ptr), start_idx, line, - inline_file_spec - ? static_cast<const void *>(inline_file_spec->get()) - : NULL); - } else { - log->Printf("SBCompileUnit(%p)::FindLineEntryIndex (start_idx=%u, " - "line=%u, SBFileSpec(%p)) => %u", - static_cast<void *>(m_opaque_ptr), start_idx, line, - inline_file_spec - ? static_cast<const void *>(inline_file_spec->get()) - : NULL, - index); - } + start_idx, line, inline_file_spec ? inline_file_spec->get() : nullptr, + exact, nullptr); } return index; } uint32_t SBCompileUnit::GetNumSupportFiles() const { - if (m_opaque_ptr) { - FileSpecList &support_files = m_opaque_ptr->GetSupportFiles(); - return support_files.GetSize(); - } + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBCompileUnit, GetNumSupportFiles); + + if (m_opaque_ptr) + return m_opaque_ptr->GetSupportFiles().GetSize(); + return 0; } lldb::SBTypeList SBCompileUnit::GetTypes(uint32_t type_mask) { + LLDB_RECORD_METHOD(lldb::SBTypeList, SBCompileUnit, GetTypes, (uint32_t), + type_mask); + SBTypeList sb_type_list; if (!m_opaque_ptr) - return sb_type_list; + return LLDB_RECORD_RESULT(sb_type_list); ModuleSP module_sp(m_opaque_ptr->GetModule()); if (!module_sp) - return sb_type_list; + return LLDB_RECORD_RESULT(sb_type_list); SymbolVendor *vendor = module_sp->GetSymbolVendor(); if (!vendor) - return sb_type_list; + return LLDB_RECORD_RESULT(sb_type_list); TypeClass type_class = static_cast<TypeClass>(type_mask); TypeList type_list; vendor->GetTypes(m_opaque_ptr, type_class, type_list); - sb_type_list.m_opaque_ap->Append(type_list); - return sb_type_list; + sb_type_list.m_opaque_up->Append(type_list); + return LLDB_RECORD_RESULT(sb_type_list); } SBFileSpec SBCompileUnit::GetSupportFileAtIndex(uint32_t idx) const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(lldb::SBFileSpec, SBCompileUnit, + GetSupportFileAtIndex, (uint32_t), idx); SBFileSpec sb_file_spec; if (m_opaque_ptr) { - FileSpecList &support_files = m_opaque_ptr->GetSupportFiles(); - FileSpec file_spec = support_files.GetFileSpecAtIndex(idx); - sb_file_spec.SetFileSpec(file_spec); + FileSpec spec = m_opaque_ptr->GetSupportFiles().GetFileSpecAtIndex(idx); + sb_file_spec.SetFileSpec(spec); } - if (log) { - SBStream sstr; - sb_file_spec.GetDescription(sstr); - log->Printf("SBCompileUnit(%p)::GetGetFileSpecAtIndex (idx=%u) => " - "SBFileSpec(%p): '%s'", - static_cast<void *>(m_opaque_ptr), idx, - static_cast<const void *>(sb_file_spec.get()), sstr.GetData()); - } - return sb_file_spec; + return LLDB_RECORD_RESULT(sb_file_spec); } uint32_t SBCompileUnit::FindSupportFileIndex(uint32_t start_idx, const SBFileSpec &sb_file, bool full) { + LLDB_RECORD_METHOD(uint32_t, SBCompileUnit, FindSupportFileIndex, + (uint32_t, const lldb::SBFileSpec &, bool), start_idx, + sb_file, full); + if (m_opaque_ptr) { - FileSpecList &support_files = m_opaque_ptr->GetSupportFiles(); + const FileSpecList &support_files = m_opaque_ptr->GetSupportFiles(); return support_files.FindFileIndex(start_idx, sb_file.ref(), full); } return 0; } lldb::LanguageType SBCompileUnit::GetLanguage() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::LanguageType, SBCompileUnit, GetLanguage); + if (m_opaque_ptr) return m_opaque_ptr->GetLanguage(); return lldb::eLanguageTypeUnknown; } -bool SBCompileUnit::IsValid() const { return m_opaque_ptr != NULL; } +bool SBCompileUnit::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCompileUnit, IsValid); + return this->operator bool(); +} +SBCompileUnit::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBCompileUnit, operator bool); + + return m_opaque_ptr != nullptr; +} bool SBCompileUnit::operator==(const SBCompileUnit &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBCompileUnit, operator==,(const lldb::SBCompileUnit &), rhs); + return m_opaque_ptr == rhs.m_opaque_ptr; } bool SBCompileUnit::operator!=(const SBCompileUnit &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBCompileUnit, operator!=,(const lldb::SBCompileUnit &), rhs); + return m_opaque_ptr != rhs.m_opaque_ptr; } @@ -216,6 +223,9 @@ } bool SBCompileUnit::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBCompileUnit, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); if (m_opaque_ptr) { @@ -225,3 +235,42 @@ return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBCompileUnit>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBCompileUnit, ()); + LLDB_REGISTER_CONSTRUCTOR(SBCompileUnit, (const lldb::SBCompileUnit &)); + LLDB_REGISTER_METHOD( + const lldb::SBCompileUnit &, + SBCompileUnit, operator=,(const lldb::SBCompileUnit &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBCompileUnit, GetFileSpec, + ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBCompileUnit, GetNumLineEntries, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBLineEntry, SBCompileUnit, + GetLineEntryAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBCompileUnit, FindLineEntryIndex, + (uint32_t, uint32_t, lldb::SBFileSpec *)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBCompileUnit, FindLineEntryIndex, + (uint32_t, uint32_t, lldb::SBFileSpec *, bool)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBCompileUnit, GetNumSupportFiles, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeList, SBCompileUnit, GetTypes, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBCompileUnit, + GetSupportFileAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBCompileUnit, FindSupportFileIndex, + (uint32_t, const lldb::SBFileSpec &, bool)); + LLDB_REGISTER_METHOD(lldb::LanguageType, SBCompileUnit, GetLanguage, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCompileUnit, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBCompileUnit, operator bool, ()); + LLDB_REGISTER_METHOD_CONST( + bool, SBCompileUnit, operator==,(const lldb::SBCompileUnit &)); + LLDB_REGISTER_METHOD_CONST( + bool, SBCompileUnit, operator!=,(const lldb::SBCompileUnit &)); + LLDB_REGISTER_METHOD(bool, SBCompileUnit, GetDescription, + (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBData.cpp b/src/llvm-project/lldb/source/API/SBData.cpp index a30a778..528cd8d 100644 --- a/src/llvm-project/lldb/source/API/SBData.cpp +++ b/src/llvm-project/lldb/source/API/SBData.cpp
@@ -1,37 +1,44 @@ //===-- SBData.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <inttypes.h> - #include "lldb/API/SBData.h" +#include "SBReproducerPrivate.h" #include "lldb/API/SBError.h" #include "lldb/API/SBStream.h" #include "lldb/Core/DumpDataExtractor.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" +#include <cinttypes> +#include <memory> + using namespace lldb; using namespace lldb_private; -SBData::SBData() : m_opaque_sp(new DataExtractor()) {} +SBData::SBData() : m_opaque_sp(new DataExtractor()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBData); +} SBData::SBData(const lldb::DataExtractorSP &data_sp) : m_opaque_sp(data_sp) {} -SBData::SBData(const SBData &rhs) : m_opaque_sp(rhs.m_opaque_sp) {} +SBData::SBData(const SBData &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBData, (const lldb::SBData &), rhs); +} const SBData &SBData::operator=(const SBData &rhs) { + LLDB_RECORD_METHOD(const lldb::SBData &, + SBData, operator=,(const lldb::SBData &), rhs); + if (this != &rhs) m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBData::~SBData() {} @@ -50,67 +57,69 @@ const lldb::DataExtractorSP &SBData::operator*() const { return m_opaque_sp; } -bool SBData::IsValid() { return m_opaque_sp.get() != NULL; } +bool SBData::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBData, IsValid); + return this->operator bool(); +} +SBData::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBData, operator bool); + + return m_opaque_sp.get() != nullptr; +} uint8_t SBData::GetAddressByteSize() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(uint8_t, SBData, GetAddressByteSize); + uint8_t value = 0; if (m_opaque_sp.get()) value = m_opaque_sp->GetAddressByteSize(); - if (log) - log->Printf("SBData::GetAddressByteSize () => " - "(%i)", - value); return value; } void SBData::SetAddressByteSize(uint8_t addr_byte_size) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBData, SetAddressByteSize, (uint8_t), + addr_byte_size); + if (m_opaque_sp.get()) m_opaque_sp->SetAddressByteSize(addr_byte_size); - if (log) - log->Printf("SBData::SetAddressByteSize (%i)", addr_byte_size); } void SBData::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBData, Clear); + if (m_opaque_sp.get()) m_opaque_sp->Clear(); } size_t SBData::GetByteSize() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBData, GetByteSize); + size_t value = 0; if (m_opaque_sp.get()) value = m_opaque_sp->GetByteSize(); - if (log) - log->Printf("SBData::GetByteSize () => " - "( %" PRIu64 " )", - (uint64_t)value); return value; } lldb::ByteOrder SBData::GetByteOrder() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::ByteOrder, SBData, GetByteOrder); + lldb::ByteOrder value = eByteOrderInvalid; if (m_opaque_sp.get()) value = m_opaque_sp->GetByteOrder(); - if (log) - log->Printf("SBData::GetByteOrder () => " - "(%i)", - value); return value; } void SBData::SetByteOrder(lldb::ByteOrder endian) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBData, SetByteOrder, (lldb::ByteOrder), endian); + if (m_opaque_sp.get()) m_opaque_sp->SetByteOrder(endian); - if (log) - log->Printf("SBData::GetByteOrder (%i)", endian); } float SBData::GetFloat(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(float, SBData, GetFloat, (lldb::SBError &, lldb::offset_t), + error, offset); + float value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -120,14 +129,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetFloat (error=%p,offset=%" PRIu64 ") => (%f)", - static_cast<void *>(error.get()), offset, value); return value; } double SBData::GetDouble(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(double, SBData, GetDouble, + (lldb::SBError &, lldb::offset_t), error, offset); + double value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -137,15 +145,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetDouble (error=%p,offset=%" PRIu64 ") => " - "(%f)", - static_cast<void *>(error.get()), offset, value); return value; } long double SBData::GetLongDouble(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(long double, SBData, GetLongDouble, + (lldb::SBError &, lldb::offset_t), error, offset); + long double value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -155,15 +161,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetLongDouble (error=%p,offset=%" PRIu64 ") => " - "(%Lf)", - static_cast<void *>(error.get()), offset, value); return value; } lldb::addr_t SBData::GetAddress(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::addr_t, SBData, GetAddress, + (lldb::SBError &, lldb::offset_t), error, offset); + lldb::addr_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -173,16 +177,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetAddress (error=%p,offset=%" PRIu64 ") => " - "(%p)", - static_cast<void *>(error.get()), offset, - reinterpret_cast<void *>(value)); return value; } uint8_t SBData::GetUnsignedInt8(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(uint8_t, SBData, GetUnsignedInt8, + (lldb::SBError &, lldb::offset_t), error, offset); + uint8_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -192,15 +193,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetUnsignedInt8 (error=%p,offset=%" PRIu64 ") => " - "(%c)", - static_cast<void *>(error.get()), offset, value); return value; } uint16_t SBData::GetUnsignedInt16(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(uint16_t, SBData, GetUnsignedInt16, + (lldb::SBError &, lldb::offset_t), error, offset); + uint16_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -210,15 +209,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetUnsignedInt16 (error=%p,offset=%" PRIu64 ") => " - "(%hd)", - static_cast<void *>(error.get()), offset, value); return value; } uint32_t SBData::GetUnsignedInt32(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(uint32_t, SBData, GetUnsignedInt32, + (lldb::SBError &, lldb::offset_t), error, offset); + uint32_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -228,15 +225,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetUnsignedInt32 (error=%p,offset=%" PRIu64 ") => " - "(%d)", - static_cast<void *>(error.get()), offset, value); return value; } uint64_t SBData::GetUnsignedInt64(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(uint64_t, SBData, GetUnsignedInt64, + (lldb::SBError &, lldb::offset_t), error, offset); + uint64_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -246,15 +241,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetUnsignedInt64 (error=%p,offset=%" PRIu64 ") => " - "(%" PRId64 ")", - static_cast<void *>(error.get()), offset, value); return value; } int8_t SBData::GetSignedInt8(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(int8_t, SBData, GetSignedInt8, + (lldb::SBError &, lldb::offset_t), error, offset); + int8_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -264,15 +257,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetSignedInt8 (error=%p,offset=%" PRIu64 ") => " - "(%c)", - static_cast<void *>(error.get()), offset, value); return value; } int16_t SBData::GetSignedInt16(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(int16_t, SBData, GetSignedInt16, + (lldb::SBError &, lldb::offset_t), error, offset); + int16_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -282,15 +273,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetSignedInt16 (error=%p,offset=%" PRIu64 ") => " - "(%hd)", - static_cast<void *>(error.get()), offset, value); return value; } int32_t SBData::GetSignedInt32(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(int32_t, SBData, GetSignedInt32, + (lldb::SBError &, lldb::offset_t), error, offset); + int32_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -300,15 +289,13 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetSignedInt32 (error=%p,offset=%" PRIu64 ") => " - "(%d)", - static_cast<void *>(error.get()), offset, value); return value; } int64_t SBData::GetSignedInt64(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(int64_t, SBData, GetSignedInt64, + (lldb::SBError &, lldb::offset_t), error, offset); + int64_t value = 0; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); @@ -318,33 +305,30 @@ if (offset == old_offset) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetSignedInt64 (error=%p,offset=%" PRIu64 ") => " - "(%" PRId64 ")", - static_cast<void *>(error.get()), offset, value); return value; } const char *SBData::GetString(lldb::SBError &error, lldb::offset_t offset) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *value = 0; + LLDB_RECORD_METHOD(const char *, SBData, GetString, + (lldb::SBError &, lldb::offset_t), error, offset); + + const char *value = nullptr; if (!m_opaque_sp.get()) { error.SetErrorString("no value to read from"); } else { uint32_t old_offset = offset; value = m_opaque_sp->GetCStr(&offset); - if (offset == old_offset || (value == NULL)) + if (offset == old_offset || (value == nullptr)) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::GetString (error=%p,offset=%" PRIu64 ") => (%p)", - static_cast<void *>(error.get()), offset, - static_cast<const void *>(value)); return value; } bool SBData::GetDescription(lldb::SBStream &description, lldb::addr_t base_addr) { + LLDB_RECORD_METHOD(bool, SBData, GetDescription, + (lldb::SBStream &, lldb::addr_t), description, base_addr); + Stream &strm = description.ref(); if (m_opaque_sp) { @@ -358,62 +342,56 @@ size_t SBData::ReadRawData(lldb::SBError &error, lldb::offset_t offset, void *buf, size_t size) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - void *ok = NULL; + LLDB_RECORD_DUMMY(size_t, SBData, ReadRawData, + (lldb::SBError &, lldb::offset_t, void *, size_t), 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 == NULL)) + if ((offset == old_offset) || (ok == nullptr)) error.SetErrorString("unable to read data"); } - if (log) - log->Printf("SBData::ReadRawData (error=%p,offset=%" PRIu64 - ",buf=%p,size=%" PRIu64 ") => " - "(%p)", - static_cast<void *>(error.get()), offset, - static_cast<void *>(buf), static_cast<uint64_t>(size), - static_cast<void *>(ok)); return ok ? size : 0; } void SBData::SetData(lldb::SBError &error, const void *buf, size_t size, lldb::ByteOrder endian, uint8_t addr_size) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_DUMMY( + void, SBData, SetData, + (lldb::SBError &, const void *, size_t, lldb::ByteOrder, uint8_t), error, + buf, size, endian, addr_size); + if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buf, size, endian, addr_size)); + 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); } - - if (log) - log->Printf("SBData::SetData (error=%p,buf=%p,size=%" PRIu64 - ",endian=%d,addr_size=%c) => " - "(%p)", - static_cast<void *>(error.get()), - static_cast<const void *>(buf), static_cast<uint64_t>(size), - endian, addr_size, static_cast<void *>(m_opaque_sp.get())); } bool SBData::Append(const SBData &rhs) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBData, Append, (const lldb::SBData &), rhs); + bool value = false; if (m_opaque_sp.get() && rhs.m_opaque_sp.get()) value = m_opaque_sp.get()->Append(*rhs.m_opaque_sp); - if (log) - log->Printf("SBData::Append (rhs=%p) => (%s)", - static_cast<void *>(rhs.get()), value ? "true" : "false"); return value; } lldb::SBData SBData::CreateDataFromCString(lldb::ByteOrder endian, uint32_t addr_byte_size, const char *data) { + LLDB_RECORD_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromCString, + (lldb::ByteOrder, uint32_t, const char *), endian, + addr_byte_size, data); + if (!data || !data[0]) - return SBData(); + return LLDB_RECORD_RESULT(SBData()); uint32_t data_len = strlen(data); @@ -423,15 +401,19 @@ SBData ret(data_sp); - return ret; + return LLDB_RECORD_RESULT(ret); } lldb::SBData SBData::CreateDataFromUInt64Array(lldb::ByteOrder endian, uint32_t addr_byte_size, uint64_t *array, size_t array_len) { + LLDB_RECORD_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromUInt64Array, + (lldb::ByteOrder, uint32_t, uint64_t *, size_t), + endian, addr_byte_size, array, array_len); + if (!array || array_len == 0) - return SBData(); + return LLDB_RECORD_RESULT(SBData()); size_t data_len = array_len * sizeof(uint64_t); @@ -441,15 +423,19 @@ SBData ret(data_sp); - return ret; + return LLDB_RECORD_RESULT(ret); } lldb::SBData SBData::CreateDataFromUInt32Array(lldb::ByteOrder endian, uint32_t addr_byte_size, uint32_t *array, size_t array_len) { + LLDB_RECORD_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromUInt32Array, + (lldb::ByteOrder, uint32_t, uint32_t *, size_t), + endian, addr_byte_size, array, array_len); + if (!array || array_len == 0) - return SBData(); + return LLDB_RECORD_RESULT(SBData()); size_t data_len = array_len * sizeof(uint32_t); @@ -459,15 +445,19 @@ SBData ret(data_sp); - return ret; + return LLDB_RECORD_RESULT(ret); } lldb::SBData SBData::CreateDataFromSInt64Array(lldb::ByteOrder endian, uint32_t addr_byte_size, int64_t *array, size_t array_len) { + LLDB_RECORD_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromSInt64Array, + (lldb::ByteOrder, uint32_t, int64_t *, size_t), + endian, addr_byte_size, array, array_len); + if (!array || array_len == 0) - return SBData(); + return LLDB_RECORD_RESULT(SBData()); size_t data_len = array_len * sizeof(int64_t); @@ -477,15 +467,19 @@ SBData ret(data_sp); - return ret; + return LLDB_RECORD_RESULT(ret); } lldb::SBData SBData::CreateDataFromSInt32Array(lldb::ByteOrder endian, uint32_t addr_byte_size, int32_t *array, size_t array_len) { + LLDB_RECORD_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromSInt32Array, + (lldb::ByteOrder, uint32_t, int32_t *, size_t), + endian, addr_byte_size, array, array_len); + if (!array || array_len == 0) - return SBData(); + return LLDB_RECORD_RESULT(SBData()); size_t data_len = array_len * sizeof(int32_t); @@ -495,15 +489,19 @@ SBData ret(data_sp); - return ret; + return LLDB_RECORD_RESULT(ret); } lldb::SBData SBData::CreateDataFromDoubleArray(lldb::ByteOrder endian, uint32_t addr_byte_size, double *array, size_t array_len) { + LLDB_RECORD_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromDoubleArray, + (lldb::ByteOrder, uint32_t, double *, size_t), + endian, addr_byte_size, array, array_len); + if (!array || array_len == 0) - return SBData(); + return LLDB_RECORD_RESULT(SBData()); size_t data_len = array_len * sizeof(double); @@ -513,16 +511,14 @@ SBData ret(data_sp); - return ret; + return LLDB_RECORD_RESULT(ret); } bool SBData::SetDataFromCString(const char *data) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBData, SetDataFromCString, (const char *), data); + if (!data) { - if (log) - log->Printf("SBData::SetDataFromCString (data=%p) => false", - static_cast<const void *>(data)); return false; } @@ -531,28 +527,21 @@ lldb::DataBufferSP buffer_sp(new DataBufferHeap(data, data_len)); if (!m_opaque_sp.get()) - m_opaque_sp.reset( - new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); else m_opaque_sp->SetData(buffer_sp); - if (log) - log->Printf("SBData::SetDataFromCString (data=%p) => true", - static_cast<const void *>(data)); return true; } bool SBData::SetDataFromUInt64Array(uint64_t *array, size_t array_len) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBData, SetDataFromUInt64Array, (uint64_t *, size_t), + array, array_len); + if (!array || array_len == 0) { - if (log) - log->Printf( - "SBData::SetDataFromUInt64Array (array=%p, array_len = %" PRIu64 - ") => " - "false", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); return false; } @@ -561,30 +550,21 @@ lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); if (!m_opaque_sp.get()) - m_opaque_sp.reset( - new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); else m_opaque_sp->SetData(buffer_sp); - if (log) - log->Printf("SBData::SetDataFromUInt64Array (array=%p, array_len = %" PRIu64 - ") => " - "true", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); return true; } bool SBData::SetDataFromUInt32Array(uint32_t *array, size_t array_len) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBData, SetDataFromUInt32Array, (uint32_t *, size_t), + array, array_len); + if (!array || array_len == 0) { - if (log) - log->Printf( - "SBData::SetDataFromUInt32Array (array=%p, array_len = %" PRIu64 - ") => " - "false", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); return false; } @@ -593,30 +573,20 @@ lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); if (!m_opaque_sp.get()) - m_opaque_sp.reset( - new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); else m_opaque_sp->SetData(buffer_sp); - if (log) - log->Printf("SBData::SetDataFromUInt32Array (array=%p, array_len = %" PRIu64 - ") => " - "true", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); - return true; } bool SBData::SetDataFromSInt64Array(int64_t *array, size_t array_len) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBData, SetDataFromSInt64Array, (int64_t *, size_t), + array, array_len); + if (!array || array_len == 0) { - if (log) - log->Printf( - "SBData::SetDataFromSInt64Array (array=%p, array_len = %" PRIu64 - ") => " - "false", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); return false; } @@ -625,30 +595,20 @@ lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); if (!m_opaque_sp.get()) - m_opaque_sp.reset( - new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); else m_opaque_sp->SetData(buffer_sp); - if (log) - log->Printf("SBData::SetDataFromSInt64Array (array=%p, array_len = %" PRIu64 - ") => " - "true", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); - return true; } bool SBData::SetDataFromSInt32Array(int32_t *array, size_t array_len) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBData, SetDataFromSInt32Array, (int32_t *, size_t), + array, array_len); + if (!array || array_len == 0) { - if (log) - log->Printf( - "SBData::SetDataFromSInt32Array (array=%p, array_len = %" PRIu64 - ") => " - "false", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); return false; } @@ -657,30 +617,20 @@ lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); if (!m_opaque_sp.get()) - m_opaque_sp.reset( - new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); else m_opaque_sp->SetData(buffer_sp); - if (log) - log->Printf("SBData::SetDataFromSInt32Array (array=%p, array_len = %" PRIu64 - ") => " - "true", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); - return true; } bool SBData::SetDataFromDoubleArray(double *array, size_t array_len) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBData, SetDataFromDoubleArray, (double *, size_t), + array, array_len); + if (!array || array_len == 0) { - if (log) - log->Printf( - "SBData::SetDataFromDoubleArray (array=%p, array_len = %" PRIu64 - ") => " - "false", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); return false; } @@ -689,16 +639,86 @@ lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); if (!m_opaque_sp.get()) - m_opaque_sp.reset( - new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); else m_opaque_sp->SetData(buffer_sp); - if (log) - log->Printf("SBData::SetDataFromDoubleArray (array=%p, array_len = %" PRIu64 - ") => " - "true", - static_cast<void *>(array), static_cast<uint64_t>(array_len)); - return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBData>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBData, ()); + LLDB_REGISTER_CONSTRUCTOR(SBData, (const lldb::SBData &)); + LLDB_REGISTER_METHOD(const lldb::SBData &, + SBData, operator=,(const lldb::SBData &)); + LLDB_REGISTER_METHOD(bool, SBData, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBData, operator bool, ()); + LLDB_REGISTER_METHOD(uint8_t, SBData, GetAddressByteSize, ()); + LLDB_REGISTER_METHOD(void, SBData, SetAddressByteSize, (uint8_t)); + LLDB_REGISTER_METHOD(void, SBData, Clear, ()); + LLDB_REGISTER_METHOD(size_t, SBData, GetByteSize, ()); + LLDB_REGISTER_METHOD(lldb::ByteOrder, SBData, GetByteOrder, ()); + LLDB_REGISTER_METHOD(void, SBData, SetByteOrder, (lldb::ByteOrder)); + LLDB_REGISTER_METHOD(float, SBData, GetFloat, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(double, SBData, GetDouble, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(long double, SBData, GetLongDouble, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(lldb::addr_t, SBData, GetAddress, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(uint8_t, SBData, GetUnsignedInt8, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(uint16_t, SBData, GetUnsignedInt16, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(uint32_t, SBData, GetUnsignedInt32, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(uint64_t, SBData, GetUnsignedInt64, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(int8_t, SBData, GetSignedInt8, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(int16_t, SBData, GetSignedInt16, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(int32_t, SBData, GetSignedInt32, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(int64_t, SBData, GetSignedInt64, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(const char *, SBData, GetString, + (lldb::SBError &, lldb::offset_t)); + LLDB_REGISTER_METHOD(bool, SBData, GetDescription, + (lldb::SBStream &, lldb::addr_t)); + LLDB_REGISTER_METHOD(bool, SBData, Append, (const lldb::SBData &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromCString, + (lldb::ByteOrder, uint32_t, const char *)); + LLDB_REGISTER_STATIC_METHOD( + lldb::SBData, SBData, CreateDataFromUInt64Array, + (lldb::ByteOrder, uint32_t, uint64_t *, size_t)); + LLDB_REGISTER_STATIC_METHOD( + lldb::SBData, SBData, CreateDataFromUInt32Array, + (lldb::ByteOrder, uint32_t, uint32_t *, size_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromSInt64Array, + (lldb::ByteOrder, uint32_t, int64_t *, size_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromSInt32Array, + (lldb::ByteOrder, uint32_t, int32_t *, size_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBData, SBData, CreateDataFromDoubleArray, + (lldb::ByteOrder, uint32_t, double *, size_t)); + LLDB_REGISTER_METHOD(bool, SBData, SetDataFromCString, (const char *)); + LLDB_REGISTER_METHOD(bool, SBData, SetDataFromUInt64Array, + (uint64_t *, size_t)); + LLDB_REGISTER_METHOD(bool, SBData, SetDataFromUInt32Array, + (uint32_t *, size_t)); + LLDB_REGISTER_METHOD(bool, SBData, SetDataFromSInt64Array, + (int64_t *, size_t)); + LLDB_REGISTER_METHOD(bool, SBData, SetDataFromSInt32Array, + (int32_t *, size_t)); + LLDB_REGISTER_METHOD(bool, SBData, SetDataFromDoubleArray, + (double *, size_t)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBDebugger.cpp b/src/llvm-project/lldb/source/API/SBDebugger.cpp index af34323..634c4a9 100644 --- a/src/llvm-project/lldb/source/API/SBDebugger.cpp +++ b/src/llvm-project/lldb/source/API/SBDebugger.cpp
@@ -1,13 +1,12 @@ //===-- SBDebugger.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "SystemInitializerFull.h" #include "lldb/API/SBDebugger.h" @@ -58,6 +57,51 @@ using namespace lldb; using namespace lldb_private; +/// Helper class for replaying commands through the reproducer. +class CommandLoader { +public: + CommandLoader(std::vector<std::string> files) : m_files(files) {} + + static std::unique_ptr<CommandLoader> Create() { + repro::Loader *loader = repro::Reproducer::Instance().GetLoader(); + if (!loader) + return {}; + + FileSpec file = loader->GetFile<repro::CommandProvider::Info>(); + if (!file) + return {}; + + auto error_or_file = llvm::MemoryBuffer::getFile(file.GetPath()); + if (auto err = error_or_file.getError()) + return {}; + + std::vector<std::string> files; + llvm::yaml::Input yin((*error_or_file)->getBuffer()); + yin >> files; + + if (auto err = yin.error()) + return {}; + + for (auto &file : files) { + FileSpec absolute_path = + loader->GetRoot().CopyByAppendingPathComponent(file); + file = absolute_path.GetPath(); + } + + return llvm::make_unique<CommandLoader>(std::move(files)); + } + + FILE *GetNextFile() { + if (m_index >= m_files.size()) + return nullptr; + return FileSystem::Instance().Fopen(m_files[m_index++].c_str(), "r"); + } + +private: + std::vector<std::string> m_files; + unsigned m_index = 0; +}; + static llvm::sys::DynamicLibrary LoadPlugin(const lldb::DebuggerSP &debugger_sp, const FileSpec &spec, Status &error) { @@ -98,60 +142,83 @@ SBError SBInputReader::Initialize( lldb::SBDebugger &sb_debugger, - unsigned long (*)(void *, lldb::SBInputReader *, lldb::InputReaderAction, - char const *, unsigned long), - void *, lldb::InputReaderGranularity, char const *, char const *, bool) { + 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_RECORD_DUMMY( + lldb::SBError, SBInputReader, Initialize, + (lldb::SBDebugger &, + unsigned long (*)(void *, lldb::SBInputReader *, lldb::InputReaderAction, + const char *, unsigned long), + void *, lldb::InputReaderGranularity, const char *, const char *, bool), + sb_debugger, callback, a, b, c, d, e); + return SBError(); } -void SBInputReader::SetIsDone(bool) {} +void SBInputReader::SetIsDone(bool b) { + LLDB_RECORD_METHOD(void, SBInputReader, SetIsDone, (bool), b); +} -bool SBInputReader::IsActive() const { return false; } +bool SBInputReader::IsActive() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBInputReader, IsActive); -SBDebugger::SBDebugger() = default; + return false; +} + +SBDebugger::SBDebugger() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBDebugger); } SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp) - : m_opaque_sp(debugger_sp) {} + : m_opaque_sp(debugger_sp) { + LLDB_RECORD_CONSTRUCTOR(SBDebugger, (const lldb::DebuggerSP &), debugger_sp); +} -SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) {} +SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBDebugger, (const lldb::SBDebugger &), rhs); +} SBDebugger::~SBDebugger() = default; SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) { + LLDB_RECORD_METHOD(lldb::SBDebugger &, + SBDebugger, operator=,(const lldb::SBDebugger &), rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } void SBDebugger::Initialize() { - SBInitializerOptions options; - SBDebugger::Initialize(options); + LLDB_RECORD_STATIC_METHOD_NO_ARGS(void, SBDebugger, Initialize); + SBError ignored = SBDebugger::InitializeWithErrorHandling(); } -lldb::SBError SBDebugger::Initialize(SBInitializerOptions &options) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +lldb::SBError SBDebugger::InitializeWithErrorHandling() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBError, SBDebugger, + InitializeWithErrorHandling); - if (log) - log->Printf("SBDebugger::Initialize ()"); + SBError error; if (auto e = g_debugger_lifetime->Initialize( - llvm::make_unique<SystemInitializerFull>(), *options.m_opaque_up, - LoadPlugin)) { + llvm::make_unique<SystemInitializerFull>(), LoadPlugin)) { error.SetError(Status(std::move(e))); } - return error; + return LLDB_RECORD_RESULT(error); } -void SBDebugger::Terminate() { g_debugger_lifetime->Terminate(); } +void SBDebugger::Terminate() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(void, SBDebugger, Terminate); + + g_debugger_lifetime->Terminate(); +} void SBDebugger::Clear() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(void, SBDebugger, Clear); - if (log) - log->Printf("SBDebugger(%p)::Clear ()", - static_cast<void *>(m_opaque_sp.get())); if (m_opaque_sp) m_opaque_sp->ClearIOHandlers(); @@ -160,18 +227,26 @@ } SBDebugger SBDebugger::Create() { - return SBDebugger::Create(false, nullptr, nullptr); + LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBDebugger, SBDebugger, Create); + + return LLDB_RECORD_RESULT(SBDebugger::Create(false, nullptr, nullptr)); } SBDebugger SBDebugger::Create(bool source_init_files) { - return SBDebugger::Create(source_init_files, nullptr, nullptr); + LLDB_RECORD_STATIC_METHOD(lldb::SBDebugger, SBDebugger, Create, (bool), + source_init_files); + + return LLDB_RECORD_RESULT( + SBDebugger::Create(source_init_files, nullptr, nullptr)); } SBDebugger SBDebugger::Create(bool source_init_files, lldb::LogOutputCallback callback, void *baton) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_DUMMY(lldb::SBDebugger, SBDebugger, Create, + (bool, lldb::LogOutputCallback, void *), source_init_files, + callback, baton); SBDebugger debugger; @@ -185,13 +260,6 @@ debugger.reset(Debugger::CreateInstance(callback, baton)); - if (log) { - SBStream sstr; - debugger.GetDescription(sstr); - log->Printf("SBDebugger::Create () => SBDebugger(%p): %s", - static_cast<void *>(debugger.m_opaque_sp.get()), - sstr.GetData()); - } SBCommandInterpreter interp = debugger.GetCommandInterpreter(); if (source_init_files) { @@ -207,15 +275,9 @@ } void SBDebugger::Destroy(SBDebugger &debugger) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_STATIC_METHOD(void, SBDebugger, Destroy, (lldb::SBDebugger &), + debugger); - if (log) { - SBStream sstr; - debugger.GetDescription(sstr); - log->Printf("SBDebugger::Destroy () => SBDebugger(%p): %s", - static_cast<void *>(debugger.m_opaque_sp.get()), - sstr.GetData()); - } Debugger::Destroy(debugger.m_opaque_sp); @@ -224,38 +286,51 @@ } void SBDebugger::MemoryPressureDetected() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(void, SBDebugger, MemoryPressureDetected); + // 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. - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); const bool mandatory = false; - if (log) { - log->Printf("SBDebugger::MemoryPressureDetected (), mandatory = %d", - mandatory); - } ModuleList::RemoveOrphanSharedModules(mandatory); } -bool SBDebugger::IsValid() const { return m_opaque_sp.get() != nullptr; } +bool SBDebugger::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, IsValid); + return this->operator bool(); +} +SBDebugger::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, operator bool); + + return m_opaque_sp.get() != nullptr; +} void SBDebugger::SetAsync(bool b) { + LLDB_RECORD_METHOD(void, SBDebugger, SetAsync, (bool), b); + if (m_opaque_sp) m_opaque_sp->SetAsyncExecution(b); } bool SBDebugger::GetAsync() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBDebugger, GetAsync); + return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false); } void SBDebugger::SkipLLDBInitFiles(bool b) { + LLDB_RECORD_METHOD(void, SBDebugger, SkipLLDBInitFiles, (bool), b); + if (m_opaque_sp) m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b); } void SBDebugger::SkipAppInitFiles(bool b) { + LLDB_RECORD_METHOD(void, SBDebugger, SkipAppInitFiles, (bool), b); + if (m_opaque_sp) m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b); } @@ -264,97 +339,102 @@ // of problems; don't want users trying to switch modes in the middle of a // debugging session. void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBDebugger, SetInputFileHandle, (FILE *, bool), fh, + transfer_ownership); - if (log) - log->Printf( - "SBDebugger(%p)::SetInputFileHandle (fh=%p, transfer_ownership=%i)", - static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh), - transfer_ownership); + if (!m_opaque_sp) + return; - if (m_opaque_sp) - m_opaque_sp->SetInputFileHandle(fh, transfer_ownership); + repro::DataRecorder *recorder = nullptr; + if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) + recorder = g->GetOrCreate<repro::CommandProvider>().GetNewDataRecorder(); + + static std::unique_ptr<CommandLoader> loader = CommandLoader::Create(); + if (loader) + fh = loader->GetNextFile(); + + m_opaque_sp->SetInputFileHandle(fh, transfer_ownership, recorder); } void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf( - "SBDebugger(%p)::SetOutputFileHandle (fh=%p, transfer_ownership=%i)", - static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh), - transfer_ownership); + LLDB_RECORD_METHOD(void, SBDebugger, SetOutputFileHandle, (FILE *, bool), fh, + transfer_ownership); if (m_opaque_sp) m_opaque_sp->SetOutputFileHandle(fh, transfer_ownership); } void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBDebugger, SetErrorFileHandle, (FILE *, bool), fh, + transfer_ownership); - if (log) - log->Printf( - "SBDebugger(%p)::SetErrorFileHandle (fh=%p, transfer_ownership=%i)", - static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh), - transfer_ownership); if (m_opaque_sp) m_opaque_sp->SetErrorFileHandle(fh, transfer_ownership); } FILE *SBDebugger::GetInputFileHandle() { + LLDB_RECORD_METHOD_NO_ARGS(FILE *, SBDebugger, GetInputFileHandle); + if (m_opaque_sp) { StreamFileSP stream_file_sp(m_opaque_sp->GetInputFile()); if (stream_file_sp) - return stream_file_sp->GetFile().GetStream(); + return LLDB_RECORD_RESULT(stream_file_sp->GetFile().GetStream()); } return nullptr; } FILE *SBDebugger::GetOutputFileHandle() { + LLDB_RECORD_METHOD_NO_ARGS(FILE *, SBDebugger, GetOutputFileHandle); + if (m_opaque_sp) { StreamFileSP stream_file_sp(m_opaque_sp->GetOutputFile()); if (stream_file_sp) - return stream_file_sp->GetFile().GetStream(); + return LLDB_RECORD_RESULT(stream_file_sp->GetFile().GetStream()); } return nullptr; } FILE *SBDebugger::GetErrorFileHandle() { + LLDB_RECORD_METHOD_NO_ARGS(FILE *, SBDebugger, GetErrorFileHandle); + if (m_opaque_sp) { StreamFileSP stream_file_sp(m_opaque_sp->GetErrorFile()); if (stream_file_sp) - return stream_file_sp->GetFile().GetStream(); + return LLDB_RECORD_RESULT(stream_file_sp->GetFile().GetStream()); } return nullptr; } void SBDebugger::SaveInputTerminalState() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBDebugger, SaveInputTerminalState); + if (m_opaque_sp) m_opaque_sp->SaveInputTerminalState(); } void SBDebugger::RestoreInputTerminalState() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBDebugger, RestoreInputTerminalState); + if (m_opaque_sp) m_opaque_sp->RestoreInputTerminalState(); } SBCommandInterpreter SBDebugger::GetCommandInterpreter() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBCommandInterpreter, SBDebugger, + GetCommandInterpreter); + SBCommandInterpreter sb_interpreter; if (m_opaque_sp) sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter()); - if (log) - log->Printf( - "SBDebugger(%p)::GetCommandInterpreter () => SBCommandInterpreter(%p)", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(sb_interpreter.get())); - return sb_interpreter; + return LLDB_RECORD_RESULT(sb_interpreter); } void SBDebugger::HandleCommand(const char *command) { + LLDB_RECORD_METHOD(void, SBDebugger, HandleCommand, (const char *), command); + if (m_opaque_sp) { TargetSP target_sp(m_opaque_sp->GetSelectedTarget()); std::unique_lock<std::recursive_mutex> lock; @@ -389,23 +469,25 @@ } SBListener SBDebugger::GetListener() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBListener, SBDebugger, GetListener); + SBListener sb_listener; if (m_opaque_sp) sb_listener.reset(m_opaque_sp->GetListener()); - if (log) - log->Printf("SBDebugger(%p)::GetListener () => SBListener(%p)", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(sb_listener.get())); - return sb_listener; + return LLDB_RECORD_RESULT(sb_listener); } void SBDebugger::HandleProcessEvent(const SBProcess &process, const SBEvent &event, FILE *out, FILE *err) { + LLDB_RECORD_METHOD( + void, SBDebugger, HandleProcessEvent, + (const lldb::SBProcess &, const lldb::SBEvent &, FILE *, FILE *), process, + event, out, err); + if (!process.IsValid()) return; @@ -448,11 +530,17 @@ } SBSourceManager SBDebugger::GetSourceManager() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSourceManager, SBDebugger, + GetSourceManager); + SBSourceManager sb_source_manager(*this); - return sb_source_manager; + return LLDB_RECORD_RESULT(sb_source_manager); } bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) { + LLDB_RECORD_STATIC_METHOD(bool, SBDebugger, GetDefaultArchitecture, + (char *, size_t), "", arch_name_len); + if (arch_name && arch_name_len) { ArchSpec default_arch = Target::GetDefaultArchitecture(); @@ -472,6 +560,9 @@ } bool SBDebugger::SetDefaultArchitecture(const char *arch_name) { + LLDB_RECORD_STATIC_METHOD(bool, SBDebugger, SetDefaultArchitecture, + (const char *), arch_name); + if (arch_name) { ArchSpec arch(arch_name); if (arch.IsValid()) { @@ -484,16 +575,24 @@ ScriptLanguage SBDebugger::GetScriptingLanguage(const char *script_language_name) { + LLDB_RECORD_METHOD(lldb::ScriptLanguage, SBDebugger, GetScriptingLanguage, + (const char *), script_language_name); + if (!script_language_name) return eScriptLanguageDefault; return OptionArgParser::ToScriptLanguage( llvm::StringRef(script_language_name), eScriptLanguageDefault, nullptr); } const char *SBDebugger::GetVersionString() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBDebugger, GetVersionString); + return lldb_private::GetVersion(); } const char *SBDebugger::StateAsCString(StateType state) { + LLDB_RECORD_STATIC_METHOD(const char *, SBDebugger, StateAsCString, + (lldb::StateType), state); + return lldb_private::StateAsCString(state); } @@ -518,6 +617,9 @@ } SBStructuredData SBDebugger::GetBuildConfiguration() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBStructuredData, SBDebugger, + GetBuildConfiguration); + auto config_up = llvm::make_unique<StructuredData::Dictionary>(); AddBoolConfigEntry( *config_up, "xml", XMLDocument::XMLEnabled(), @@ -526,27 +628,25 @@ SBStructuredData data; data.m_impl_up->SetObjectSP(std::move(config_up)); - return data; + return LLDB_RECORD_RESULT(data); } bool SBDebugger::StateIsRunningState(StateType state) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_STATIC_METHOD(bool, SBDebugger, StateIsRunningState, + (lldb::StateType), state); + const bool result = lldb_private::StateIsRunningState(state); - if (log) - log->Printf("SBDebugger::StateIsRunningState (state=%s) => %i", - StateAsCString(state), result); return result; } bool SBDebugger::StateIsStoppedState(StateType state) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_STATIC_METHOD(bool, SBDebugger, StateIsStoppedState, + (lldb::StateType), state); + const bool result = lldb_private::StateIsStoppedState(state, false); - if (log) - log->Printf("SBDebugger::StateIsStoppedState (state=%s) => %i", - StateAsCString(state), result); return result; } @@ -556,6 +656,11 @@ const char *platform_name, bool add_dependent_modules, lldb::SBError &sb_error) { + LLDB_RECORD_METHOD( + lldb::SBTarget, SBDebugger, CreateTarget, + (const char *, const char *, const char *, bool, lldb::SBError &), + filename, target_triple, platform_name, add_dependent_modules, sb_error); + SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { @@ -583,12 +688,16 @@ platform_name, add_dependent_modules, sb_error.GetCString(), static_cast<void *>(target_sp.get())); - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename, const char *target_triple) { + LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, + CreateTargetWithFileAndTargetTriple, + (const char *, const char *), filename, target_triple); + SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { @@ -607,11 +716,14 @@ static_cast<void *>(m_opaque_sp.get()), filename, target_triple, static_cast<void *>(target_sp.get())); - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename, const char *arch_cstr) { + LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, CreateTargetWithFileAndArch, + (const char *, const char *), filename, arch_cstr); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); SBTarget sb_target; @@ -637,10 +749,13 @@ static_cast<void *>(m_opaque_sp.get()), filename, arch_cstr, static_cast<void *>(target_sp.get())); - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::CreateTarget(const char *filename) { + LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, CreateTarget, (const char *), + filename); + SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { @@ -662,10 +777,12 @@ "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)", static_cast<void *>(m_opaque_sp.get()), filename, static_cast<void *>(target_sp.get())); - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::GetDummyTarget() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTarget, SBDebugger, GetDummyTarget); + SBTarget sb_target; if (m_opaque_sp) { sb_target.SetSP(m_opaque_sp->GetDummyTarget()->shared_from_this()); @@ -676,10 +793,13 @@ "SBDebugger(%p)::GetDummyTarget() => SBTarget(%p)", static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(sb_target.GetSP().get())); - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } bool SBDebugger::DeleteTarget(lldb::SBTarget &target) { + LLDB_RECORD_METHOD(bool, SBDebugger, DeleteTarget, (lldb::SBTarget &), + target); + bool result = false; if (m_opaque_sp) { TargetSP target_sp(target.GetSP()); @@ -703,15 +823,20 @@ } SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, GetTargetAtIndex, (uint32_t), + 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; + return LLDB_RECORD_RESULT(sb_target); } uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) { + LLDB_RECORD_METHOD(uint32_t, SBDebugger, GetIndexOfTarget, (lldb::SBTarget), + target); lldb::TargetSP target_sp = target.GetSP(); if (!target_sp) @@ -724,16 +849,22 @@ } SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) { + LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithProcessID, + (lldb::pid_t), 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; + return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename, const char *arch_name) { + LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithFileAndArch, + (const char *, const char *), filename, arch_name); + SBTarget sb_target; if (m_opaque_sp && filename && filename[0]) { // No need to lock, the target list is thread safe @@ -744,7 +875,7 @@ FileSpec(filename), arch_name ? &arch : nullptr)); sb_target.SetSP(target_sp); } - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) { @@ -758,6 +889,8 @@ } uint32_t SBDebugger::GetNumTargets() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumTargets); + if (m_opaque_sp) { // No need to lock, the target list is thread safe return m_opaque_sp->GetTargetList().GetNumTargets(); @@ -766,6 +899,8 @@ } SBTarget SBDebugger::GetSelectedTarget() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTarget, SBDebugger, GetSelectedTarget); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); SBTarget sb_target; @@ -784,10 +919,13 @@ static_cast<void *>(target_sp.get()), sstr.GetData()); } - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } void SBDebugger::SetSelectedTarget(SBTarget &sb_target) { + LLDB_RECORD_METHOD(void, SBDebugger, SetSelectedTarget, (lldb::SBTarget &), + sb_target); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); TargetSP target_sp(sb_target.GetSP()); @@ -804,6 +942,8 @@ } SBPlatform SBDebugger::GetSelectedPlatform() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBPlatform, SBDebugger, GetSelectedPlatform); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); SBPlatform sb_platform; @@ -816,10 +956,13 @@ static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(sb_platform.GetSP().get()), sb_platform.GetName()); - return sb_platform; + return LLDB_RECORD_RESULT(sb_platform); } void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) { + LLDB_RECORD_METHOD(void, SBDebugger, SetSelectedPlatform, + (lldb::SBPlatform &), sb_platform); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); DebuggerSP debugger_sp(m_opaque_sp); @@ -835,6 +978,8 @@ } uint32_t SBDebugger::GetNumPlatforms() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumPlatforms); + if (m_opaque_sp) { // No need to lock, the platform list is thread safe return m_opaque_sp->GetPlatformList().GetSize(); @@ -843,15 +988,20 @@ } SBPlatform SBDebugger::GetPlatformAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBPlatform, SBDebugger, GetPlatformAtIndex, + (uint32_t), 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; + return LLDB_RECORD_RESULT(sb_platform); } uint32_t SBDebugger::GetNumAvailablePlatforms() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumAvailablePlatforms); + uint32_t idx = 0; while (true) { if (!PluginManager::GetPlatformPluginNameAtIndex(idx)) { @@ -864,6 +1014,9 @@ } SBStructuredData SBDebugger::GetAvailablePlatformInfoAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBStructuredData, SBDebugger, + GetAvailablePlatformInfoAtIndex, (uint32_t), idx); + SBStructuredData data; auto platform_dict = llvm::make_unique<StructuredData::Dictionary>(); llvm::StringRef name_str("name"), desc_str("description"); @@ -878,28 +1031,34 @@ const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex(idx - 1); if (!plugin_name) { - return data; + return LLDB_RECORD_RESULT(data); } platform_dict->AddStringItem(name_str, llvm::StringRef(plugin_name)); const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex(idx - 1); if (!plugin_desc) { - return data; + return LLDB_RECORD_RESULT(data); } platform_dict->AddStringItem(desc_str, llvm::StringRef(plugin_desc)); } data.m_impl_up->SetObjectSP( StructuredData::ObjectSP(platform_dict.release())); - return data; + return LLDB_RECORD_RESULT(data); } void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) { + LLDB_RECORD_DUMMY(void, SBDebugger, DispatchInput, + (void *, const void *, size_t), baton, data, data_len); + DispatchInput(data, data_len); } void SBDebugger::DispatchInput(const void *data, size_t data_len) { + LLDB_RECORD_DUMMY(void, SBDebugger, DispatchInput, (const void *, size_t), + data, data_len); + // Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); // // if (log) @@ -915,19 +1074,29 @@ } void SBDebugger::DispatchInputInterrupt() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBDebugger, DispatchInputInterrupt); + if (m_opaque_sp) m_opaque_sp->DispatchInputInterrupt(); } void SBDebugger::DispatchInputEndOfFile() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBDebugger, DispatchInputEndOfFile); + if (m_opaque_sp) m_opaque_sp->DispatchInputEndOfFile(); } -void SBDebugger::PushInputReader(SBInputReader &reader) {} +void SBDebugger::PushInputReader(SBInputReader &reader) { + LLDB_RECORD_METHOD(void, SBDebugger, PushInputReader, (lldb::SBInputReader &), + reader); +} void SBDebugger::RunCommandInterpreter(bool auto_handle_events, bool spawn_thread) { + LLDB_RECORD_METHOD(void, SBDebugger, RunCommandInterpreter, (bool, bool), + auto_handle_events, spawn_thread); + if (m_opaque_sp) { CommandInterpreterRunOptions options; @@ -943,6 +1112,12 @@ bool &stopped_for_crash) { + LLDB_RECORD_METHOD(void, SBDebugger, RunCommandInterpreter, + (bool, bool, lldb::SBCommandInterpreterRunOptions &, int &, + bool &, bool &), + auto_handle_events, spawn_thread, options, num_errors, + quit_requested, stopped_for_crash); + if (m_opaque_sp) { CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter(); interp.RunCommandInterpreter(auto_handle_events, spawn_thread, @@ -955,12 +1130,16 @@ SBError SBDebugger::RunREPL(lldb::LanguageType language, const char *repl_options) { + LLDB_RECORD_METHOD(lldb::SBError, SBDebugger, RunREPL, + (lldb::LanguageType, const char *), 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; + return LLDB_RECORD_RESULT(error); } void SBDebugger::reset(const DebuggerSP &debugger_sp) { @@ -977,20 +1156,29 @@ const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; } SBDebugger SBDebugger::FindDebuggerWithID(int id) { + LLDB_RECORD_STATIC_METHOD(lldb::SBDebugger, SBDebugger, FindDebuggerWithID, + (int), 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; + return LLDB_RECORD_RESULT(sb_debugger); } const char *SBDebugger::GetInstanceName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBDebugger, GetInstanceName); + return (m_opaque_sp ? m_opaque_sp->GetInstanceName().AsCString() : nullptr); } SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value, const char *debugger_instance_name) { + LLDB_RECORD_STATIC_METHOD(lldb::SBError, SBDebugger, SetInternalVariable, + (const char *, const char *, const char *), + var_name, value, debugger_instance_name); + SBError sb_error; DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( ConstString(debugger_instance_name))); @@ -1006,12 +1194,16 @@ } if (error.Fail()) sb_error.SetError(error); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBStringList SBDebugger::GetInternalVariableValue(const char *var_name, const char *debugger_instance_name) { + LLDB_RECORD_STATIC_METHOD( + lldb::SBStringList, SBDebugger, GetInternalVariableValue, + (const char *, const char *), var_name, debugger_instance_name); + SBStringList ret_value; DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( ConstString(debugger_instance_name))); @@ -1028,23 +1220,30 @@ if (!value_str.empty()) { StringList string_list; string_list.SplitIntoLines(value_str); - return SBStringList(&string_list); + return LLDB_RECORD_RESULT(SBStringList(&string_list)); } } } - return SBStringList(); + return LLDB_RECORD_RESULT(SBStringList()); } uint32_t SBDebugger::GetTerminalWidth() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBDebugger, GetTerminalWidth); + return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0); } void SBDebugger::SetTerminalWidth(uint32_t term_width) { + LLDB_RECORD_METHOD(void, SBDebugger, SetTerminalWidth, (uint32_t), + term_width); + if (m_opaque_sp) m_opaque_sp->SetTerminalWidth(term_width); } const char *SBDebugger::GetPrompt() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBDebugger, GetPrompt); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (log) @@ -1057,43 +1256,64 @@ } void SBDebugger::SetPrompt(const char *prompt) { + LLDB_RECORD_METHOD(void, SBDebugger, SetPrompt, (const char *), prompt); + if (m_opaque_sp) m_opaque_sp->SetPrompt(llvm::StringRef::withNullAsEmpty(prompt)); } const char *SBDebugger::GetReproducerPath() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBDebugger, GetReproducerPath); + return (m_opaque_sp ? ConstString(m_opaque_sp->GetReproducerPath()).GetCString() : nullptr); } ScriptLanguage SBDebugger::GetScriptLanguage() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::ScriptLanguage, SBDebugger, + GetScriptLanguage); + return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone); } void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) { + LLDB_RECORD_METHOD(void, SBDebugger, SetScriptLanguage, + (lldb::ScriptLanguage), script_lang); + if (m_opaque_sp) { m_opaque_sp->SetScriptLanguage(script_lang); } } bool SBDebugger::SetUseExternalEditor(bool value) { + LLDB_RECORD_METHOD(bool, SBDebugger, SetUseExternalEditor, (bool), value); + return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false); } bool SBDebugger::GetUseExternalEditor() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBDebugger, GetUseExternalEditor); + return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false); } bool SBDebugger::SetUseColor(bool value) { + LLDB_RECORD_METHOD(bool, SBDebugger, SetUseColor, (bool), value); + return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false); } bool SBDebugger::GetUseColor() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, GetUseColor); + return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false); } bool SBDebugger::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBDebugger, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); if (m_opaque_sp) { @@ -1107,10 +1327,15 @@ } user_id_t SBDebugger::GetID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::user_id_t, SBDebugger, GetID); + return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID); } SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) { + LLDB_RECORD_METHOD(lldb::SBError, SBDebugger, SetCurrentPlatform, + (const char *), platform_name_cstr); + SBError sb_error; if (m_opaque_sp) { if (platform_name_cstr && platform_name_cstr[0]) { @@ -1135,10 +1360,13 @@ } else { sb_error.ref().SetErrorString("invalid debugger"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) { + LLDB_RECORD_METHOD(bool, SBDebugger, SetCurrentPlatformSDKRoot, + (const char *), sysroot); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (m_opaque_sp) { PlatformSP platform_sp( @@ -1155,49 +1383,68 @@ } bool SBDebugger::GetCloseInputOnEOF() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, GetCloseInputOnEOF); + return (m_opaque_sp ? m_opaque_sp->GetCloseInputOnEOF() : false); } void SBDebugger::SetCloseInputOnEOF(bool b) { + LLDB_RECORD_METHOD(void, SBDebugger, SetCloseInputOnEOF, (bool), b); + if (m_opaque_sp) m_opaque_sp->SetCloseInputOnEOF(b); } SBTypeCategory SBDebugger::GetCategory(const char *category_name) { + LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, + (const char *), category_name); + if (!category_name || *category_name == 0) - return SBTypeCategory(); + return LLDB_RECORD_RESULT(SBTypeCategory()); TypeCategoryImplSP category_sp; if (DataVisualization::Categories::GetCategory(ConstString(category_name), - category_sp, false)) - return SBTypeCategory(category_sp); - else - return SBTypeCategory(); + category_sp, false)) { + return LLDB_RECORD_RESULT(SBTypeCategory(category_sp)); + } else { + return LLDB_RECORD_RESULT(SBTypeCategory()); + } } SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) { + LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, + (lldb::LanguageType), lang_type); + TypeCategoryImplSP category_sp; - if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) - return SBTypeCategory(category_sp); - else - return SBTypeCategory(); + if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) { + return LLDB_RECORD_RESULT(SBTypeCategory(category_sp)); + } else { + return LLDB_RECORD_RESULT(SBTypeCategory()); + } } SBTypeCategory SBDebugger::CreateCategory(const char *category_name) { + LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, CreateCategory, + (const char *), category_name); + if (!category_name || *category_name == 0) - return SBTypeCategory(); + return LLDB_RECORD_RESULT(SBTypeCategory()); TypeCategoryImplSP category_sp; if (DataVisualization::Categories::GetCategory(ConstString(category_name), - category_sp, true)) - return SBTypeCategory(category_sp); - else - return SBTypeCategory(); + category_sp, true)) { + return LLDB_RECORD_RESULT(SBTypeCategory(category_sp)); + } else { + return LLDB_RECORD_RESULT(SBTypeCategory()); + } } bool SBDebugger::DeleteCategory(const char *category_name) { + LLDB_RECORD_METHOD(bool, SBDebugger, DeleteCategory, (const char *), + category_name); + if (!category_name || *category_name == 0) return false; @@ -1205,47 +1452,65 @@ } uint32_t SBDebugger::GetNumCategories() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumCategories); + return DataVisualization::Categories::GetCount(); } SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) { - return SBTypeCategory( - DataVisualization::Categories::GetCategoryAtIndex(index)); + LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategoryAtIndex, + (uint32_t), index); + + return LLDB_RECORD_RESULT( + SBTypeCategory(DataVisualization::Categories::GetCategoryAtIndex(index))); } SBTypeCategory SBDebugger::GetDefaultCategory() { - return GetCategory("default"); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeCategory, SBDebugger, + GetDefaultCategory); + + return LLDB_RECORD_RESULT(GetCategory("default")); } SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(lldb::SBTypeFormat, SBDebugger, GetFormatForType, + (lldb::SBTypeNameSpecifier), type_name); + SBTypeCategory default_category_sb = GetDefaultCategory(); if (default_category_sb.GetEnabled()) - return default_category_sb.GetFormatForType(type_name); - return SBTypeFormat(); + return LLDB_RECORD_RESULT(default_category_sb.GetFormatForType(type_name)); + return LLDB_RECORD_RESULT(SBTypeFormat()); } -#ifndef LLDB_DISABLE_PYTHON SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(lldb::SBTypeSummary, SBDebugger, GetSummaryForType, + (lldb::SBTypeNameSpecifier), type_name); + if (!type_name.IsValid()) - return SBTypeSummary(); - return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP())); + return LLDB_RECORD_RESULT(SBTypeSummary()); + return LLDB_RECORD_RESULT( + SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP()))); } -#endif // LLDB_DISABLE_PYTHON SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(lldb::SBTypeFilter, SBDebugger, GetFilterForType, + (lldb::SBTypeNameSpecifier), type_name); + if (!type_name.IsValid()) - return SBTypeFilter(); - return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP())); + return LLDB_RECORD_RESULT(SBTypeFilter()); + return LLDB_RECORD_RESULT( + SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP()))); } -#ifndef LLDB_DISABLE_PYTHON SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(lldb::SBTypeSynthetic, SBDebugger, GetSyntheticForType, + (lldb::SBTypeNameSpecifier), type_name); + if (!type_name.IsValid()) - return SBTypeSynthetic(); - return SBTypeSynthetic( - DataVisualization::GetSyntheticForType(type_name.GetSP())); + return LLDB_RECORD_RESULT(SBTypeSynthetic()); + return LLDB_RECORD_RESULT(SBTypeSynthetic( + DataVisualization::GetSyntheticForType(type_name.GetSP()))); } -#endif // LLDB_DISABLE_PYTHON static llvm::ArrayRef<const char *> GetCategoryArray(const char **categories) { if (categories == nullptr) @@ -1257,6 +1522,9 @@ } bool SBDebugger::EnableLog(const char *channel, const char **categories) { + LLDB_RECORD_METHOD(bool, SBDebugger, EnableLog, (const char *, const char **), + channel, categories); + if (m_opaque_sp) { uint32_t log_options = LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; @@ -1270,7 +1538,193 @@ void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton) { + LLDB_RECORD_DUMMY(void, SBDebugger, SetLoggingCallback, + (lldb::LogOutputCallback, void *), log_callback, baton); + if (m_opaque_sp) { return m_opaque_sp->SetLoggingCallback(log_callback, baton); } } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBInputReader>(Registry &R) { + LLDB_REGISTER_METHOD(void, SBInputReader, SetIsDone, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBInputReader, IsActive, ()); +} + +static void SetFileHandleRedirect(SBDebugger *, FILE *, bool) { + // Do nothing. +} + +static bool GetDefaultArchitectureRedirect(char *arch_name, + size_t arch_name_len) { + // The function is writing to its argument. Without the redirect it would + // write into the replay buffer. + char buffer[1024]; + return SBDebugger::GetDefaultArchitecture(buffer, arch_name_len); +} + +template <> +void RegisterMethods<SBDebugger>(Registry &R) { + // Custom implementation. + R.Register(&invoke<void (SBDebugger::*)( + FILE *, bool)>::method<&SBDebugger::SetErrorFileHandle>::doit, + &SetFileHandleRedirect); + R.Register(&invoke<void (SBDebugger::*)( + FILE *, bool)>::method<&SBDebugger::SetOutputFileHandle>::doit, + &SetFileHandleRedirect); + R.Register<bool(char *, size_t)>(static_cast<bool (*)(char *, size_t)>( + &SBDebugger::GetDefaultArchitecture), + &GetDefaultArchitectureRedirect); + + LLDB_REGISTER_CONSTRUCTOR(SBDebugger, ()); + LLDB_REGISTER_CONSTRUCTOR(SBDebugger, (const lldb::DebuggerSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBDebugger, (const lldb::SBDebugger &)); + LLDB_REGISTER_METHOD(lldb::SBDebugger &, + SBDebugger, operator=,(const lldb::SBDebugger &)); + LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, Initialize, ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBError, SBDebugger, + InitializeWithErrorHandling, ()); + LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, Terminate, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, Clear, ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBDebugger, SBDebugger, Create, ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBDebugger, SBDebugger, Create, (bool)); + LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, Destroy, + (lldb::SBDebugger &)); + LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, MemoryPressureDetected, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SetAsync, (bool)); + LLDB_REGISTER_METHOD(bool, SBDebugger, GetAsync, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SkipLLDBInitFiles, (bool)); + LLDB_REGISTER_METHOD(void, SBDebugger, SkipAppInitFiles, (bool)); + LLDB_REGISTER_METHOD(void, SBDebugger, SetInputFileHandle, (FILE *, bool)); + LLDB_REGISTER_METHOD(FILE *, SBDebugger, GetInputFileHandle, ()); + LLDB_REGISTER_METHOD(FILE *, SBDebugger, GetOutputFileHandle, ()); + LLDB_REGISTER_METHOD(FILE *, SBDebugger, GetErrorFileHandle, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SaveInputTerminalState, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, RestoreInputTerminalState, ()); + LLDB_REGISTER_METHOD(lldb::SBCommandInterpreter, SBDebugger, + GetCommandInterpreter, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, HandleCommand, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBListener, SBDebugger, GetListener, ()); + LLDB_REGISTER_METHOD( + void, SBDebugger, HandleProcessEvent, + (const lldb::SBProcess &, const lldb::SBEvent &, FILE *, FILE *)); + LLDB_REGISTER_METHOD(lldb::SBSourceManager, SBDebugger, GetSourceManager, + ()); + LLDB_REGISTER_STATIC_METHOD(bool, SBDebugger, SetDefaultArchitecture, + (const char *)); + LLDB_REGISTER_METHOD(lldb::ScriptLanguage, SBDebugger, GetScriptingLanguage, + (const char *)); + LLDB_REGISTER_STATIC_METHOD(const char *, SBDebugger, GetVersionString, ()); + LLDB_REGISTER_STATIC_METHOD(const char *, SBDebugger, StateAsCString, + (lldb::StateType)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBStructuredData, SBDebugger, + GetBuildConfiguration, ()); + LLDB_REGISTER_STATIC_METHOD(bool, SBDebugger, StateIsRunningState, + (lldb::StateType)); + LLDB_REGISTER_STATIC_METHOD(bool, SBDebugger, StateIsStoppedState, + (lldb::StateType)); + LLDB_REGISTER_METHOD( + lldb::SBTarget, SBDebugger, CreateTarget, + (const char *, const char *, const char *, bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, + CreateTargetWithFileAndTargetTriple, + (const char *, const char *)); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, + CreateTargetWithFileAndArch, + (const char *, const char *)); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, CreateTarget, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, GetDummyTarget, ()); + LLDB_REGISTER_METHOD(bool, SBDebugger, DeleteTarget, (lldb::SBTarget &)); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, GetTargetAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetIndexOfTarget, + (lldb::SBTarget)); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithProcessID, + (lldb::pid_t)); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithFileAndArch, + (const char *, const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumTargets, ()); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, GetSelectedTarget, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SetSelectedTarget, + (lldb::SBTarget &)); + LLDB_REGISTER_METHOD(lldb::SBPlatform, SBDebugger, GetSelectedPlatform, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SetSelectedPlatform, + (lldb::SBPlatform &)); + LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumPlatforms, ()); + LLDB_REGISTER_METHOD(lldb::SBPlatform, SBDebugger, GetPlatformAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumAvailablePlatforms, ()); + LLDB_REGISTER_METHOD(lldb::SBStructuredData, SBDebugger, + GetAvailablePlatformInfoAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBDebugger, DispatchInputInterrupt, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, DispatchInputEndOfFile, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, PushInputReader, + (lldb::SBInputReader &)); + LLDB_REGISTER_METHOD(void, SBDebugger, RunCommandInterpreter, (bool, bool)); + LLDB_REGISTER_METHOD(void, SBDebugger, RunCommandInterpreter, + (bool, bool, lldb::SBCommandInterpreterRunOptions &, + int &, bool &, bool &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBDebugger, RunREPL, + (lldb::LanguageType, const char *)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBDebugger, SBDebugger, + FindDebuggerWithID, (int)); + LLDB_REGISTER_METHOD(const char *, SBDebugger, GetInstanceName, ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBError, SBDebugger, SetInternalVariable, + (const char *, const char *, const char *)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBStringList, SBDebugger, + GetInternalVariableValue, + (const char *, const char *)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBDebugger, GetTerminalWidth, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SetTerminalWidth, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(const char *, SBDebugger, GetPrompt, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SetPrompt, (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBDebugger, GetReproducerPath, ()); + LLDB_REGISTER_METHOD_CONST(lldb::ScriptLanguage, SBDebugger, + GetScriptLanguage, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SetScriptLanguage, + (lldb::ScriptLanguage)); + LLDB_REGISTER_METHOD(bool, SBDebugger, SetUseExternalEditor, (bool)); + LLDB_REGISTER_METHOD(bool, SBDebugger, GetUseExternalEditor, ()); + LLDB_REGISTER_METHOD(bool, SBDebugger, SetUseColor, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, GetUseColor, ()); + LLDB_REGISTER_METHOD(bool, SBDebugger, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(lldb::user_id_t, SBDebugger, GetID, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBDebugger, SetCurrentPlatform, + (const char *)); + LLDB_REGISTER_METHOD(bool, SBDebugger, SetCurrentPlatformSDKRoot, + (const char *)); + LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, GetCloseInputOnEOF, ()); + LLDB_REGISTER_METHOD(void, SBDebugger, SetCloseInputOnEOF, (bool)); + LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, + (lldb::LanguageType)); + LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, CreateCategory, + (const char *)); + LLDB_REGISTER_METHOD(bool, SBDebugger, DeleteCategory, (const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumCategories, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategoryAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetDefaultCategory, + ()); + LLDB_REGISTER_METHOD(lldb::SBTypeFormat, SBDebugger, GetFormatForType, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeSummary, SBDebugger, GetSummaryForType, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeSynthetic, SBDebugger, GetSyntheticForType, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeFilter, SBDebugger, GetFilterForType, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(bool, SBDebugger, EnableLog, + (const char *, const char **)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBDeclaration.cpp b/src/llvm-project/lldb/source/API/SBDeclaration.cpp index 90e4db3..a7790b2 100644 --- a/src/llvm-project/lldb/source/API/SBDeclaration.cpp +++ b/src/llvm-project/lldb/source/API/SBDeclaration.cpp
@@ -1,17 +1,17 @@ //===-- SBDeclaration.cpp ----------------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBStream.h" #include "lldb/Host/PosixApi.h" #include "lldb/Symbol/Declaration.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" #include <limits.h> @@ -19,27 +19,30 @@ using namespace lldb; using namespace lldb_private; -SBDeclaration::SBDeclaration() : m_opaque_ap() {} +SBDeclaration::SBDeclaration() : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBDeclaration); +} -SBDeclaration::SBDeclaration(const SBDeclaration &rhs) : m_opaque_ap() { - if (rhs.IsValid()) - ref() = rhs.ref(); +SBDeclaration::SBDeclaration(const SBDeclaration &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBDeclaration, (const lldb::SBDeclaration &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBDeclaration::SBDeclaration(const lldb_private::Declaration *lldb_object_ptr) - : m_opaque_ap() { + : m_opaque_up() { if (lldb_object_ptr) - ref() = *lldb_object_ptr; + m_opaque_up = llvm::make_unique<Declaration>(*lldb_object_ptr); } const SBDeclaration &SBDeclaration::operator=(const SBDeclaration &rhs) { - if (this != &rhs) { - if (rhs.IsValid()) - ref() = rhs.ref(); - else - m_opaque_ap.reset(); - } - return *this; + LLDB_RECORD_METHOD(const lldb::SBDeclaration &, + SBDeclaration, operator=,(const lldb::SBDeclaration &), + rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } void SBDeclaration::SetDeclaration( @@ -50,60 +53,75 @@ SBDeclaration::~SBDeclaration() {} bool SBDeclaration::IsValid() const { - return m_opaque_ap.get() && m_opaque_ap->IsValid(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDeclaration, IsValid); + return this->operator bool(); +} +SBDeclaration::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDeclaration, operator bool); + + return m_opaque_up.get() && m_opaque_up->IsValid(); } SBFileSpec SBDeclaration::GetFileSpec() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBDeclaration, + GetFileSpec); + SBFileSpec sb_file_spec; - if (m_opaque_ap.get() && m_opaque_ap->GetFile()) - sb_file_spec.SetFileSpec(m_opaque_ap->GetFile()); + if (m_opaque_up.get() && m_opaque_up->GetFile()) + sb_file_spec.SetFileSpec(m_opaque_up->GetFile()); - if (log) { - SBStream sstr; - sb_file_spec.GetDescription(sstr); - log->Printf("SBLineEntry(%p)::GetFileSpec () => SBFileSpec(%p): %s", - static_cast<void *>(m_opaque_ap.get()), - static_cast<const void *>(sb_file_spec.get()), sstr.GetData()); - } - return sb_file_spec; + return LLDB_RECORD_RESULT(sb_file_spec); } uint32_t SBDeclaration::GetLine() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBDeclaration, GetLine); + uint32_t line = 0; - if (m_opaque_ap) - line = m_opaque_ap->GetLine(); + if (m_opaque_up) + line = m_opaque_up->GetLine(); - if (log) - log->Printf("SBLineEntry(%p)::GetLine () => %u", - static_cast<void *>(m_opaque_ap.get()), line); return line; } uint32_t SBDeclaration::GetColumn() const { - if (m_opaque_ap) - return m_opaque_ap->GetColumn(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBDeclaration, GetColumn); + + if (m_opaque_up) + return m_opaque_up->GetColumn(); return 0; } void SBDeclaration::SetFileSpec(lldb::SBFileSpec filespec) { + LLDB_RECORD_METHOD(void, SBDeclaration, SetFileSpec, (lldb::SBFileSpec), + filespec); + if (filespec.IsValid()) ref().SetFile(filespec.ref()); else ref().SetFile(FileSpec()); } -void SBDeclaration::SetLine(uint32_t line) { ref().SetLine(line); } +void SBDeclaration::SetLine(uint32_t line) { + LLDB_RECORD_METHOD(void, SBDeclaration, SetLine, (uint32_t), line); -void SBDeclaration::SetColumn(uint32_t column) { ref().SetColumn(column); } + ref().SetLine(line); +} + +void SBDeclaration::SetColumn(uint32_t column) { + LLDB_RECORD_METHOD(void, SBDeclaration, SetColumn, (uint32_t), column); + + ref().SetColumn(column); +} bool SBDeclaration::operator==(const SBDeclaration &rhs) const { - lldb_private::Declaration *lhs_ptr = m_opaque_ap.get(); - lldb_private::Declaration *rhs_ptr = rhs.m_opaque_ap.get(); + LLDB_RECORD_METHOD_CONST( + bool, SBDeclaration, operator==,(const lldb::SBDeclaration &), 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; @@ -112,8 +130,11 @@ } bool SBDeclaration::operator!=(const SBDeclaration &rhs) const { - lldb_private::Declaration *lhs_ptr = m_opaque_ap.get(); - lldb_private::Declaration *rhs_ptr = rhs.m_opaque_ap.get(); + LLDB_RECORD_METHOD_CONST( + bool, SBDeclaration, operator!=,(const lldb::SBDeclaration &), 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; @@ -122,25 +143,28 @@ } const lldb_private::Declaration *SBDeclaration::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } lldb_private::Declaration &SBDeclaration::ref() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new lldb_private::Declaration()); - return *m_opaque_ap; + if (m_opaque_up == nullptr) + m_opaque_up.reset(new lldb_private::Declaration()); + return *m_opaque_up; } const lldb_private::Declaration &SBDeclaration::ref() const { - return *m_opaque_ap; + return *m_opaque_up; } bool SBDeclaration::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBDeclaration, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); - if (m_opaque_ap) { + if (m_opaque_up) { char file_path[PATH_MAX * 2]; - m_opaque_ap->GetFile().GetPath(file_path, sizeof(file_path)); + m_opaque_up->GetFile().GetPath(file_path, sizeof(file_path)); strm.Printf("%s:%u", file_path, GetLine()); if (GetColumn() > 0) strm.Printf(":%u", GetColumn()); @@ -150,4 +174,34 @@ return true; } -lldb_private::Declaration *SBDeclaration::get() { return m_opaque_ap.get(); } +lldb_private::Declaration *SBDeclaration::get() { return m_opaque_up.get(); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBDeclaration>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBDeclaration, ()); + LLDB_REGISTER_CONSTRUCTOR(SBDeclaration, (const lldb::SBDeclaration &)); + LLDB_REGISTER_METHOD( + const lldb::SBDeclaration &, + SBDeclaration, operator=,(const lldb::SBDeclaration &)); + LLDB_REGISTER_METHOD_CONST(bool, SBDeclaration, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBDeclaration, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBDeclaration, GetFileSpec, + ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBDeclaration, GetLine, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBDeclaration, GetColumn, ()); + LLDB_REGISTER_METHOD(void, SBDeclaration, SetFileSpec, (lldb::SBFileSpec)); + LLDB_REGISTER_METHOD(void, SBDeclaration, SetLine, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBDeclaration, SetColumn, (uint32_t)); + LLDB_REGISTER_METHOD_CONST( + bool, SBDeclaration, operator==,(const lldb::SBDeclaration &)); + LLDB_REGISTER_METHOD_CONST( + bool, SBDeclaration, operator!=,(const lldb::SBDeclaration &)); + LLDB_REGISTER_METHOD(bool, SBDeclaration, GetDescription, + (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBError.cpp b/src/llvm-project/lldb/source/API/SBError.cpp index 04433bb..7256e8e 100644 --- a/src/llvm-project/lldb/source/API/SBError.cpp +++ b/src/llvm-project/lldb/source/API/SBError.cpp
@@ -1,15 +1,15 @@ //===-- SBError.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBStream.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include <stdarg.h> @@ -17,157 +17,196 @@ using namespace lldb; using namespace lldb_private; -SBError::SBError() : m_opaque_ap() {} +SBError::SBError() : m_opaque_up() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBError); } -SBError::SBError(const SBError &rhs) : m_opaque_ap() { - if (rhs.IsValid()) - m_opaque_ap.reset(new Status(*rhs)); +SBError::SBError(const SBError &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBError, (const lldb::SBError &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBError::~SBError() {} const SBError &SBError::operator=(const SBError &rhs) { - if (rhs.IsValid()) { - if (m_opaque_ap) - *m_opaque_ap = *rhs; - else - m_opaque_ap.reset(new Status(*rhs)); - } else - m_opaque_ap.reset(); + LLDB_RECORD_METHOD(const lldb::SBError &, + SBError, operator=,(const lldb::SBError &), rhs); - return *this; + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } const char *SBError::GetCString() const { - if (m_opaque_ap) - return m_opaque_ap->AsCString(); - return NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBError, GetCString); + + if (m_opaque_up) + return m_opaque_up->AsCString(); + return nullptr; } void SBError::Clear() { - if (m_opaque_ap) - m_opaque_ap->Clear(); + LLDB_RECORD_METHOD_NO_ARGS(void, SBError, Clear); + + if (m_opaque_up) + m_opaque_up->Clear(); } bool SBError::Fail() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBError, Fail); bool ret_value = false; - if (m_opaque_ap) - ret_value = m_opaque_ap->Fail(); + if (m_opaque_up) + ret_value = m_opaque_up->Fail(); - if (log) - log->Printf("SBError(%p)::Fail () => %i", - static_cast<void *>(m_opaque_ap.get()), ret_value); return ret_value; } bool SBError::Success() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - bool ret_value = true; - if (m_opaque_ap) - ret_value = m_opaque_ap->Success(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBError, Success); - if (log) - log->Printf("SBError(%p)::Success () => %i", - static_cast<void *>(m_opaque_ap.get()), ret_value); + bool ret_value = true; + if (m_opaque_up) + ret_value = m_opaque_up->Success(); return ret_value; } uint32_t SBError::GetError() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBError, GetError); + uint32_t err = 0; - if (m_opaque_ap) - err = m_opaque_ap->GetError(); + if (m_opaque_up) + err = m_opaque_up->GetError(); - if (log) - log->Printf("SBError(%p)::GetError () => 0x%8.8x", - static_cast<void *>(m_opaque_ap.get()), err); return err; } ErrorType SBError::GetType() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - ErrorType err_type = eErrorTypeInvalid; - if (m_opaque_ap) - err_type = m_opaque_ap->GetType(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::ErrorType, SBError, GetType); - if (log) - log->Printf("SBError(%p)::GetType () => %i", - static_cast<void *>(m_opaque_ap.get()), err_type); + 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_RECORD_METHOD(void, SBError, SetError, (uint32_t, lldb::ErrorType), err, + type); + CreateIfNeeded(); - m_opaque_ap->SetError(err, type); + m_opaque_up->SetError(err, type); } void SBError::SetError(const Status &lldb_error) { CreateIfNeeded(); - *m_opaque_ap = lldb_error; + *m_opaque_up = lldb_error; } void SBError::SetErrorToErrno() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBError, SetErrorToErrno); + CreateIfNeeded(); - m_opaque_ap->SetErrorToErrno(); + m_opaque_up->SetErrorToErrno(); } void SBError::SetErrorToGenericError() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBError, SetErrorToGenericError); + CreateIfNeeded(); - m_opaque_ap->SetErrorToErrno(); + m_opaque_up->SetErrorToErrno(); } void SBError::SetErrorString(const char *err_str) { + LLDB_RECORD_METHOD(void, SBError, SetErrorString, (const char *), err_str); + CreateIfNeeded(); - m_opaque_ap->SetErrorString(err_str); + 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_ap->SetErrorStringWithVarArg(format, args); + int num_chars = m_opaque_up->SetErrorStringWithVarArg(format, args); va_end(args); return num_chars; } -bool SBError::IsValid() const { return m_opaque_ap != NULL; } +bool SBError::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBError, IsValid); + return this->operator bool(); +} +SBError::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBError, operator bool); -void SBError::CreateIfNeeded() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new Status()); + return m_opaque_up != nullptr; } -lldb_private::Status *SBError::operator->() { return m_opaque_ap.get(); } +void SBError::CreateIfNeeded() { + if (m_opaque_up == nullptr) + m_opaque_up.reset(new Status()); +} -lldb_private::Status *SBError::get() { return m_opaque_ap.get(); } +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_ap; + 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_ap; + return *m_opaque_up; } bool SBError::GetDescription(SBStream &description) { - if (m_opaque_ap) { - if (m_opaque_ap->Success()) + LLDB_RECORD_METHOD(bool, SBError, GetDescription, (lldb::SBStream &), + 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 != NULL ? err_string : "")); + description.Printf("error: %s", + (err_string != nullptr ? err_string : "")); } } else description.Printf("error: <NULL>"); return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBError>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBError, ()); + LLDB_REGISTER_CONSTRUCTOR(SBError, (const lldb::SBError &)); + LLDB_REGISTER_METHOD(const lldb::SBError &, + SBError, operator=,(const lldb::SBError &)); + LLDB_REGISTER_METHOD_CONST(const char *, SBError, GetCString, ()); + LLDB_REGISTER_METHOD(void, SBError, Clear, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBError, Fail, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBError, Success, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBError, GetError, ()); + LLDB_REGISTER_METHOD_CONST(lldb::ErrorType, SBError, GetType, ()); + LLDB_REGISTER_METHOD(void, SBError, SetError, (uint32_t, lldb::ErrorType)); + LLDB_REGISTER_METHOD(void, SBError, SetErrorToErrno, ()); + LLDB_REGISTER_METHOD(void, SBError, SetErrorToGenericError, ()); + LLDB_REGISTER_METHOD(void, SBError, SetErrorString, (const char *)); + LLDB_REGISTER_METHOD_CONST(bool, SBError, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBError, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBError, GetDescription, (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBEvent.cpp b/src/llvm-project/lldb/source/API/SBEvent.cpp index 0556f50..75ca283 100644 --- a/src/llvm-project/lldb/source/API/SBEvent.cpp +++ b/src/llvm-project/lldb/source/API/SBEvent.cpp
@@ -1,13 +1,13 @@ //===-- SBEvent.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBBroadcaster.h" #include "lldb/API/SBStream.h" @@ -22,71 +22,83 @@ using namespace lldb; using namespace lldb_private; -SBEvent::SBEvent() : m_event_sp(), m_opaque_ptr(NULL) {} +SBEvent::SBEvent() : m_event_sp(), m_opaque_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBEvent); +} SBEvent::SBEvent(uint32_t event_type, const char *cstr, uint32_t cstr_len) : m_event_sp(new Event(event_type, new EventDataBytes(cstr, cstr_len))), - m_opaque_ptr(m_event_sp.get()) {} + m_opaque_ptr(m_event_sp.get()) { + LLDB_RECORD_CONSTRUCTOR(SBEvent, (uint32_t, const char *, uint32_t), + event_type, cstr, cstr_len); +} SBEvent::SBEvent(EventSP &event_sp) - : m_event_sp(event_sp), m_opaque_ptr(event_sp.get()) {} + : m_event_sp(event_sp), m_opaque_ptr(event_sp.get()) { + LLDB_RECORD_CONSTRUCTOR(SBEvent, (lldb::EventSP &), event_sp); +} -SBEvent::SBEvent(Event *event_ptr) : m_event_sp(), m_opaque_ptr(event_ptr) {} +SBEvent::SBEvent(Event *event_ptr) : m_event_sp(), m_opaque_ptr(event_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBEvent, (lldb_private::Event *), event_ptr); +} SBEvent::SBEvent(const SBEvent &rhs) - : m_event_sp(rhs.m_event_sp), m_opaque_ptr(rhs.m_opaque_ptr) {} + : m_event_sp(rhs.m_event_sp), m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBEvent, (const lldb::SBEvent &), rhs); +} const SBEvent &SBEvent::operator=(const SBEvent &rhs) { + LLDB_RECORD_METHOD(const lldb::SBEvent &, + SBEvent, operator=,(const lldb::SBEvent &), rhs); + if (this != &rhs) { m_event_sp = rhs.m_event_sp; m_opaque_ptr = rhs.m_opaque_ptr; } - return *this; + return LLDB_RECORD_RESULT(*this); } SBEvent::~SBEvent() {} const char *SBEvent::GetDataFlavor() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBEvent, GetDataFlavor); + Event *lldb_event = get(); if (lldb_event) { EventData *event_data = lldb_event->GetData(); if (event_data) return lldb_event->GetData()->GetFlavor().AsCString(); } - return NULL; + return nullptr; } uint32_t SBEvent::GetType() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBEvent, GetType); + const Event *lldb_event = get(); uint32_t event_type = 0; if (lldb_event) event_type = lldb_event->GetType(); - if (log) { - StreamString sstr; - if (lldb_event && lldb_event->GetBroadcaster() && - lldb_event->GetBroadcaster()->GetEventNames(sstr, event_type, true)) - log->Printf("SBEvent(%p)::GetType () => 0x%8.8x (%s)", - static_cast<void *>(get()), event_type, sstr.GetData()); - else - log->Printf("SBEvent(%p)::GetType () => 0x%8.8x", - static_cast<void *>(get()), event_type); - } return event_type; } SBBroadcaster SBEvent::GetBroadcaster() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBroadcaster, SBEvent, + GetBroadcaster); + SBBroadcaster broadcaster; const Event *lldb_event = get(); if (lldb_event) broadcaster.reset(lldb_event->GetBroadcaster(), false); - return broadcaster; + return LLDB_RECORD_RESULT(broadcaster); } const char *SBEvent::GetBroadcasterClass() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBEvent, GetBroadcasterClass); + const Event *lldb_event = get(); if (lldb_event) return lldb_event->GetBroadcaster()->GetBroadcasterClass().AsCString(); @@ -95,28 +107,30 @@ } bool SBEvent::BroadcasterMatchesPtr(const SBBroadcaster *broadcaster) { + LLDB_RECORD_METHOD(bool, SBEvent, BroadcasterMatchesPtr, + (const lldb::SBBroadcaster *), broadcaster); + if (broadcaster) return BroadcasterMatchesRef(*broadcaster); return false; } bool SBEvent::BroadcasterMatchesRef(const SBBroadcaster &broadcaster) { + LLDB_RECORD_METHOD(bool, SBEvent, BroadcasterMatchesRef, + (const lldb::SBBroadcaster &), broadcaster); Event *lldb_event = get(); bool success = false; if (lldb_event) success = lldb_event->BroadcasterIs(broadcaster.get()); - // For logging, this gets a little chatty so only enable this when verbose - // logging is on - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - LLDB_LOGV(log, "({0}) (SBBroadcaster({1}): {2}) => {3}", get(), - broadcaster.get(), broadcaster.GetName(), success); return success; } void SBEvent::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBEvent, Clear); + Event *lldb_event = get(); if (lldb_event) lldb_event->Clear(); @@ -146,25 +160,29 @@ } bool SBEvent::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBEvent, IsValid); + return this->operator bool(); +} +SBEvent::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBEvent, operator bool); + // Do NOT use m_opaque_ptr directly!!! Must use the SBEvent::get() accessor. // See comments in SBEvent::get().... - return SBEvent::get() != NULL; + return SBEvent::get() != nullptr; } const char *SBEvent::GetCStringFromEvent(const SBEvent &event) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf("SBEvent(%p)::GetCStringFromEvent () => \"%s\"", - static_cast<void *>(event.get()), - reinterpret_cast<const char *>( - EventDataBytes::GetBytesFromEvent(event.get()))); + LLDB_RECORD_STATIC_METHOD(const char *, SBEvent, GetCStringFromEvent, + (const lldb::SBEvent &), event); return reinterpret_cast<const char *>( EventDataBytes::GetBytesFromEvent(event.get())); } bool SBEvent::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBEvent, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); if (get()) { @@ -176,6 +194,9 @@ } bool SBEvent::GetDescription(SBStream &description) const { + LLDB_RECORD_METHOD_CONST(bool, SBEvent, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); if (get()) { @@ -185,3 +206,37 @@ return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBEvent>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBEvent, ()); + LLDB_REGISTER_CONSTRUCTOR(SBEvent, (uint32_t, const char *, uint32_t)); + LLDB_REGISTER_CONSTRUCTOR(SBEvent, (lldb::EventSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBEvent, (lldb_private::Event *)); + LLDB_REGISTER_CONSTRUCTOR(SBEvent, (const lldb::SBEvent &)); + LLDB_REGISTER_METHOD(const lldb::SBEvent &, + SBEvent, operator=,(const lldb::SBEvent &)); + LLDB_REGISTER_METHOD(const char *, SBEvent, GetDataFlavor, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBEvent, GetType, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBBroadcaster, SBEvent, GetBroadcaster, + ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBEvent, GetBroadcasterClass, ()); + LLDB_REGISTER_METHOD(bool, SBEvent, BroadcasterMatchesPtr, + (const lldb::SBBroadcaster *)); + LLDB_REGISTER_METHOD(bool, SBEvent, BroadcasterMatchesRef, + (const lldb::SBBroadcaster &)); + LLDB_REGISTER_METHOD(void, SBEvent, Clear, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBEvent, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBEvent, operator bool, ()); + LLDB_REGISTER_STATIC_METHOD(const char *, SBEvent, GetCStringFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_METHOD(bool, SBEvent, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(bool, SBEvent, GetDescription, + (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBExecutionContext.cpp b/src/llvm-project/lldb/source/API/SBExecutionContext.cpp index 74a543c..1224c2a 100644 --- a/src/llvm-project/lldb/source/API/SBExecutionContext.cpp +++ b/src/llvm-project/lldb/source/API/SBExecutionContext.cpp
@@ -1,14 +1,14 @@ //===-- SBExecutionContext.cpp ------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBFrame.h" #include "lldb/API/SBProcess.h" @@ -20,32 +20,49 @@ using namespace lldb; using namespace lldb_private; -SBExecutionContext::SBExecutionContext() : m_exe_ctx_sp() {} +SBExecutionContext::SBExecutionContext() : m_exe_ctx_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBExecutionContext); +} SBExecutionContext::SBExecutionContext(const lldb::SBExecutionContext &rhs) - : m_exe_ctx_sp(rhs.m_exe_ctx_sp) {} + : m_exe_ctx_sp(rhs.m_exe_ctx_sp) { + LLDB_RECORD_CONSTRUCTOR(SBExecutionContext, + (const lldb::SBExecutionContext &), rhs); +} SBExecutionContext::SBExecutionContext( lldb::ExecutionContextRefSP exe_ctx_ref_sp) - : m_exe_ctx_sp(exe_ctx_ref_sp) {} + : m_exe_ctx_sp(exe_ctx_ref_sp) { + LLDB_RECORD_CONSTRUCTOR(SBExecutionContext, (lldb::ExecutionContextRefSP), + exe_ctx_ref_sp); +} SBExecutionContext::SBExecutionContext(const lldb::SBTarget &target) : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_RECORD_CONSTRUCTOR(SBExecutionContext, (const lldb::SBTarget &), target); + m_exe_ctx_sp->SetTargetSP(target.GetSP()); } SBExecutionContext::SBExecutionContext(const lldb::SBProcess &process) : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_RECORD_CONSTRUCTOR(SBExecutionContext, (const lldb::SBProcess &), + process); + m_exe_ctx_sp->SetProcessSP(process.GetSP()); } SBExecutionContext::SBExecutionContext(lldb::SBThread thread) : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_RECORD_CONSTRUCTOR(SBExecutionContext, (lldb::SBThread), thread); + m_exe_ctx_sp->SetThreadPtr(thread.get()); } SBExecutionContext::SBExecutionContext(const lldb::SBFrame &frame) : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_RECORD_CONSTRUCTOR(SBExecutionContext, (const lldb::SBFrame &), frame); + m_exe_ctx_sp->SetFrameSP(frame.GetFrameSP()); } @@ -53,8 +70,12 @@ const SBExecutionContext &SBExecutionContext:: operator=(const lldb::SBExecutionContext &rhs) { + LLDB_RECORD_METHOD( + const lldb::SBExecutionContext &, + SBExecutionContext, operator=,(const lldb::SBExecutionContext &), rhs); + m_exe_ctx_sp = rhs.m_exe_ctx_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } ExecutionContextRef *SBExecutionContext::get() const { @@ -62,41 +83,81 @@ } SBTarget SBExecutionContext::GetTarget() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBTarget, SBExecutionContext, + GetTarget); + 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; + return LLDB_RECORD_RESULT(sb_target); } SBProcess SBExecutionContext::GetProcess() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBProcess, SBExecutionContext, + GetProcess); + 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; + return LLDB_RECORD_RESULT(sb_process); } SBThread SBExecutionContext::GetThread() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBThread, SBExecutionContext, + GetThread); + 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; + return LLDB_RECORD_RESULT(sb_thread); } SBFrame SBExecutionContext::GetFrame() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFrame, SBExecutionContext, GetFrame); + 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; + return LLDB_RECORD_RESULT(sb_frame); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBExecutionContext>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBExecutionContext, ()); + LLDB_REGISTER_CONSTRUCTOR(SBExecutionContext, + (const lldb::SBExecutionContext &)); + LLDB_REGISTER_CONSTRUCTOR(SBExecutionContext, + (lldb::ExecutionContextRefSP)); + LLDB_REGISTER_CONSTRUCTOR(SBExecutionContext, (const lldb::SBTarget &)); + LLDB_REGISTER_CONSTRUCTOR(SBExecutionContext, (const lldb::SBProcess &)); + LLDB_REGISTER_CONSTRUCTOR(SBExecutionContext, (lldb::SBThread)); + LLDB_REGISTER_CONSTRUCTOR(SBExecutionContext, (const lldb::SBFrame &)); + LLDB_REGISTER_METHOD( + const lldb::SBExecutionContext &, + SBExecutionContext, operator=,(const lldb::SBExecutionContext &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBTarget, SBExecutionContext, GetTarget, + ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBProcess, SBExecutionContext, GetProcess, + ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBThread, SBExecutionContext, GetThread, + ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBFrame, SBExecutionContext, GetFrame, ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBExpressionOptions.cpp b/src/llvm-project/lldb/source/API/SBExpressionOptions.cpp index 76cec87..8c34194 100644 --- a/src/llvm-project/lldb/source/API/SBExpressionOptions.cpp +++ b/src/llvm-project/lldb/source/API/SBExpressionOptions.cpp
@@ -1,177 +1,336 @@ //===-- SBExpressionOptions.cpp ---------------------------------------------*- //C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBStream.h" - #include "lldb/Target/Target.h" using namespace lldb; using namespace lldb_private; SBExpressionOptions::SBExpressionOptions() - : m_opaque_ap(new EvaluateExpressionOptions()) {} + : m_opaque_up(new EvaluateExpressionOptions()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBExpressionOptions); +} -SBExpressionOptions::SBExpressionOptions(const SBExpressionOptions &rhs) { - m_opaque_ap.reset(new EvaluateExpressionOptions()); - *(m_opaque_ap.get()) = rhs.ref(); +SBExpressionOptions::SBExpressionOptions(const SBExpressionOptions &rhs) + : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBExpressionOptions, + (const lldb::SBExpressionOptions &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } const SBExpressionOptions &SBExpressionOptions:: operator=(const SBExpressionOptions &rhs) { - if (this != &rhs) { - this->ref() = rhs.ref(); - } - return *this; + LLDB_RECORD_METHOD( + const lldb::SBExpressionOptions &, + SBExpressionOptions, operator=,(const lldb::SBExpressionOptions &), rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } SBExpressionOptions::~SBExpressionOptions() {} bool SBExpressionOptions::GetCoerceResultToId() const { - return m_opaque_ap->DoesCoerceToId(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBExpressionOptions, + GetCoerceResultToId); + + return m_opaque_up->DoesCoerceToId(); } void SBExpressionOptions::SetCoerceResultToId(bool coerce) { - m_opaque_ap->SetCoerceToId(coerce); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetCoerceResultToId, (bool), + coerce); + + m_opaque_up->SetCoerceToId(coerce); } bool SBExpressionOptions::GetUnwindOnError() const { - return m_opaque_ap->DoesUnwindOnError(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBExpressionOptions, GetUnwindOnError); + + return m_opaque_up->DoesUnwindOnError(); } void SBExpressionOptions::SetUnwindOnError(bool unwind) { - m_opaque_ap->SetUnwindOnError(unwind); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetUnwindOnError, (bool), + unwind); + + m_opaque_up->SetUnwindOnError(unwind); } bool SBExpressionOptions::GetIgnoreBreakpoints() const { - return m_opaque_ap->DoesIgnoreBreakpoints(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBExpressionOptions, + GetIgnoreBreakpoints); + + return m_opaque_up->DoesIgnoreBreakpoints(); } void SBExpressionOptions::SetIgnoreBreakpoints(bool ignore) { - m_opaque_ap->SetIgnoreBreakpoints(ignore); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetIgnoreBreakpoints, (bool), + ignore); + + m_opaque_up->SetIgnoreBreakpoints(ignore); } lldb::DynamicValueType SBExpressionOptions::GetFetchDynamicValue() const { - return m_opaque_ap->GetUseDynamic(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::DynamicValueType, SBExpressionOptions, + GetFetchDynamicValue); + + return m_opaque_up->GetUseDynamic(); } void SBExpressionOptions::SetFetchDynamicValue(lldb::DynamicValueType dynamic) { - m_opaque_ap->SetUseDynamic(dynamic); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetFetchDynamicValue, + (lldb::DynamicValueType), dynamic); + + m_opaque_up->SetUseDynamic(dynamic); } uint32_t SBExpressionOptions::GetTimeoutInMicroSeconds() const { - return m_opaque_ap->GetTimeout() ? m_opaque_ap->GetTimeout()->count() : 0; + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBExpressionOptions, + GetTimeoutInMicroSeconds); + + return m_opaque_up->GetTimeout() ? m_opaque_up->GetTimeout()->count() : 0; } void SBExpressionOptions::SetTimeoutInMicroSeconds(uint32_t timeout) { - m_opaque_ap->SetTimeout(timeout == 0 ? Timeout<std::micro>(llvm::None) + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetTimeoutInMicroSeconds, + (uint32_t), timeout); + + m_opaque_up->SetTimeout(timeout == 0 ? Timeout<std::micro>(llvm::None) : std::chrono::microseconds(timeout)); } uint32_t SBExpressionOptions::GetOneThreadTimeoutInMicroSeconds() const { - return m_opaque_ap->GetOneThreadTimeout() ? m_opaque_ap->GetOneThreadTimeout()->count() : 0; + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBExpressionOptions, + GetOneThreadTimeoutInMicroSeconds); + + return m_opaque_up->GetOneThreadTimeout() + ? m_opaque_up->GetOneThreadTimeout()->count() + : 0; } void SBExpressionOptions::SetOneThreadTimeoutInMicroSeconds(uint32_t timeout) { - m_opaque_ap->SetOneThreadTimeout(timeout == 0 + LLDB_RECORD_METHOD(void, SBExpressionOptions, + SetOneThreadTimeoutInMicroSeconds, (uint32_t), timeout); + + m_opaque_up->SetOneThreadTimeout(timeout == 0 ? Timeout<std::micro>(llvm::None) : std::chrono::microseconds(timeout)); } bool SBExpressionOptions::GetTryAllThreads() const { - return m_opaque_ap->GetTryAllThreads(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBExpressionOptions, GetTryAllThreads); + + return m_opaque_up->GetTryAllThreads(); } void SBExpressionOptions::SetTryAllThreads(bool run_others) { - m_opaque_ap->SetTryAllThreads(run_others); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetTryAllThreads, (bool), + run_others); + + m_opaque_up->SetTryAllThreads(run_others); } bool SBExpressionOptions::GetStopOthers() const { - return m_opaque_ap->GetStopOthers(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBExpressionOptions, GetStopOthers); + + return m_opaque_up->GetStopOthers(); } void SBExpressionOptions::SetStopOthers(bool run_others) { - m_opaque_ap->SetStopOthers(run_others); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetStopOthers, (bool), + run_others); + + m_opaque_up->SetStopOthers(run_others); } bool SBExpressionOptions::GetTrapExceptions() const { - return m_opaque_ap->GetTrapExceptions(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBExpressionOptions, + GetTrapExceptions); + + return m_opaque_up->GetTrapExceptions(); } void SBExpressionOptions::SetTrapExceptions(bool trap_exceptions) { - m_opaque_ap->SetTrapExceptions(trap_exceptions); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetTrapExceptions, (bool), + trap_exceptions); + + m_opaque_up->SetTrapExceptions(trap_exceptions); } void SBExpressionOptions::SetLanguage(lldb::LanguageType language) { - m_opaque_ap->SetLanguage(language); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetLanguage, + (lldb::LanguageType), language); + + m_opaque_up->SetLanguage(language); } void SBExpressionOptions::SetCancelCallback( lldb::ExpressionCancelCallback callback, void *baton) { - m_opaque_ap->SetCancelCallback(callback, baton); + LLDB_RECORD_DUMMY(void, SBExpressionOptions, SetCancelCallback, + (lldb::ExpressionCancelCallback, void *), callback, baton); + + m_opaque_up->SetCancelCallback(callback, baton); } bool SBExpressionOptions::GetGenerateDebugInfo() { - return m_opaque_ap->GetGenerateDebugInfo(); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBExpressionOptions, GetGenerateDebugInfo); + + return m_opaque_up->GetGenerateDebugInfo(); } void SBExpressionOptions::SetGenerateDebugInfo(bool b) { - return m_opaque_ap->SetGenerateDebugInfo(b); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetGenerateDebugInfo, (bool), + b); + + return m_opaque_up->SetGenerateDebugInfo(b); } bool SBExpressionOptions::GetSuppressPersistentResult() { - return m_opaque_ap->GetResultIsInternal(); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBExpressionOptions, + GetSuppressPersistentResult); + + return m_opaque_up->GetResultIsInternal(); } void SBExpressionOptions::SetSuppressPersistentResult(bool b) { - return m_opaque_ap->SetResultIsInternal(b); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetSuppressPersistentResult, + (bool), b); + + return m_opaque_up->SetResultIsInternal(b); } const char *SBExpressionOptions::GetPrefix() const { - return m_opaque_ap->GetPrefix(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBExpressionOptions, + GetPrefix); + + return m_opaque_up->GetPrefix(); } void SBExpressionOptions::SetPrefix(const char *prefix) { - return m_opaque_ap->SetPrefix(prefix); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetPrefix, (const char *), + prefix); + + return m_opaque_up->SetPrefix(prefix); } bool SBExpressionOptions::GetAutoApplyFixIts() { - return m_opaque_ap->GetAutoApplyFixIts(); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBExpressionOptions, GetAutoApplyFixIts); + + return m_opaque_up->GetAutoApplyFixIts(); } void SBExpressionOptions::SetAutoApplyFixIts(bool b) { - return m_opaque_ap->SetAutoApplyFixIts(b); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetAutoApplyFixIts, (bool), b); + + return m_opaque_up->SetAutoApplyFixIts(b); } bool SBExpressionOptions::GetTopLevel() { - return m_opaque_ap->GetExecutionPolicy() == eExecutionPolicyTopLevel; + LLDB_RECORD_METHOD_NO_ARGS(bool, SBExpressionOptions, GetTopLevel); + + return m_opaque_up->GetExecutionPolicy() == eExecutionPolicyTopLevel; } void SBExpressionOptions::SetTopLevel(bool b) { - m_opaque_ap->SetExecutionPolicy(b ? eExecutionPolicyTopLevel - : m_opaque_ap->default_execution_policy); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetTopLevel, (bool), b); + + m_opaque_up->SetExecutionPolicy(b ? eExecutionPolicyTopLevel + : m_opaque_up->default_execution_policy); } bool SBExpressionOptions::GetAllowJIT() { - return m_opaque_ap->GetExecutionPolicy() != eExecutionPolicyNever; + LLDB_RECORD_METHOD_NO_ARGS(bool, SBExpressionOptions, GetAllowJIT); + + return m_opaque_up->GetExecutionPolicy() != eExecutionPolicyNever; } void SBExpressionOptions::SetAllowJIT(bool allow) { - m_opaque_ap->SetExecutionPolicy(allow ? m_opaque_ap->default_execution_policy - : eExecutionPolicyNever); + LLDB_RECORD_METHOD(void, SBExpressionOptions, SetAllowJIT, (bool), allow); + + m_opaque_up->SetExecutionPolicy(allow ? m_opaque_up->default_execution_policy + : eExecutionPolicyNever); } EvaluateExpressionOptions *SBExpressionOptions::get() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } EvaluateExpressionOptions &SBExpressionOptions::ref() const { - return *(m_opaque_ap.get()); + return *(m_opaque_up.get()); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBExpressionOptions>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBExpressionOptions, ()); + LLDB_REGISTER_CONSTRUCTOR(SBExpressionOptions, + (const lldb::SBExpressionOptions &)); + LLDB_REGISTER_METHOD( + const lldb::SBExpressionOptions &, + SBExpressionOptions, operator=,(const lldb::SBExpressionOptions &)); + LLDB_REGISTER_METHOD_CONST(bool, SBExpressionOptions, GetCoerceResultToId, + ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetCoerceResultToId, + (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBExpressionOptions, GetUnwindOnError, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetUnwindOnError, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBExpressionOptions, GetIgnoreBreakpoints, + ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetIgnoreBreakpoints, + (bool)); + LLDB_REGISTER_METHOD_CONST(lldb::DynamicValueType, SBExpressionOptions, + GetFetchDynamicValue, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetFetchDynamicValue, + (lldb::DynamicValueType)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBExpressionOptions, + GetTimeoutInMicroSeconds, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetTimeoutInMicroSeconds, + (uint32_t)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBExpressionOptions, + GetOneThreadTimeoutInMicroSeconds, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, + SetOneThreadTimeoutInMicroSeconds, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(bool, SBExpressionOptions, GetTryAllThreads, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetTryAllThreads, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBExpressionOptions, GetStopOthers, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetStopOthers, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBExpressionOptions, GetTrapExceptions, + ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetTrapExceptions, (bool)); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetLanguage, + (lldb::LanguageType)); + LLDB_REGISTER_METHOD(bool, SBExpressionOptions, GetGenerateDebugInfo, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetGenerateDebugInfo, + (bool)); + LLDB_REGISTER_METHOD(bool, SBExpressionOptions, GetSuppressPersistentResult, + ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetSuppressPersistentResult, + (bool)); + LLDB_REGISTER_METHOD_CONST(const char *, SBExpressionOptions, GetPrefix, + ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetPrefix, (const char *)); + LLDB_REGISTER_METHOD(bool, SBExpressionOptions, GetAutoApplyFixIts, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetAutoApplyFixIts, (bool)); + LLDB_REGISTER_METHOD(bool, SBExpressionOptions, GetTopLevel, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetTopLevel, (bool)); + LLDB_REGISTER_METHOD(bool, SBExpressionOptions, GetAllowJIT, ()); + LLDB_REGISTER_METHOD(void, SBExpressionOptions, SetAllowJIT, (bool)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBFileSpec.cpp b/src/llvm-project/lldb/source/API/SBFileSpec.cpp index f136409..2f910b9 100644 --- a/src/llvm-project/lldb/source/API/SBFileSpec.cpp +++ b/src/llvm-project/lldb/source/API/SBFileSpec.cpp
@@ -1,76 +1,109 @@ //===-- SBFileSpec.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <inttypes.h> -#include <limits.h> - #include "lldb/API/SBFileSpec.h" +#include "SBReproducerPrivate.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/Log.h" #include "lldb/Utility/Stream.h" #include "llvm/ADT/SmallString.h" +#include <inttypes.h> +#include <limits.h> + using namespace lldb; using namespace lldb_private; -SBFileSpec::SBFileSpec() : m_opaque_ap(new lldb_private::FileSpec()) {} +SBFileSpec::SBFileSpec() : m_opaque_up(new lldb_private::FileSpec()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBFileSpec); +} -SBFileSpec::SBFileSpec(const SBFileSpec &rhs) - : m_opaque_ap(new lldb_private::FileSpec(*rhs.m_opaque_ap)) {} +SBFileSpec::SBFileSpec(const SBFileSpec &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBFileSpec, (const lldb::SBFileSpec &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} SBFileSpec::SBFileSpec(const lldb_private::FileSpec &fspec) - : m_opaque_ap(new lldb_private::FileSpec(fspec)) {} + : m_opaque_up(new lldb_private::FileSpec(fspec)) {} // Deprecated!!! -SBFileSpec::SBFileSpec(const char *path) : m_opaque_ap(new FileSpec(path)) { - FileSystem::Instance().Resolve(*m_opaque_ap); +SBFileSpec::SBFileSpec(const char *path) : m_opaque_up(new FileSpec(path)) { + LLDB_RECORD_CONSTRUCTOR(SBFileSpec, (const char *), path); + + FileSystem::Instance().Resolve(*m_opaque_up); } SBFileSpec::SBFileSpec(const char *path, bool resolve) - : m_opaque_ap(new FileSpec(path)) { + : m_opaque_up(new FileSpec(path)) { + LLDB_RECORD_CONSTRUCTOR(SBFileSpec, (const char *, bool), path, resolve); + if (resolve) - FileSystem::Instance().Resolve(*m_opaque_ap); + FileSystem::Instance().Resolve(*m_opaque_up); } SBFileSpec::~SBFileSpec() {} const SBFileSpec &SBFileSpec::operator=(const SBFileSpec &rhs) { + LLDB_RECORD_METHOD(const lldb::SBFileSpec &, + SBFileSpec, operator=,(const lldb::SBFileSpec &), rhs); + if (this != &rhs) - *m_opaque_ap = *rhs.m_opaque_ap; - return *this; + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } -bool SBFileSpec::IsValid() const { return m_opaque_ap->operator bool(); } +bool SBFileSpec::operator==(const SBFileSpec &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBFileSpec, operator==,(const SBFileSpec &rhs), + rhs); + + return ref() == rhs.ref(); +} + +bool SBFileSpec::operator!=(const SBFileSpec &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBFileSpec, operator!=,(const SBFileSpec &rhs), + rhs); + + return !(*this == rhs); +} + +bool SBFileSpec::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFileSpec, IsValid); + return this->operator bool(); +} +SBFileSpec::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFileSpec, operator bool); + + return m_opaque_up->operator bool(); +} bool SBFileSpec::Exists() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFileSpec, Exists); - bool result = FileSystem::Instance().Exists(*m_opaque_ap); - - if (log) - log->Printf("SBFileSpec(%p)::Exists () => %s", - static_cast<void *>(m_opaque_ap.get()), - (result ? "true" : "false")); - - return result; + return FileSystem::Instance().Exists(*m_opaque_up); } bool SBFileSpec::ResolveExecutableLocation() { - return FileSystem::Instance().ResolveExecutableLocation(*m_opaque_ap); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBFileSpec, ResolveExecutableLocation); + + return FileSystem::Instance().ResolveExecutableLocation(*m_opaque_up); } int SBFileSpec::ResolvePath(const char *src_path, char *dst_path, size_t dst_len) { + LLDB_RECORD_STATIC_METHOD(int, SBFileSpec, ResolvePath, + (const char *, char *, size_t), 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()); @@ -78,61 +111,42 @@ } const char *SBFileSpec::GetFilename() const { - const char *s = m_opaque_ap->GetFilename().AsCString(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFileSpec, GetFilename); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (s) - log->Printf("SBFileSpec(%p)::GetFilename () => \"%s\"", - static_cast<void *>(m_opaque_ap.get()), s); - else - log->Printf("SBFileSpec(%p)::GetFilename () => NULL", - static_cast<void *>(m_opaque_ap.get())); - } - - return s; + return m_opaque_up->GetFilename().AsCString(); } const char *SBFileSpec::GetDirectory() const { - FileSpec directory{*m_opaque_ap}; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFileSpec, GetDirectory); + + FileSpec directory{*m_opaque_up}; directory.GetFilename().Clear(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (directory) - log->Printf("SBFileSpec(%p)::GetDirectory () => \"%s\"", - static_cast<void *>(m_opaque_ap.get()), - directory.GetCString()); - else - log->Printf("SBFileSpec(%p)::GetDirectory () => NULL", - static_cast<void *>(m_opaque_ap.get())); - } return directory.GetCString(); } void SBFileSpec::SetFilename(const char *filename) { + LLDB_RECORD_METHOD(void, SBFileSpec, SetFilename, (const char *), filename); + if (filename && filename[0]) - m_opaque_ap->GetFilename().SetCString(filename); + m_opaque_up->GetFilename().SetCString(filename); else - m_opaque_ap->GetFilename().Clear(); + m_opaque_up->GetFilename().Clear(); } void SBFileSpec::SetDirectory(const char *directory) { + LLDB_RECORD_METHOD(void, SBFileSpec, SetDirectory, (const char *), directory); + if (directory && directory[0]) - m_opaque_ap->GetDirectory().SetCString(directory); + m_opaque_up->GetDirectory().SetCString(directory); else - m_opaque_ap->GetDirectory().Clear(); + m_opaque_up->GetDirectory().Clear(); } uint32_t SBFileSpec::GetPath(char *dst_path, size_t dst_len) const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(uint32_t, SBFileSpec, GetPath, (char *, size_t), + dst_path, dst_len); - uint32_t result = m_opaque_ap->GetPath(dst_path, dst_len); - - if (log) - log->Printf("SBFileSpec(%p)::GetPath (dst_path=\"%.*s\", dst_len=%" PRIu64 - ") => %u", - static_cast<void *>(m_opaque_ap.get()), result, dst_path, - static_cast<uint64_t>(dst_len), result); + uint32_t result = m_opaque_up->GetPath(dst_path, dst_len); if (result == 0 && dst_path && dst_len > 0) *dst_path = '\0'; @@ -140,31 +154,70 @@ } const lldb_private::FileSpec *SBFileSpec::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const lldb_private::FileSpec *SBFileSpec::get() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const lldb_private::FileSpec &SBFileSpec::operator*() const { - return *m_opaque_ap; + return *m_opaque_up; } -const lldb_private::FileSpec &SBFileSpec::ref() const { return *m_opaque_ap; } +const lldb_private::FileSpec &SBFileSpec::ref() const { return *m_opaque_up; } void SBFileSpec::SetFileSpec(const lldb_private::FileSpec &fs) { - *m_opaque_ap = fs; + *m_opaque_up = fs; } bool SBFileSpec::GetDescription(SBStream &description) const { + LLDB_RECORD_METHOD_CONST(bool, SBFileSpec, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); char path[PATH_MAX]; - if (m_opaque_ap->GetPath(path, sizeof(path))) + if (m_opaque_up->GetPath(path, sizeof(path))) strm.PutCString(path); return true; } void SBFileSpec::AppendPathComponent(const char *fn) { - m_opaque_ap->AppendPathComponent(fn); + LLDB_RECORD_METHOD(void, SBFileSpec, AppendPathComponent, (const char *), fn); + + m_opaque_up->AppendPathComponent(fn); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBFileSpec>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, ()); + LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, (const lldb::SBFileSpec &)); + LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, (const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, (const char *, bool)); + LLDB_REGISTER_METHOD(const lldb::SBFileSpec &, + SBFileSpec, operator=,(const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBFileSpec, operator==,(const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBFileSpec, operator!=,(const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, Exists, ()); + LLDB_REGISTER_METHOD(bool, SBFileSpec, ResolveExecutableLocation, ()); + LLDB_REGISTER_STATIC_METHOD(int, SBFileSpec, ResolvePath, + (const char *, char *, size_t)); + LLDB_REGISTER_METHOD_CONST(const char *, SBFileSpec, GetFilename, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBFileSpec, GetDirectory, ()); + LLDB_REGISTER_METHOD(void, SBFileSpec, SetFilename, (const char *)); + LLDB_REGISTER_METHOD(void, SBFileSpec, SetDirectory, (const char *)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBFileSpec, GetPath, (char *, size_t)); + LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(void, SBFileSpec, AppendPathComponent, (const char *)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBFileSpecList.cpp b/src/llvm-project/lldb/source/API/SBFileSpecList.cpp index 439859c..3143964 100644 --- a/src/llvm-project/lldb/source/API/SBFileSpecList.cpp +++ b/src/llvm-project/lldb/source/API/SBFileSpecList.cpp
@@ -1,99 +1,121 @@ //===-- SBFileSpecList.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <limits.h> - -#include "lldb/API/SBFileSpec.h" #include "lldb/API/SBFileSpecList.h" +#include "SBReproducerPrivate.h" +#include "Utils.h" +#include "lldb/API/SBFileSpec.h" #include "lldb/API/SBStream.h" #include "lldb/Core/FileSpecList.h" #include "lldb/Host/PosixApi.h" #include "lldb/Utility/FileSpec.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" +#include <limits.h> + using namespace lldb; using namespace lldb_private; -SBFileSpecList::SBFileSpecList() : m_opaque_ap(new FileSpecList()) {} +SBFileSpecList::SBFileSpecList() : m_opaque_up(new FileSpecList()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBFileSpecList); +} -SBFileSpecList::SBFileSpecList(const SBFileSpecList &rhs) : m_opaque_ap() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +SBFileSpecList::SBFileSpecList(const SBFileSpecList &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBFileSpecList, (const lldb::SBFileSpecList &), rhs); - if (rhs.m_opaque_ap) - m_opaque_ap.reset(new FileSpecList(*(rhs.get()))); - if (log) { - log->Printf("SBFileSpecList::SBFileSpecList (const SBFileSpecList " - "rhs.ap=%p) => SBFileSpecList(%p)", - static_cast<void *>(rhs.m_opaque_ap.get()), - static_cast<void *>(m_opaque_ap.get())); - } + m_opaque_up = clone(rhs.m_opaque_up); } SBFileSpecList::~SBFileSpecList() {} const SBFileSpecList &SBFileSpecList::operator=(const SBFileSpecList &rhs) { - if (this != &rhs) { - m_opaque_ap.reset(new lldb_private::FileSpecList(*(rhs.get()))); - } - return *this; + LLDB_RECORD_METHOD(const lldb::SBFileSpecList &, + SBFileSpecList, operator=,(const lldb::SBFileSpecList &), + rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } -uint32_t SBFileSpecList::GetSize() const { return m_opaque_ap->GetSize(); } +uint32_t SBFileSpecList::GetSize() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBFileSpecList, GetSize); + + return m_opaque_up->GetSize(); +} void SBFileSpecList::Append(const SBFileSpec &sb_file) { - m_opaque_ap->Append(sb_file.ref()); + LLDB_RECORD_METHOD(void, SBFileSpecList, Append, (const lldb::SBFileSpec &), + sb_file); + + m_opaque_up->Append(sb_file.ref()); } bool SBFileSpecList::AppendIfUnique(const SBFileSpec &sb_file) { - return m_opaque_ap->AppendIfUnique(sb_file.ref()); + LLDB_RECORD_METHOD(bool, SBFileSpecList, AppendIfUnique, + (const lldb::SBFileSpec &), sb_file); + + return m_opaque_up->AppendIfUnique(sb_file.ref()); } -void SBFileSpecList::Clear() { m_opaque_ap->Clear(); } +void SBFileSpecList::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBFileSpecList, Clear); + + m_opaque_up->Clear(); +} uint32_t SBFileSpecList::FindFileIndex(uint32_t idx, const SBFileSpec &sb_file, bool full) { - return m_opaque_ap->FindFileIndex(idx, sb_file.ref(), full); + LLDB_RECORD_METHOD(uint32_t, SBFileSpecList, FindFileIndex, + (uint32_t, const lldb::SBFileSpec &, bool), idx, sb_file, + full); + + return m_opaque_up->FindFileIndex(idx, sb_file.ref(), full); } const SBFileSpec SBFileSpecList::GetFileSpecAtIndex(uint32_t idx) const { + LLDB_RECORD_METHOD_CONST(const lldb::SBFileSpec, SBFileSpecList, + GetFileSpecAtIndex, (uint32_t), idx); + SBFileSpec new_spec; - new_spec.SetFileSpec(m_opaque_ap->GetFileSpecAtIndex(idx)); - return new_spec; + new_spec.SetFileSpec(m_opaque_up->GetFileSpecAtIndex(idx)); + return LLDB_RECORD_RESULT(new_spec); } const lldb_private::FileSpecList *SBFileSpecList::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const lldb_private::FileSpecList *SBFileSpecList::get() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const lldb_private::FileSpecList &SBFileSpecList::operator*() const { - return *m_opaque_ap; + return *m_opaque_up; } const lldb_private::FileSpecList &SBFileSpecList::ref() const { - return *m_opaque_ap; + return *m_opaque_up; } bool SBFileSpecList::GetDescription(SBStream &description) const { + LLDB_RECORD_METHOD_CONST(bool, SBFileSpecList, GetDescription, + (lldb::SBStream &), description); + Stream &strm = description.ref(); - if (m_opaque_ap) { - uint32_t num_files = m_opaque_ap->GetSize(); + 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_ap->GetFileSpecAtIndex(i).GetPath(path, sizeof(path))) + if (m_opaque_up->GetFileSpecAtIndex(i).GetPath(path, sizeof(path))) strm.Printf("\n %s", path); } } else @@ -101,3 +123,30 @@ return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBFileSpecList>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBFileSpecList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBFileSpecList, (const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD( + const lldb::SBFileSpecList &, + SBFileSpecList, operator=,(const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBFileSpecList, GetSize, ()); + LLDB_REGISTER_METHOD(void, SBFileSpecList, Append, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(bool, SBFileSpecList, AppendIfUnique, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(void, SBFileSpecList, Clear, ()); + LLDB_REGISTER_METHOD(uint32_t, SBFileSpecList, FindFileIndex, + (uint32_t, const lldb::SBFileSpec &, bool)); + LLDB_REGISTER_METHOD_CONST(const lldb::SBFileSpec, SBFileSpecList, + GetFileSpecAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD_CONST(bool, SBFileSpecList, GetDescription, + (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBFrame.cpp b/src/llvm-project/lldb/source/API/SBFrame.cpp index 44dcfd8..9268f0f 100644 --- a/src/llvm-project/lldb/source/API/SBFrame.cpp +++ b/src/llvm-project/lldb/source/API/SBFrame.cpp
@@ -1,9 +1,8 @@ //===-- SBFrame.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,11 +14,13 @@ #include "lldb/lldb-types.h" -#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" +#include "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/Core/Address.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/ValueObjectRegister.h" #include "lldb/Core/ValueObjectVariable.h" +#include "lldb/Expression/ExpressionVariable.h" #include "lldb/Expression/UserExpression.h" #include "lldb/Host/Host.h" #include "lldb/Symbol/Block.h" @@ -37,7 +38,6 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" #include "lldb/API/SBAddress.h" @@ -54,30 +54,31 @@ using namespace lldb; using namespace lldb_private; -SBFrame::SBFrame() : m_opaque_sp(new ExecutionContextRef()) {} +SBFrame::SBFrame() : m_opaque_sp(new ExecutionContextRef()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBFrame); +} SBFrame::SBFrame(const StackFrameSP &lldb_object_sp) : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) { - SBStream sstr; - GetDescription(sstr); - log->Printf("SBFrame::SBFrame (sp=%p) => SBFrame(%p): %s", - static_cast<void *>(lldb_object_sp.get()), - static_cast<void *>(lldb_object_sp.get()), sstr.GetData()); - } + LLDB_RECORD_CONSTRUCTOR(SBFrame, (const lldb::StackFrameSP &), + lldb_object_sp); } -SBFrame::SBFrame(const SBFrame &rhs) - : m_opaque_sp(new ExecutionContextRef(*rhs.m_opaque_sp)) {} +SBFrame::SBFrame(const SBFrame &rhs) : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR(SBFrame, (const lldb::SBFrame &), rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); +} SBFrame::~SBFrame() = default; const SBFrame &SBFrame::operator=(const SBFrame &rhs) { + LLDB_RECORD_METHOD(const lldb::SBFrame &, + SBFrame, operator=,(const lldb::SBFrame &), rhs); + if (this != &rhs) - *m_opaque_sp = *rhs.m_opaque_sp; - return *this; + m_opaque_sp = clone(rhs.m_opaque_sp); + return LLDB_RECORD_RESULT(*this); } StackFrameSP SBFrame::GetFrameSP() const { @@ -89,6 +90,12 @@ } bool SBFrame::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, IsValid); + return this->operator bool(); +} +SBFrame::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, operator bool); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -105,7 +112,9 @@ } SBSymbolContext SBFrame::GetSymbolContext(uint32_t resolve_scope) const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(lldb::SBSymbolContext, SBFrame, GetSymbolContext, + (uint32_t), resolve_scope); + SBSymbolContext sb_sym_ctx; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -117,31 +126,17 @@ Process::StopLocker stop_locker; if (stop_locker.TryLock(&process->GetRunLock())) { frame = exe_ctx.GetFramePtr(); - if (frame) { + if (frame) sb_sym_ctx.SetSymbolContext(&frame->GetSymbolContext(scope)); - } else { - if (log) - log->Printf("SBFrame::GetVariables () => error: could not " - "reconstruct frame object for this SBFrame."); - } - } else { - if (log) - log->Printf( - "SBFrame::GetSymbolContext () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetSymbolContext (resolve_scope=0x%8.8x) => " - "SBSymbolContext(%p)", - static_cast<void *>(frame), resolve_scope, - static_cast<void *>(sb_sym_ctx.get())); - - return sb_sym_ctx; + return LLDB_RECORD_RESULT(sb_sym_ctx); } SBModule SBFrame::GetModule() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBModule, SBFrame, GetModule); + SBModule sb_module; ModuleSP module_sp; std::unique_lock<std::recursive_mutex> lock; @@ -157,27 +152,17 @@ if (frame) { module_sp = frame->GetSymbolContext(eSymbolContextModule).module_sp; sb_module.SetSP(module_sp); - } else { - if (log) - log->Printf("SBFrame::GetModule () => error: could not reconstruct " - "frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetModule () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetModule () => SBModule(%p)", - static_cast<void *>(frame), - static_cast<void *>(module_sp.get())); - - return sb_module; + return LLDB_RECORD_RESULT(sb_module); } SBCompileUnit SBFrame::GetCompileUnit() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBCompileUnit, SBFrame, + GetCompileUnit); + SBCompileUnit sb_comp_unit; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -192,26 +177,16 @@ if (frame) { sb_comp_unit.reset( frame->GetSymbolContext(eSymbolContextCompUnit).comp_unit); - } else { - if (log) - log->Printf("SBFrame::GetCompileUnit () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetCompileUnit () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetCompileUnit () => SBCompileUnit(%p)", - static_cast<void *>(frame), - static_cast<void *>(sb_comp_unit.get())); - return sb_comp_unit; + return LLDB_RECORD_RESULT(sb_comp_unit); } SBFunction SBFrame::GetFunction() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFunction, SBFrame, GetFunction); + SBFunction sb_function; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -226,26 +201,16 @@ if (frame) { sb_function.reset( frame->GetSymbolContext(eSymbolContextFunction).function); - } else { - if (log) - log->Printf("SBFrame::GetFunction () => error: could not reconstruct " - "frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetFunction () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetFunction () => SBFunction(%p)", - static_cast<void *>(frame), - static_cast<void *>(sb_function.get())); - return sb_function; + return LLDB_RECORD_RESULT(sb_function); } SBSymbol SBFrame::GetSymbol() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBSymbol, SBFrame, GetSymbol); + SBSymbol sb_symbol; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -259,25 +224,16 @@ frame = exe_ctx.GetFramePtr(); if (frame) { sb_symbol.reset(frame->GetSymbolContext(eSymbolContextSymbol).symbol); - } else { - if (log) - log->Printf("SBFrame::GetSymbol () => error: could not reconstruct " - "frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetSymbol () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetSymbol () => SBSymbol(%p)", - static_cast<void *>(frame), - static_cast<void *>(sb_symbol.get())); - return sb_symbol; + + return LLDB_RECORD_RESULT(sb_symbol); } SBBlock SBFrame::GetBlock() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBlock, SBFrame, GetBlock); + SBBlock sb_block; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -289,60 +245,37 @@ Process::StopLocker stop_locker; if (stop_locker.TryLock(&process->GetRunLock())) { frame = exe_ctx.GetFramePtr(); - if (frame) { + if (frame) sb_block.SetPtr(frame->GetSymbolContext(eSymbolContextBlock).block); - } else { - if (log) - log->Printf("SBFrame::GetBlock () => error: could not reconstruct " - "frame object for this SBFrame."); - } - } else { - if (log) - log->Printf("SBFrame(%p)::GetBlock () => error: process is running", - static_cast<void *>(frame)); } } - if (log) - log->Printf("SBFrame(%p)::GetBlock () => SBBlock(%p)", - static_cast<void *>(frame), - static_cast<void *>(sb_block.GetPtr())); - return sb_block; + return LLDB_RECORD_RESULT(sb_block); } SBBlock SBFrame::GetFrameBlock() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBlock, SBFrame, GetFrameBlock); + 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(); - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); Process *process = exe_ctx.GetProcessPtr(); if (target && process) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process->GetRunLock())) { frame = exe_ctx.GetFramePtr(); - if (frame) { + if (frame) sb_block.SetPtr(frame->GetFrameBlock()); - } else { - if (log) - log->Printf("SBFrame::GetFrameBlock () => error: could not " - "reconstruct frame object for this SBFrame."); - } - } else { - if (log) - log->Printf("SBFrame::GetFrameBlock () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetFrameBlock () => SBBlock(%p)", - static_cast<void *>(frame), - static_cast<void *>(sb_block.GetPtr())); - return sb_block; + return LLDB_RECORD_RESULT(sb_block); } SBLineEntry SBFrame::GetLineEntry() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBLineEntry, SBFrame, GetLineEntry); + SBLineEntry sb_line_entry; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -357,24 +290,15 @@ if (frame) { sb_line_entry.SetLineEntry( frame->GetSymbolContext(eSymbolContextLineEntry).line_entry); - } else { - if (log) - log->Printf("SBFrame::GetLineEntry () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetLineEntry () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetLineEntry () => SBLineEntry(%p)", - static_cast<void *>(frame), - static_cast<void *>(sb_line_entry.get())); - return sb_line_entry; + return LLDB_RECORD_RESULT(sb_line_entry); } uint32_t SBFrame::GetFrameID() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBFrame, GetFrameID); + uint32_t frame_idx = UINT32_MAX; std::unique_lock<std::recursive_mutex> lock; @@ -384,14 +308,12 @@ if (frame) frame_idx = frame->GetFrameIndex(); - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBFrame(%p)::GetFrameID () => %u", static_cast<void *>(frame), - frame_idx); return frame_idx; } lldb::addr_t SBFrame::GetCFA() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetCFA); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -402,7 +324,8 @@ } addr_t SBFrame::GetPC() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetPC); + addr_t addr = LLDB_INVALID_ADDRESS; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -417,26 +340,16 @@ if (frame) { addr = frame->GetFrameCodeAddress().GetOpcodeLoadAddress( target, AddressClass::eCode); - } else { - if (log) - log->Printf("SBFrame::GetPC () => error: could not reconstruct frame " - "object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetPC () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetPC () => 0x%" PRIx64, - static_cast<void *>(frame), addr); - return addr; } bool SBFrame::SetPC(addr_t new_pc) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBFrame, SetPC, (lldb::addr_t), new_pc); + bool ret_val = false; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -450,26 +363,16 @@ frame = exe_ctx.GetFramePtr(); if (frame) { ret_val = frame->GetRegisterContext()->SetPC(new_pc); - } else { - if (log) - log->Printf("SBFrame::SetPC () => error: could not reconstruct frame " - "object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::SetPC () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::SetPC (new_pc=0x%" PRIx64 ") => %i", - static_cast<void *>(frame), new_pc, ret_val); - return ret_val; } addr_t SBFrame::GetSP() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetSP); + addr_t addr = LLDB_INVALID_ADDRESS; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -483,25 +386,16 @@ frame = exe_ctx.GetFramePtr(); if (frame) { addr = frame->GetRegisterContext()->GetSP(); - } else { - if (log) - log->Printf("SBFrame::GetSP () => error: could not reconstruct frame " - "object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetSP () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetSP () => 0x%" PRIx64, - static_cast<void *>(frame), addr); return addr; } addr_t SBFrame::GetFP() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetFP); + addr_t addr = LLDB_INVALID_ADDRESS; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -513,27 +407,17 @@ Process::StopLocker stop_locker; if (stop_locker.TryLock(&process->GetRunLock())) { frame = exe_ctx.GetFramePtr(); - if (frame) { + if (frame) addr = frame->GetRegisterContext()->GetFP(); - } else { - if (log) - log->Printf("SBFrame::GetFP () => error: could not reconstruct frame " - "object for this SBFrame."); - } - } else { - if (log) - log->Printf("SBFrame::GetFP () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetFP () => 0x%" PRIx64, - static_cast<void *>(frame), addr); return addr; } SBAddress SBFrame::GetPCAddress() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBFrame, GetPCAddress); + SBAddress sb_addr; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -545,27 +429,23 @@ Process::StopLocker stop_locker; if (stop_locker.TryLock(&process->GetRunLock())) { frame = exe_ctx.GetFramePtr(); - if (frame) { + if (frame) sb_addr.SetAddress(&frame->GetFrameCodeAddress()); - } else { - if (log) - log->Printf("SBFrame::GetPCAddress () => error: could not " - "reconstruct frame object for this SBFrame."); - } - } else { - if (log) - log->Printf("SBFrame::GetPCAddress () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetPCAddress () => SBAddress(%p)", - static_cast<void *>(frame), static_cast<void *>(sb_addr.get())); - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); } -void SBFrame::Clear() { m_opaque_sp->Clear(); } +void SBFrame::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBFrame, Clear); + + m_opaque_sp->Clear(); +} lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path) { + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath, + (const char *), var_path); + SBValue sb_value; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -577,18 +457,18 @@ frame->CalculateTarget()->GetPreferDynamicValue(); sb_value = GetValueForVariablePath(var_path, use_dynamic); } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path, DynamicValueType use_dynamic) { + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath, + (const char *, lldb::DynamicValueType), var_path, + use_dynamic); + SBValue sb_value; - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (var_path == nullptr || var_path[0] == '\0') { - if (log) - log->Printf( - "SBFrame::GetValueForVariablePath called with empty variable path."); - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } std::unique_lock<std::recursive_mutex> lock; @@ -610,21 +490,16 @@ StackFrame::eExpressionPathOptionsAllowDirectIVarAccess, var_sp, error)); sb_value.SetSP(value_sp, use_dynamic); - } else { - if (log) - log->Printf("SBFrame::GetValueForVariablePath () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf( - "SBFrame::GetValueForVariablePath () => error: process is running"); } } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } SBValue SBFrame::FindVariable(const char *name) { + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindVariable, (const char *), + name); + SBValue value; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -636,19 +511,19 @@ frame->CalculateTarget()->GetPreferDynamicValue(); value = FindVariable(name, use_dynamic); } - return value; + return LLDB_RECORD_RESULT(value); } SBValue SBFrame::FindVariable(const char *name, lldb::DynamicValueType use_dynamic) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindVariable, + (const char *, lldb::DynamicValueType), name, use_dynamic); + VariableSP var_sp; SBValue sb_value; if (name == nullptr || name[0] == '\0') { - if (log) - log->Printf("SBFrame::FindVariable called with empty name"); - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } ValueObjectSP value_sp; @@ -667,26 +542,17 @@ if (value_sp) sb_value.SetSP(value_sp, use_dynamic); - } else { - if (log) - log->Printf("SBFrame::FindVariable () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::FindVariable () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::FindVariable (name=\"%s\") => SBValue(%p)", - static_cast<void *>(frame), name, - static_cast<void *>(value_sp.get())); - - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } SBValue SBFrame::FindValue(const char *name, ValueType value_type) { + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindValue, + (const char *, lldb::ValueType), name, value_type); + SBValue value; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -698,18 +564,19 @@ frame->CalculateTarget()->GetPreferDynamicValue(); value = FindValue(name, value_type, use_dynamic); } - return value; + return LLDB_RECORD_RESULT(value); } SBValue SBFrame::FindValue(const char *name, ValueType value_type, lldb::DynamicValueType use_dynamic) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindValue, + (const char *, lldb::ValueType, lldb::DynamicValueType), + name, value_type, use_dynamic); + SBValue sb_value; if (name == nullptr || name[0] == '\0') { - if (log) - log->Printf("SBFrame::FindValue called with empty name."); - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } ValueObjectSP value_sp; @@ -816,38 +683,38 @@ default: break; } - } else { - if (log) - log->Printf("SBFrame::FindValue () => error: could not reconstruct " - "frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::FindValue () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::FindVariableInScope (name=\"%s\", value_type=%i) " - "=> SBValue(%p)", - static_cast<void *>(frame), name, value_type, - static_cast<void *>(value_sp.get())); - - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } bool SBFrame::IsEqual(const SBFrame &that) const { + LLDB_RECORD_METHOD_CONST(bool, SBFrame, IsEqual, (const lldb::SBFrame &), + 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 { return IsEqual(rhs); } +bool SBFrame::operator==(const SBFrame &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBFrame, operator==,(const lldb::SBFrame &), + rhs); -bool SBFrame::operator!=(const SBFrame &rhs) const { return !IsEqual(rhs); } + return IsEqual(rhs); +} + +bool SBFrame::operator!=(const SBFrame &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBFrame, operator!=,(const lldb::SBFrame &), + rhs); + + return !IsEqual(rhs); +} SBThread SBFrame::GetThread() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBThread, SBFrame, GetThread); std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -855,19 +722,12 @@ ThreadSP thread_sp(exe_ctx.GetThreadSP()); SBThread sb_thread(thread_sp); - if (log) { - SBStream sstr; - sb_thread.GetDescription(sstr); - log->Printf("SBFrame(%p)::GetThread () => SBThread(%p): %s", - static_cast<void *>(exe_ctx.GetFramePtr()), - static_cast<void *>(thread_sp.get()), sstr.GetData()); - } - - return sb_thread; + return LLDB_RECORD_RESULT(sb_thread); } const char *SBFrame::Disassemble() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFrame, Disassemble); + const char *disassembly = nullptr; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -881,26 +741,19 @@ frame = exe_ctx.GetFramePtr(); if (frame) { disassembly = frame->Disassemble(); - } else { - if (log) - log->Printf("SBFrame::Disassemble () => error: could not reconstruct " - "frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::Disassemble () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::Disassemble () => %s", static_cast<void *>(frame), - disassembly); - return disassembly; } SBValueList SBFrame::GetVariables(bool arguments, bool locals, bool statics, bool in_scope_only) { + LLDB_RECORD_METHOD(lldb::SBValueList, SBFrame, GetVariables, + (bool, bool, bool, bool), arguments, locals, statics, + in_scope_only); + SBValueList value_list; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -923,12 +776,16 @@ value_list = GetVariables(options); } - return value_list; + return LLDB_RECORD_RESULT(value_list); } lldb::SBValueList SBFrame::GetVariables(bool arguments, bool locals, bool statics, bool in_scope_only, lldb::DynamicValueType use_dynamic) { + LLDB_RECORD_METHOD(lldb::SBValueList, SBFrame, GetVariables, + (bool, bool, bool, bool, lldb::DynamicValueType), + arguments, locals, statics, in_scope_only, use_dynamic); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -942,11 +799,12 @@ options.SetInScopeOnly(in_scope_only); options.SetIncludeRuntimeSupportValues(include_runtime_support_values); options.SetUseDynamic(use_dynamic); - return GetVariables(options); + return LLDB_RECORD_RESULT(GetVariables(options)); } SBValueList SBFrame::GetVariables(const lldb::SBVariablesOptions &options) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBValueList, SBFrame, GetVariables, + (const lldb::SBVariablesOptions &), options); SBValueList value_list; std::unique_lock<std::recursive_mutex> lock; @@ -965,12 +823,6 @@ options.GetIncludeRuntimeSupportValues(); const lldb::DynamicValueType use_dynamic = options.GetUseDynamic(); - if (log) - log->Printf( - "SBFrame::GetVariables (arguments=%i, recognized_arguments=%i, " - "locals=%i, statics=%i, in_scope_only=%i runtime=%i dynamic=%i)", - arguments, recognized_arguments, locals, statics, in_scope_only, - include_runtime_support_values, use_dynamic); std::set<VariableSP> variable_set; Process *process = exe_ctx.GetProcessPtr(); @@ -1046,27 +898,15 @@ } } } - } else { - if (log) - log->Printf("SBFrame::GetVariables () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetVariables () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetVariables (...) => SBValueList(%p)", - static_cast<void *>(frame), - static_cast<void *>(value_list.opaque_ptr())); - - return value_list; + return LLDB_RECORD_RESULT(value_list); } SBValueList SBFrame::GetRegisters() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValueList, SBFrame, GetRegisters); SBValueList value_list; std::unique_lock<std::recursive_mutex> lock; @@ -1088,27 +928,16 @@ ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx)); } } - } else { - if (log) - log->Printf("SBFrame::GetRegisters () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetRegisters () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::GetRegisters () => SBValueList(%p)", - static_cast<void *>(frame), - static_cast<void *>(value_list.opaque_ptr())); - - return value_list; + return LLDB_RECORD_RESULT(value_list); } SBValue SBFrame::FindRegister(const char *name) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindRegister, (const char *), + name); SBValue result; ValueObjectSP value_sp; @@ -1139,27 +968,17 @@ } } } - } else { - if (log) - log->Printf("SBFrame::FindRegister () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::FindRegister () => error: process is running"); } } - if (log) - log->Printf("SBFrame(%p)::FindRegister () => SBValue(%p)", - static_cast<void *>(frame), - static_cast<void *>(value_sp.get())); - - return result; + return LLDB_RECORD_RESULT(result); } bool SBFrame::GetDescription(SBStream &description) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBFrame, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); std::unique_lock<std::recursive_mutex> lock; @@ -1174,14 +993,7 @@ frame = exe_ctx.GetFramePtr(); if (frame) { frame->DumpUsingSettingsFormat(&strm); - } else { - if (log) - log->Printf("SBFrame::GetDescription () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetDescription () => error: process is running"); } } else @@ -1191,6 +1003,9 @@ } SBValue SBFrame::EvaluateExpression(const char *expr) { + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, (const char *), + expr); + SBValue result; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1208,14 +1023,18 @@ options.SetLanguage(target->GetLanguage()); else options.SetLanguage(frame->GetLanguage()); - return EvaluateExpression(expr, options); + return LLDB_RECORD_RESULT(EvaluateExpression(expr, options)); } - return result; + return LLDB_RECORD_RESULT(result); } SBValue SBFrame::EvaluateExpression(const char *expr, lldb::DynamicValueType fetch_dynamic_value) { + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, + (const char *, lldb::DynamicValueType), expr, + fetch_dynamic_value); + SBExpressionOptions options; options.SetFetchDynamicValue(fetch_dynamic_value); options.SetUnwindOnError(true); @@ -1229,12 +1048,16 @@ options.SetLanguage(target->GetLanguage()); else if (frame) options.SetLanguage(frame->GetLanguage()); - return EvaluateExpression(expr, options); + return LLDB_RECORD_RESULT(EvaluateExpression(expr, options)); } SBValue SBFrame::EvaluateExpression(const char *expr, lldb::DynamicValueType fetch_dynamic_value, bool unwind_on_error) { + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, + (const char *, lldb::DynamicValueType, bool), expr, + fetch_dynamic_value, unwind_on_error); + SBExpressionOptions options; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1248,25 +1071,21 @@ options.SetLanguage(target->GetLanguage()); else if (frame) options.SetLanguage(frame->GetLanguage()); - return EvaluateExpression(expr, options); + return LLDB_RECORD_RESULT(EvaluateExpression(expr, options)); } lldb::SBValue SBFrame::EvaluateExpression(const char *expr, const SBExpressionOptions &options) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &), expr, + options); -#ifndef LLDB_DISABLE_PYTHON Log *expr_log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); -#endif - ExpressionResults exe_results = eExpressionSetupError; SBValue expr_result; if (expr == nullptr || expr[0] == '\0') { - if (log) - log->Printf( - "SBFrame::EvaluateExpression called with an empty expression"); - return expr_result; + return LLDB_RECORD_RESULT(expr_result); } ValueObjectSP expr_value_sp; @@ -1274,8 +1093,6 @@ std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBFrame()::EvaluateExpression (expr=\"%s\")...", expr); StackFrame *frame = nullptr; Target *target = exe_ctx.GetTargetPtr(); @@ -1297,43 +1114,29 @@ frame_description.GetData()); } - exe_results = target->EvaluateExpression(expr, frame, expr_value_sp, - options.ref()); + target->EvaluateExpression(expr, frame, expr_value_sp, options.ref()); expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); - } else { - if (log) - log->Printf("SBFrame::EvaluateExpression () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf( - "SBFrame::EvaluateExpression () => error: process is running"); } } -#ifndef LLDB_DISABLE_PYTHON if (expr_log) expr_log->Printf("** [SBFrame::EvaluateExpression] Expression result is " "%s, summary %s **", expr_result.GetValue(), expr_result.GetSummary()); - if (log) - log->Printf("SBFrame(%p)::EvaluateExpression (expr=\"%s\") => SBValue(%p) " - "(execution result=%d)", - static_cast<void *>(frame), expr, - static_cast<void *>(expr_value_sp.get()), exe_results); -#endif - - return expr_result; + return LLDB_RECORD_RESULT(expr_result); } bool SBFrame::IsInlined() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBFrame, IsInlined); + return static_cast<const SBFrame *>(this)->IsInlined(); } bool SBFrame::IsInlined() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, IsInlined); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1349,24 +1152,21 @@ Block *block = frame->GetSymbolContext(eSymbolContextBlock).block; if (block) return block->GetContainingInlinedBlock() != nullptr; - } else { - if (log) - log->Printf("SBFrame::IsInlined () => error: could not reconstruct " - "frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::IsInlined () => error: process is running"); } } return false; } bool SBFrame::IsArtificial() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBFrame, IsArtificial); + return static_cast<const SBFrame *>(this)->IsArtificial(); } bool SBFrame::IsArtificial() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, IsArtificial); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1378,13 +1178,17 @@ } const char *SBFrame::GetFunctionName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBFrame, GetFunctionName); + return static_cast<const SBFrame *>(this)->GetFunctionName(); } lldb::LanguageType SBFrame::GuessLanguage() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::LanguageType, SBFrame, GuessLanguage); + 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(); @@ -1401,7 +1205,8 @@ } const char *SBFrame::GetFunctionName() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFrame, GetFunctionName); + const char *name = nullptr; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1436,21 +1241,15 @@ if (sc.symbol) name = sc.symbol->GetName().GetCString(); } - } else { - if (log) - log->Printf("SBFrame::GetFunctionName () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf("SBFrame::GetFunctionName() => error: process is running"); } } return name; } const char *SBFrame::GetDisplayFunctionName() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBFrame, GetDisplayFunctionName); + const char *name = nullptr; std::unique_lock<std::recursive_mutex> lock; @@ -1486,16 +1285,87 @@ if (sc.symbol) name = sc.symbol->GetDisplayName().GetCString(); } - } else { - if (log) - log->Printf("SBFrame::GetDisplayFunctionName () => error: could not " - "reconstruct frame object for this SBFrame."); } - } else { - if (log) - log->Printf( - "SBFrame::GetDisplayFunctionName() => error: process is running"); } } return name; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBFrame>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBFrame, ()); + LLDB_REGISTER_CONSTRUCTOR(SBFrame, (const lldb::StackFrameSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBFrame, (const lldb::SBFrame &)); + LLDB_REGISTER_METHOD(const lldb::SBFrame &, + SBFrame, operator=,(const lldb::SBFrame &)); + LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBFrame, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBSymbolContext, SBFrame, GetSymbolContext, + (uint32_t)); + LLDB_REGISTER_METHOD_CONST(lldb::SBModule, SBFrame, GetModule, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBCompileUnit, SBFrame, GetCompileUnit, + ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBFunction, SBFrame, GetFunction, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBSymbol, SBFrame, GetSymbol, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBBlock, SBFrame, GetBlock, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBBlock, SBFrame, GetFrameBlock, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBLineEntry, SBFrame, GetLineEntry, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBFrame, GetFrameID, ()); + LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetCFA, ()); + LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetPC, ()); + LLDB_REGISTER_METHOD(bool, SBFrame, SetPC, (lldb::addr_t)); + LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetSP, ()); + LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetFP, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBFrame, GetPCAddress, ()); + LLDB_REGISTER_METHOD(void, SBFrame, Clear, ()); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath, + (const char *, lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindVariable, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindVariable, + (const char *, lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindValue, + (const char *, lldb::ValueType)); + LLDB_REGISTER_METHOD( + lldb::SBValue, SBFrame, FindValue, + (const char *, lldb::ValueType, lldb::DynamicValueType)); + LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsEqual, (const lldb::SBFrame &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBFrame, operator==,(const lldb::SBFrame &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBFrame, operator!=,(const lldb::SBFrame &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBThread, SBFrame, GetThread, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBFrame, Disassemble, ()); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetVariables, + (bool, bool, bool, bool)); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetVariables, + (bool, bool, bool, bool, lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetVariables, + (const lldb::SBVariablesOptions &)); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetRegisters, ()); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindRegister, (const char *)); + LLDB_REGISTER_METHOD(bool, SBFrame, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, + (const char *, lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, + (const char *, lldb::DynamicValueType, bool)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &)); + LLDB_REGISTER_METHOD(bool, SBFrame, IsInlined, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsInlined, ()); + LLDB_REGISTER_METHOD(bool, SBFrame, IsArtificial, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsArtificial, ()); + LLDB_REGISTER_METHOD(const char *, SBFrame, GetFunctionName, ()); + LLDB_REGISTER_METHOD_CONST(lldb::LanguageType, SBFrame, GuessLanguage, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBFrame, GetFunctionName, ()); + LLDB_REGISTER_METHOD(const char *, SBFrame, GetDisplayFunctionName, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBFunction.cpp b/src/llvm-project/lldb/source/API/SBFunction.cpp index 6a24f64..1770bed 100644 --- a/src/llvm-project/lldb/source/API/SBFunction.cpp +++ b/src/llvm-project/lldb/source/API/SBFunction.cpp
@@ -1,13 +1,13 @@ //===-- SBFunction.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBProcess.h" #include "lldb/API/SBStream.h" #include "lldb/Core/Disassembler.h" @@ -18,89 +18,90 @@ #include "lldb/Symbol/VariableList.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Log.h" using namespace lldb; using namespace lldb_private; -SBFunction::SBFunction() : m_opaque_ptr(NULL) {} +SBFunction::SBFunction() : m_opaque_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBFunction); +} 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) {} - -const SBFunction &SBFunction::operator=(const SBFunction &rhs) { - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; + : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBFunction, (const lldb::SBFunction &), rhs); } -SBFunction::~SBFunction() { m_opaque_ptr = NULL; } +const SBFunction &SBFunction::operator=(const SBFunction &rhs) { + LLDB_RECORD_METHOD(const lldb::SBFunction &, + SBFunction, operator=,(const lldb::SBFunction &), rhs); -bool SBFunction::IsValid() const { return m_opaque_ptr != NULL; } + m_opaque_ptr = rhs.m_opaque_ptr; + return LLDB_RECORD_RESULT(*this); +} + +SBFunction::~SBFunction() { m_opaque_ptr = nullptr; } + +bool SBFunction::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFunction, IsValid); + return this->operator bool(); +} +SBFunction::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFunction, operator bool); + + return m_opaque_ptr != nullptr; +} const char *SBFunction::GetName() const { - const char *cstr = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFunction, GetName); + + const char *cstr = nullptr; if (m_opaque_ptr) cstr = m_opaque_ptr->GetName().AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (cstr) - log->Printf("SBFunction(%p)::GetName () => \"%s\"", - static_cast<void *>(m_opaque_ptr), cstr); - else - log->Printf("SBFunction(%p)::GetName () => NULL", - static_cast<void *>(m_opaque_ptr)); - } return cstr; } const char *SBFunction::GetDisplayName() const { - const char *cstr = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFunction, GetDisplayName); + + const char *cstr = nullptr; if (m_opaque_ptr) cstr = m_opaque_ptr->GetMangled() .GetDisplayDemangledName(m_opaque_ptr->GetLanguage()) .AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (cstr) - log->Printf("SBFunction(%p)::GetDisplayName () => \"%s\"", - static_cast<void *>(m_opaque_ptr), cstr); - else - log->Printf("SBFunction(%p)::GetDisplayName () => NULL", - static_cast<void *>(m_opaque_ptr)); - } return cstr; } const char *SBFunction::GetMangledName() const { - const char *cstr = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFunction, GetMangledName); + + const char *cstr = nullptr; if (m_opaque_ptr) cstr = m_opaque_ptr->GetMangled().GetMangledName().AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (cstr) - log->Printf("SBFunction(%p)::GetMangledName () => \"%s\"", - static_cast<void *>(m_opaque_ptr), cstr); - else - log->Printf("SBFunction(%p)::GetMangledName () => NULL", - static_cast<void *>(m_opaque_ptr)); - } return cstr; } bool SBFunction::operator==(const SBFunction &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBFunction, operator==,(const lldb::SBFunction &), rhs); + return m_opaque_ptr == rhs.m_opaque_ptr; } bool SBFunction::operator!=(const SBFunction &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBFunction, operator!=,(const lldb::SBFunction &), rhs); + return m_opaque_ptr != rhs.m_opaque_ptr; } bool SBFunction::GetDescription(SBStream &s) { + LLDB_RECORD_METHOD(bool, SBFunction, GetDescription, (lldb::SBStream &), s); + if (m_opaque_ptr) { s.Printf("SBFunction: id = 0x%8.8" PRIx64 ", name = %s", m_opaque_ptr->GetID(), m_opaque_ptr->GetName().AsCString()); @@ -114,11 +115,17 @@ } SBInstructionList SBFunction::GetInstructions(SBTarget target) { - return GetInstructions(target, NULL); + LLDB_RECORD_METHOD(lldb::SBInstructionList, SBFunction, GetInstructions, + (lldb::SBTarget), target); + + return LLDB_RECORD_RESULT(GetInstructions(target, nullptr)); } SBInstructionList SBFunction::GetInstructions(SBTarget target, const char *flavor) { + LLDB_RECORD_METHOD(lldb::SBInstructionList, SBFunction, GetInstructions, + (lldb::SBTarget, const char *), target, flavor); + SBInstructionList sb_instructions; if (m_opaque_ptr) { ExecutionContext exe_ctx; @@ -134,11 +141,11 @@ if (module_sp) { const bool prefer_file_cache = false; sb_instructions.SetDisassembler(Disassembler::DisassembleRange( - module_sp->GetArchitecture(), NULL, flavor, exe_ctx, + module_sp->GetArchitecture(), nullptr, flavor, exe_ctx, m_opaque_ptr->GetAddressRange(), prefer_file_cache)); } } - return sb_instructions; + return LLDB_RECORD_RESULT(sb_instructions); } lldb_private::Function *SBFunction::get() { return m_opaque_ptr; } @@ -148,13 +155,17 @@ } SBAddress SBFunction::GetStartAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBAddress, SBFunction, GetStartAddress); + SBAddress addr; if (m_opaque_ptr) addr.SetAddress(&m_opaque_ptr->GetAddressRange().GetBaseAddress()); - return addr; + return LLDB_RECORD_RESULT(addr); } SBAddress SBFunction::GetEndAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBAddress, SBFunction, GetEndAddress); + SBAddress addr; if (m_opaque_ptr) { addr_t byte_size = m_opaque_ptr->GetAddressRange().GetByteSize(); @@ -163,10 +174,13 @@ addr->Slide(byte_size); } } - return addr; + return LLDB_RECORD_RESULT(addr); } const char *SBFunction::GetArgumentName(uint32_t arg_idx) { + LLDB_RECORD_METHOD(const char *, SBFunction, GetArgumentName, (uint32_t), + arg_idx); + if (m_opaque_ptr) { Block &block = m_opaque_ptr->GetBlock(true); VariableListSP variable_list_sp = block.GetBlockVariableList(true); @@ -183,29 +197,37 @@ } uint32_t SBFunction::GetPrologueByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBFunction, GetPrologueByteSize); + if (m_opaque_ptr) return m_opaque_ptr->GetPrologueByteSize(); return 0; } SBType SBFunction::GetType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBFunction, GetType); + 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; + return LLDB_RECORD_RESULT(sb_type); } SBBlock SBFunction::GetBlock() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBFunction, GetBlock); + SBBlock sb_block; if (m_opaque_ptr) sb_block.SetPtr(&m_opaque_ptr->GetBlock(true)); - return sb_block; + return LLDB_RECORD_RESULT(sb_block); } lldb::LanguageType SBFunction::GetLanguage() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::LanguageType, SBFunction, GetLanguage); + if (m_opaque_ptr) { if (m_opaque_ptr->GetCompileUnit()) return m_opaque_ptr->GetCompileUnit()->GetLanguage(); @@ -214,9 +236,47 @@ } bool SBFunction::GetIsOptimized() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBFunction, GetIsOptimized); + if (m_opaque_ptr) { if (m_opaque_ptr->GetCompileUnit()) return m_opaque_ptr->GetCompileUnit()->GetIsOptimized(); } return false; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBFunction>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBFunction, ()); + LLDB_REGISTER_CONSTRUCTOR(SBFunction, (const lldb::SBFunction &)); + LLDB_REGISTER_METHOD(const lldb::SBFunction &, + SBFunction, operator=,(const lldb::SBFunction &)); + LLDB_REGISTER_METHOD_CONST(bool, SBFunction, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBFunction, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBFunction, GetName, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBFunction, GetDisplayName, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBFunction, GetMangledName, ()); + LLDB_REGISTER_METHOD_CONST( + bool, SBFunction, operator==,(const lldb::SBFunction &)); + LLDB_REGISTER_METHOD_CONST( + bool, SBFunction, operator!=,(const lldb::SBFunction &)); + LLDB_REGISTER_METHOD(bool, SBFunction, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(lldb::SBInstructionList, SBFunction, GetInstructions, + (lldb::SBTarget)); + LLDB_REGISTER_METHOD(lldb::SBInstructionList, SBFunction, GetInstructions, + (lldb::SBTarget, const char *)); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBFunction, GetStartAddress, ()); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBFunction, GetEndAddress, ()); + LLDB_REGISTER_METHOD(const char *, SBFunction, GetArgumentName, (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBFunction, GetPrologueByteSize, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBFunction, GetType, ()); + LLDB_REGISTER_METHOD(lldb::SBBlock, SBFunction, GetBlock, ()); + LLDB_REGISTER_METHOD(lldb::LanguageType, SBFunction, GetLanguage, ()); + LLDB_REGISTER_METHOD(bool, SBFunction, GetIsOptimized, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBHostOS.cpp b/src/llvm-project/lldb/source/API/SBHostOS.cpp index ac6ab40..c3c92e6 100644 --- a/src/llvm-project/lldb/source/API/SBHostOS.cpp +++ b/src/llvm-project/lldb/source/API/SBHostOS.cpp
@@ -1,16 +1,12 @@ //===-- SBHostOS.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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_DISABLE_PYTHON -#include "Plugins/ScriptInterpreter/Python/lldb-python.h" -#endif - +#include "SBReproducerPrivate.h" #include "lldb/API/SBError.h" #include "lldb/API/SBHostOS.h" #include "lldb/Host/FileSystem.h" @@ -20,7 +16,6 @@ #include "lldb/Host/HostThread.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Utility/FileSpec.h" -#include "lldb/Utility/Log.h" #include "Plugins/ExpressionParser/Clang/ClangHost.h" #ifndef LLDB_DISABLE_PYTHON @@ -34,16 +29,25 @@ using namespace lldb_private; SBFileSpec SBHostOS::GetProgramFileSpec() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBFileSpec, SBHostOS, + GetProgramFileSpec); + SBFileSpec sb_filespec; sb_filespec.SetFileSpec(HostInfo::GetProgramFileSpec()); - return sb_filespec; + return LLDB_RECORD_RESULT(sb_filespec); } SBFileSpec SBHostOS::GetLLDBPythonPath() { - return GetLLDBPath(ePathTypePythonDir); + LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBFileSpec, SBHostOS, + GetLLDBPythonPath); + + return LLDB_RECORD_RESULT(GetLLDBPath(ePathTypePythonDir)); } SBFileSpec SBHostOS::GetLLDBPath(lldb::PathType path_type) { + LLDB_RECORD_STATIC_METHOD(lldb::SBFileSpec, SBHostOS, GetLLDBPath, + (lldb::PathType), path_type); + FileSpec fspec; switch (path_type) { case ePathTypeLLDBShlibDir: @@ -79,10 +83,13 @@ SBFileSpec sb_fspec; sb_fspec.SetFileSpec(fspec); - return sb_fspec; + return LLDB_RECORD_RESULT(sb_fspec); } SBFileSpec SBHostOS::GetUserHomeDirectory() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBFileSpec, SBHostOS, + GetUserHomeDirectory); + SBFileSpec sb_fspec; llvm::SmallString<64> home_dir_path; @@ -91,32 +98,38 @@ FileSystem::Instance().Resolve(homedir); sb_fspec.SetFileSpec(homedir); - return sb_fspec; + return LLDB_RECORD_RESULT(sb_fspec); } lldb::thread_t SBHostOS::ThreadCreate(const char *name, lldb::thread_func_t thread_function, void *thread_arg, SBError *error_ptr) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_DUMMY(lldb::thread_t, SBHostOS, ThreadCreate, + (lldb::thread_func_t, void *, SBError *), name, + thread_function, thread_arg, error_ptr); + llvm::Expected<HostThread> thread = + ThreadLauncher::LaunchThread(name, thread_function, thread_arg); + if (!thread) { + if (error_ptr) + error_ptr->SetError(Status(thread.takeError())); + else + llvm::consumeError(thread.takeError()); + return LLDB_INVALID_HOST_THREAD; + } - if (log) - log->Printf( - "SBHostOS::ThreadCreate (name=\"%s\", thread_function=%p, " - "thread_arg=%p, error_ptr=%p)", - name, - reinterpret_cast<void *>(reinterpret_cast<intptr_t>(thread_function)), - static_cast<void *>(thread_arg), static_cast<void *>(error_ptr)); - - // FIXME: You should log the return value? - - HostThread thread(ThreadLauncher::LaunchThread( - name, thread_function, thread_arg, error_ptr ? error_ptr->get() : NULL)); - return thread.Release(); + return thread->Release(); } -void SBHostOS::ThreadCreated(const char *name) {} +void SBHostOS::ThreadCreated(const char *name) { + LLDB_RECORD_STATIC_METHOD(void, SBHostOS, ThreadCreated, (const char *), + name); +} bool SBHostOS::ThreadCancel(lldb::thread_t thread, SBError *error_ptr) { + LLDB_RECORD_DUMMY(bool, SBHostOS, ThreadCancel, + (lldb::thread_t, lldb::SBError *), thread, + error_ptr); + Status error; HostThread host_thread(thread); error = host_thread.Cancel(); @@ -127,6 +140,10 @@ } bool SBHostOS::ThreadDetach(lldb::thread_t thread, SBError *error_ptr) { + LLDB_RECORD_DUMMY(bool, SBHostOS, ThreadDetach, + (lldb::thread_t, lldb::SBError *), thread, + error_ptr); + Status error; #if defined(_WIN32) if (error_ptr) @@ -143,6 +160,11 @@ bool SBHostOS::ThreadJoin(lldb::thread_t thread, lldb::thread_result_t *result, SBError *error_ptr) { + LLDB_RECORD_DUMMY( + bool, SBHostOS, ThreadJoin, + (lldb::thread_t, lldb::thread_result_t *, lldb::SBError *), thread, + result, error_ptr); + Status error; HostThread host_thread(thread); error = host_thread.Join(result); @@ -151,3 +173,22 @@ host_thread.Release(); return error.Success(); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBHostOS>(Registry &R) { + LLDB_REGISTER_STATIC_METHOD(lldb::SBFileSpec, SBHostOS, GetProgramFileSpec, + ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBFileSpec, SBHostOS, GetLLDBPythonPath, + ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBFileSpec, SBHostOS, GetLLDBPath, + (lldb::PathType)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBFileSpec, SBHostOS, + GetUserHomeDirectory, ()); + LLDB_REGISTER_STATIC_METHOD(void, SBHostOS, ThreadCreated, (const char *)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBInitializerOptions.cpp b/src/llvm-project/lldb/source/API/SBInitializerOptions.cpp deleted file mode 100644 index 8d8ec28..0000000 --- a/src/llvm-project/lldb/source/API/SBInitializerOptions.cpp +++ /dev/null
@@ -1,49 +0,0 @@ -//===-- SBInitializerOptions.cpp --------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "lldb/API/SBInitializerOptions.h" -#include "lldb/Initialization/SystemInitializer.h" - -using namespace lldb; -using namespace lldb_private; - -SBInitializerOptions::SBInitializerOptions(const SBInitializerOptions &rhs) { - m_opaque_up.reset(new InitializerOptions()); - *(m_opaque_up.get()) = rhs.ref(); -} - -const SBInitializerOptions &SBInitializerOptions:: -operator=(const SBInitializerOptions &rhs) { - if (this != &rhs) { - this->ref() = rhs.ref(); - } - return *this; -} - -SBInitializerOptions::~SBInitializerOptions() {} - -SBInitializerOptions::SBInitializerOptions() { - m_opaque_up.reset(new InitializerOptions()); -} - -void SBInitializerOptions::SetCaptureReproducer(bool b) { - m_opaque_up->reproducer_capture = b; -} - -void SBInitializerOptions::SetReplayReproducer(bool b) { - m_opaque_up->reproducer_replay = b; -} - -void SBInitializerOptions::SetReproducerPath(const char *path) { - m_opaque_up->reproducer_path = path; -} - -InitializerOptions &SBInitializerOptions::ref() const { - return *(m_opaque_up.get()); -}
diff --git a/src/llvm-project/lldb/source/API/SBInstruction.cpp b/src/llvm-project/lldb/source/API/SBInstruction.cpp index 462f082..fcf66fd 100644 --- a/src/llvm-project/lldb/source/API/SBInstruction.cpp +++ b/src/llvm-project/lldb/source/API/SBInstruction.cpp
@@ -1,16 +1,17 @@ //===-- SBInstruction.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBFrame.h" + #include "lldb/API/SBInstruction.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBTarget.h" @@ -26,7 +27,8 @@ #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 @@ -45,7 +47,6 @@ // 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, @@ -64,34 +65,55 @@ using namespace lldb; using namespace lldb_private; -SBInstruction::SBInstruction() : m_opaque_sp() {} +SBInstruction::SBInstruction() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBInstruction); +} 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) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBInstruction, (const lldb::SBInstruction &), rhs); +} const SBInstruction &SBInstruction::operator=(const SBInstruction &rhs) { + LLDB_RECORD_METHOD(const lldb::SBInstruction &, + SBInstruction, operator=,(const lldb::SBInstruction &), + rhs); + if (this != &rhs) m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBInstruction::~SBInstruction() {} -bool SBInstruction::IsValid() { return m_opaque_sp && m_opaque_sp->IsValid(); } +bool SBInstruction::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBInstruction, IsValid); + return this->operator bool(); +} +SBInstruction::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBInstruction, operator bool); + + return m_opaque_sp && m_opaque_sp->IsValid(); +} SBAddress SBInstruction::GetAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBAddress, SBInstruction, GetAddress); + SBAddress sb_addr; lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp && inst_sp->GetAddress().IsValid()) sb_addr.SetAddress(&inst_sp->GetAddress()); - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); } const char *SBInstruction::GetMnemonic(SBTarget target) { + LLDB_RECORD_METHOD(const char *, SBInstruction, GetMnemonic, (lldb::SBTarget), + target); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) { ExecutionContext exe_ctx; @@ -105,10 +127,13 @@ } return inst_sp->GetMnemonic(&exe_ctx); } - return NULL; + return nullptr; } const char *SBInstruction::GetOperands(SBTarget target) { + LLDB_RECORD_METHOD(const char *, SBInstruction, GetOperands, (lldb::SBTarget), + target); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) { ExecutionContext exe_ctx; @@ -122,10 +147,13 @@ } return inst_sp->GetOperands(&exe_ctx); } - return NULL; + return nullptr; } const char *SBInstruction::GetComment(SBTarget target) { + LLDB_RECORD_METHOD(const char *, SBInstruction, GetComment, (lldb::SBTarget), + target); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) { ExecutionContext exe_ctx; @@ -139,10 +167,12 @@ } return inst_sp->GetComment(&exe_ctx); } - return NULL; + return nullptr; } size_t SBInstruction::GetByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBInstruction, GetByteSize); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) return inst_sp->GetOpcode().GetByteSize(); @@ -150,6 +180,9 @@ } SBData SBInstruction::GetData(SBTarget target) { + LLDB_RECORD_METHOD(lldb::SBData, SBInstruction, GetData, (lldb::SBTarget), + target); + lldb::SBData sb_data; lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) { @@ -158,10 +191,12 @@ sb_data.SetOpaque(data_extractor_sp); } } - return sb_data; + return LLDB_RECORD_RESULT(sb_data); } bool SBInstruction::DoesBranch() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBInstruction, DoesBranch); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) return inst_sp->DoesBranch(); @@ -169,13 +204,17 @@ } bool SBInstruction::HasDelaySlot() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBInstruction, HasDelaySlot); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) return inst_sp->HasDelaySlot(); return false; } -bool SBInstruction::CanSetBreakpoint () { +bool SBInstruction::CanSetBreakpoint() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBInstruction, CanSetBreakpoint); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) return inst_sp->CanSetBreakpoint(); @@ -191,10 +230,13 @@ void SBInstruction::SetOpaque(const lldb::DisassemblerSP &disasm_sp, const lldb::InstructionSP &inst_sp) { - m_opaque_sp.reset(new InstructionImpl(disasm_sp, inst_sp)); + m_opaque_sp = std::make_shared<InstructionImpl>(disasm_sp, inst_sp); } bool SBInstruction::GetDescription(lldb::SBStream &s) { + LLDB_RECORD_METHOD(bool, SBInstruction, GetDescription, (lldb::SBStream &), + s); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) { SymbolContext sc; @@ -207,14 +249,16 @@ // 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, NULL, &sc, NULL, &format, 0); + inst_sp->Dump(&s.ref(), 0, true, false, nullptr, &sc, nullptr, &format, 0); return true; } return false; } void SBInstruction::Print(FILE *out) { - if (out == NULL) + LLDB_RECORD_METHOD(void, SBInstruction, Print, (FILE *), out); + + if (out == nullptr) return; lldb::InstructionSP inst_sp(GetOpaque()); @@ -228,12 +272,16 @@ StreamFile out_stream(out, false); FormatEntity::Entry format; FormatEntity::Parse("${addr}: ", format); - inst_sp->Dump(&out_stream, 0, true, false, NULL, &sc, NULL, &format, 0); + inst_sp->Dump(&out_stream, 0, true, false, nullptr, &sc, nullptr, &format, + 0); } } bool SBInstruction::EmulateWithFrame(lldb::SBFrame &frame, uint32_t evaluate_options) { + LLDB_RECORD_METHOD(bool, SBInstruction, EmulateWithFrame, + (lldb::SBFrame &, uint32_t), frame, evaluate_options); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp) { lldb::StackFrameSP frame_sp(frame.GetFrameSP()); @@ -256,6 +304,9 @@ } bool SBInstruction::DumpEmulation(const char *triple) { + LLDB_RECORD_METHOD(bool, SBInstruction, DumpEmulation, (const char *), + triple); + lldb::InstructionSP inst_sp(GetOpaque()); if (inst_sp && triple) { return inst_sp->DumpEmulation(HostInfo::GetAugmentedArchSpec(triple)); @@ -265,6 +316,10 @@ bool SBInstruction::TestEmulation(lldb::SBStream &output_stream, const char *test_file) { + LLDB_RECORD_METHOD(bool, SBInstruction, TestEmulation, + (lldb::SBStream &, const char *), output_stream, + test_file); + if (!m_opaque_sp) SetOpaque(lldb::DisassemblerSP(), lldb::InstructionSP(new PseudoInstruction())); @@ -274,3 +329,41 @@ return inst_sp->TestEmulation(output_stream.get(), test_file); return false; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBInstruction>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBInstruction, ()); + LLDB_REGISTER_CONSTRUCTOR(SBInstruction, (const lldb::SBInstruction &)); + LLDB_REGISTER_METHOD( + const lldb::SBInstruction &, + SBInstruction, operator=,(const lldb::SBInstruction &)); + LLDB_REGISTER_METHOD(bool, SBInstruction, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBInstruction, operator bool, ()); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBInstruction, GetAddress, ()); + LLDB_REGISTER_METHOD(const char *, SBInstruction, GetMnemonic, + (lldb::SBTarget)); + LLDB_REGISTER_METHOD(const char *, SBInstruction, GetOperands, + (lldb::SBTarget)); + LLDB_REGISTER_METHOD(const char *, SBInstruction, GetComment, + (lldb::SBTarget)); + LLDB_REGISTER_METHOD(size_t, SBInstruction, GetByteSize, ()); + LLDB_REGISTER_METHOD(lldb::SBData, SBInstruction, GetData, + (lldb::SBTarget)); + LLDB_REGISTER_METHOD(bool, SBInstruction, DoesBranch, ()); + LLDB_REGISTER_METHOD(bool, SBInstruction, HasDelaySlot, ()); + LLDB_REGISTER_METHOD(bool, SBInstruction, CanSetBreakpoint, ()); + LLDB_REGISTER_METHOD(bool, SBInstruction, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(void, SBInstruction, Print, (FILE *)); + LLDB_REGISTER_METHOD(bool, SBInstruction, EmulateWithFrame, + (lldb::SBFrame &, uint32_t)); + LLDB_REGISTER_METHOD(bool, SBInstruction, DumpEmulation, (const char *)); + LLDB_REGISTER_METHOD(bool, SBInstruction, TestEmulation, + (lldb::SBStream &, const char *)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBInstructionList.cpp b/src/llvm-project/lldb/source/API/SBInstructionList.cpp index 29e0c96..cce923b 100644 --- a/src/llvm-project/lldb/source/API/SBInstructionList.cpp +++ b/src/llvm-project/lldb/source/API/SBInstructionList.cpp
@@ -1,15 +1,15 @@ //===-- SBInstructionList.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/SBInstruction.h" +#include "SBReproducerPrivate.h" #include "lldb/API/SBAddress.h" +#include "lldb/API/SBInstruction.h" #include "lldb/API/SBStream.h" #include "lldb/Core/Disassembler.h" #include "lldb/Core/Module.h" @@ -19,40 +19,66 @@ using namespace lldb; using namespace lldb_private; -SBInstructionList::SBInstructionList() : m_opaque_sp() {} +SBInstructionList::SBInstructionList() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBInstructionList); +} SBInstructionList::SBInstructionList(const SBInstructionList &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBInstructionList, (const lldb::SBInstructionList &), + rhs); +} const SBInstructionList &SBInstructionList:: operator=(const SBInstructionList &rhs) { + LLDB_RECORD_METHOD( + const lldb::SBInstructionList &, + SBInstructionList, operator=,(const lldb::SBInstructionList &), rhs); + if (this != &rhs) m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBInstructionList::~SBInstructionList() {} -bool SBInstructionList::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBInstructionList::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBInstructionList, IsValid); + return this->operator bool(); +} +SBInstructionList::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBInstructionList, operator bool); + + return m_opaque_sp.get() != nullptr; +} size_t SBInstructionList::GetSize() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBInstructionList, GetSize); + if (m_opaque_sp) return m_opaque_sp->GetInstructionList().GetSize(); return 0; } SBInstruction SBInstructionList::GetInstructionAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBInstruction, SBInstructionList, + GetInstructionAtIndex, (uint32_t), 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; + return LLDB_RECORD_RESULT(inst); } size_t SBInstructionList::GetInstructionsCount(const SBAddress &start, - const SBAddress &end, - bool canSetBreakpoint) { + const SBAddress &end, + bool canSetBreakpoint) { + LLDB_RECORD_METHOD(size_t, SBInstructionList, GetInstructionsCount, + (const lldb::SBAddress &, const lldb::SBAddress &, bool), + start, end, canSetBreakpoint); + size_t num_instructions = GetSize(); size_t i = 0; SBAddress addr; @@ -75,20 +101,32 @@ return upper_index - lower_index - instructions_to_skip; } -void SBInstructionList::Clear() { m_opaque_sp.reset(); } +void SBInstructionList::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBInstructionList, Clear); -void SBInstructionList::AppendInstruction(SBInstruction insn) {} + m_opaque_sp.reset(); +} + +void SBInstructionList::AppendInstruction(SBInstruction insn) { + LLDB_RECORD_METHOD(void, SBInstructionList, AppendInstruction, + (lldb::SBInstruction), insn); +} void SBInstructionList::SetDisassembler(const lldb::DisassemblerSP &opaque_sp) { m_opaque_sp = opaque_sp; } void SBInstructionList::Print(FILE *out) { - if (out == NULL) + LLDB_RECORD_METHOD(void, SBInstructionList, Print, (FILE *), out); + + if (out == nullptr) return; } bool SBInstructionList::GetDescription(lldb::SBStream &description) { + LLDB_RECORD_METHOD(bool, SBInstructionList, GetDescription, + (lldb::SBStream &), description); + if (m_opaque_sp) { size_t num_instructions = GetSize(); if (num_instructions) { @@ -104,7 +142,7 @@ for (size_t i = 0; i < num_instructions; ++i) { Instruction *inst = m_opaque_sp->GetInstructionList().GetInstructionAtIndex(i).get(); - if (inst == NULL) + if (inst == nullptr) break; const Address &addr = inst->GetAddress(); @@ -115,7 +153,7 @@ addr, eSymbolContextEverything, sc); } - inst->Dump(&sref, max_opcode_byte_size, true, false, NULL, &sc, + inst->Dump(&sref, max_opcode_byte_size, true, false, nullptr, &sc, &prev_sc, &format, 0); sref.EOL(); } @@ -126,6 +164,9 @@ } bool SBInstructionList::DumpEmulationForAllInstructions(const char *triple) { + LLDB_RECORD_METHOD(bool, SBInstructionList, DumpEmulationForAllInstructions, + (const char *), triple); + if (m_opaque_sp) { size_t len = GetSize(); for (size_t i = 0; i < len; ++i) { @@ -135,3 +176,35 @@ } return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBInstructionList>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBInstructionList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBInstructionList, + (const lldb::SBInstructionList &)); + LLDB_REGISTER_METHOD( + const lldb::SBInstructionList &, + SBInstructionList, operator=,(const lldb::SBInstructionList &)); + LLDB_REGISTER_METHOD_CONST(bool, SBInstructionList, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBInstructionList, operator bool, ()); + LLDB_REGISTER_METHOD(size_t, SBInstructionList, GetSize, ()); + LLDB_REGISTER_METHOD(lldb::SBInstruction, SBInstructionList, + GetInstructionAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD( + size_t, SBInstructionList, GetInstructionsCount, + (const lldb::SBAddress &, const lldb::SBAddress &, bool)); + LLDB_REGISTER_METHOD(void, SBInstructionList, Clear, ()); + LLDB_REGISTER_METHOD(void, SBInstructionList, AppendInstruction, + (lldb::SBInstruction)); + LLDB_REGISTER_METHOD(void, SBInstructionList, Print, (FILE *)); + LLDB_REGISTER_METHOD(bool, SBInstructionList, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(bool, SBInstructionList, + DumpEmulationForAllInstructions, (const char *)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBLanguageRuntime.cpp b/src/llvm-project/lldb/source/API/SBLanguageRuntime.cpp index d3b7514..04bd08f 100644 --- a/src/llvm-project/lldb/source/API/SBLanguageRuntime.cpp +++ b/src/llvm-project/lldb/source/API/SBLanguageRuntime.cpp
@@ -1,13 +1,13 @@ //===-- SBLanguageRuntime.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/Target/Language.h" using namespace lldb; @@ -15,11 +15,32 @@ lldb::LanguageType SBLanguageRuntime::GetLanguageTypeFromString(const char *string) { + LLDB_RECORD_STATIC_METHOD(lldb::LanguageType, SBLanguageRuntime, + GetLanguageTypeFromString, (const char *), string); + return Language::GetLanguageTypeFromString( llvm::StringRef::withNullAsEmpty(string)); } const char * SBLanguageRuntime::GetNameForLanguageType(lldb::LanguageType language) { + LLDB_RECORD_STATIC_METHOD(const char *, SBLanguageRuntime, + GetNameForLanguageType, (lldb::LanguageType), + language); + return Language::GetNameForLanguageType(language); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBLanguageRuntime>(Registry &R) { + LLDB_REGISTER_STATIC_METHOD(lldb::LanguageType, SBLanguageRuntime, + GetLanguageTypeFromString, (const char *)); + LLDB_REGISTER_STATIC_METHOD(const char *, SBLanguageRuntime, + GetNameForLanguageType, (lldb::LanguageType)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBLaunchInfo.cpp b/src/llvm-project/lldb/source/API/SBLaunchInfo.cpp index b1bbfa5..5c5e697 100644 --- a/src/llvm-project/lldb/source/API/SBLaunchInfo.cpp +++ b/src/llvm-project/lldb/source/API/SBLaunchInfo.cpp
@@ -1,17 +1,17 @@ //===-- SBLaunchInfo.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBListener.h" -#include "lldb/Target/ProcessLaunchInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" using namespace lldb; using namespace lldb_private; @@ -36,6 +36,8 @@ SBLaunchInfo::SBLaunchInfo(const char **argv) : m_opaque_sp(new SBLaunchInfoImpl()) { + LLDB_RECORD_CONSTRUCTOR(SBLaunchInfo, (const char **), argv); + m_opaque_sp->GetFlags().Reset(eLaunchFlagDebug | eLaunchFlagDisableASLR); if (argv && argv[0]) m_opaque_sp->GetArguments().SetArguments(argv); @@ -51,46 +53,92 @@ *m_opaque_sp = info; } -lldb::pid_t SBLaunchInfo::GetProcessID() { return m_opaque_sp->GetProcessID(); } +lldb::pid_t SBLaunchInfo::GetProcessID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::pid_t, SBLaunchInfo, GetProcessID); -uint32_t SBLaunchInfo::GetUserID() { return m_opaque_sp->GetUserID(); } + return m_opaque_sp->GetProcessID(); +} -uint32_t SBLaunchInfo::GetGroupID() { return m_opaque_sp->GetGroupID(); } +uint32_t SBLaunchInfo::GetUserID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBLaunchInfo, GetUserID); -bool SBLaunchInfo::UserIDIsValid() { return m_opaque_sp->UserIDIsValid(); } + return m_opaque_sp->GetUserID(); +} -bool SBLaunchInfo::GroupIDIsValid() { return m_opaque_sp->GroupIDIsValid(); } +uint32_t SBLaunchInfo::GetGroupID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBLaunchInfo, GetGroupID); -void SBLaunchInfo::SetUserID(uint32_t uid) { m_opaque_sp->SetUserID(uid); } + return m_opaque_sp->GetGroupID(); +} -void SBLaunchInfo::SetGroupID(uint32_t gid) { m_opaque_sp->SetGroupID(gid); } +bool SBLaunchInfo::UserIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBLaunchInfo, UserIDIsValid); + + return m_opaque_sp->UserIDIsValid(); +} + +bool SBLaunchInfo::GroupIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBLaunchInfo, GroupIDIsValid); + + return m_opaque_sp->GroupIDIsValid(); +} + +void SBLaunchInfo::SetUserID(uint32_t uid) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetUserID, (uint32_t), uid); + + m_opaque_sp->SetUserID(uid); +} + +void SBLaunchInfo::SetGroupID(uint32_t gid) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetGroupID, (uint32_t), gid); + + m_opaque_sp->SetGroupID(gid); +} SBFileSpec SBLaunchInfo::GetExecutableFile() { - return SBFileSpec(m_opaque_sp->GetExecutableFile()); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFileSpec, SBLaunchInfo, GetExecutableFile); + + return LLDB_RECORD_RESULT(SBFileSpec(m_opaque_sp->GetExecutableFile())); } void SBLaunchInfo::SetExecutableFile(SBFileSpec exe_file, bool add_as_first_arg) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetExecutableFile, + (lldb::SBFileSpec, bool), exe_file, add_as_first_arg); + m_opaque_sp->SetExecutableFile(exe_file.ref(), add_as_first_arg); } SBListener SBLaunchInfo::GetListener() { - return SBListener(m_opaque_sp->GetListener()); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBListener, SBLaunchInfo, GetListener); + + return LLDB_RECORD_RESULT(SBListener(m_opaque_sp->GetListener())); } void SBLaunchInfo::SetListener(SBListener &listener) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetListener, (lldb::SBListener &), + listener); + m_opaque_sp->SetListener(listener.GetSP()); } uint32_t SBLaunchInfo::GetNumArguments() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBLaunchInfo, GetNumArguments); + return m_opaque_sp->GetArguments().GetArgumentCount(); } const char *SBLaunchInfo::GetArgumentAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(const char *, SBLaunchInfo, GetArgumentAtIndex, (uint32_t), + idx); + return m_opaque_sp->GetArguments().GetArgumentAtIndex(idx); } void SBLaunchInfo::SetArguments(const char **argv, bool append) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetArguments, (const char **, bool), + argv, append); + if (append) { if (argv) m_opaque_sp->GetArguments().AppendArguments(argv); @@ -103,16 +151,24 @@ } uint32_t SBLaunchInfo::GetNumEnvironmentEntries() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBLaunchInfo, GetNumEnvironmentEntries); + return m_opaque_sp->GetEnvironment().size(); } const char *SBLaunchInfo::GetEnvironmentEntryAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(const char *, SBLaunchInfo, GetEnvironmentEntryAtIndex, + (uint32_t), idx); + if (idx > GetNumEnvironmentEntries()) return nullptr; return m_opaque_sp->GetEnvp()[idx]; } void SBLaunchInfo::SetEnvironmentEntries(const char **envp, bool append) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetEnvironmentEntries, + (const char **, bool), envp, append); + Environment env(envp); if (append) m_opaque_sp->GetEnvironment().insert(env.begin(), env.end()); @@ -121,33 +177,54 @@ m_opaque_sp->RegenerateEnvp(); } -void SBLaunchInfo::Clear() { m_opaque_sp->Clear(); } +void SBLaunchInfo::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBLaunchInfo, Clear); + + m_opaque_sp->Clear(); +} const char *SBLaunchInfo::GetWorkingDirectory() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBLaunchInfo, + GetWorkingDirectory); + return m_opaque_sp->GetWorkingDirectory().GetCString(); } void SBLaunchInfo::SetWorkingDirectory(const char *working_dir) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetWorkingDirectory, (const char *), + working_dir); + m_opaque_sp->SetWorkingDirectory(FileSpec(working_dir)); } uint32_t SBLaunchInfo::GetLaunchFlags() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBLaunchInfo, GetLaunchFlags); + return m_opaque_sp->GetFlags().Get(); } void SBLaunchInfo::SetLaunchFlags(uint32_t flags) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetLaunchFlags, (uint32_t), flags); + m_opaque_sp->GetFlags().Reset(flags); } const char *SBLaunchInfo::GetProcessPluginName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBLaunchInfo, GetProcessPluginName); + return m_opaque_sp->GetProcessPluginName(); } void SBLaunchInfo::SetProcessPluginName(const char *plugin_name) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetProcessPluginName, (const char *), + plugin_name); + return m_opaque_sp->SetProcessPluginName(plugin_name); } const char *SBLaunchInfo::GetShell() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBLaunchInfo, GetShell); + // 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()); @@ -155,54 +232,148 @@ } void SBLaunchInfo::SetShell(const char *path) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetShell, (const char *), path); + m_opaque_sp->SetShell(FileSpec(path)); } bool SBLaunchInfo::GetShellExpandArguments() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBLaunchInfo, GetShellExpandArguments); + return m_opaque_sp->GetShellExpandArguments(); } void SBLaunchInfo::SetShellExpandArguments(bool expand) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetShellExpandArguments, (bool), + expand); + m_opaque_sp->SetShellExpandArguments(expand); } uint32_t SBLaunchInfo::GetResumeCount() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBLaunchInfo, GetResumeCount); + return m_opaque_sp->GetResumeCount(); } void SBLaunchInfo::SetResumeCount(uint32_t c) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetResumeCount, (uint32_t), c); + m_opaque_sp->SetResumeCount(c); } bool SBLaunchInfo::AddCloseFileAction(int fd) { + LLDB_RECORD_METHOD(bool, SBLaunchInfo, AddCloseFileAction, (int), fd); + return m_opaque_sp->AppendCloseFileAction(fd); } bool SBLaunchInfo::AddDuplicateFileAction(int fd, int dup_fd) { + LLDB_RECORD_METHOD(bool, SBLaunchInfo, AddDuplicateFileAction, (int, int), fd, + dup_fd); + return m_opaque_sp->AppendDuplicateFileAction(fd, dup_fd); } bool SBLaunchInfo::AddOpenFileAction(int fd, const char *path, bool read, bool write) { + LLDB_RECORD_METHOD(bool, SBLaunchInfo, AddOpenFileAction, + (int, const char *, bool, bool), fd, path, read, write); + return m_opaque_sp->AppendOpenFileAction(fd, FileSpec(path), read, write); } bool SBLaunchInfo::AddSuppressFileAction(int fd, bool read, bool write) { + LLDB_RECORD_METHOD(bool, SBLaunchInfo, AddSuppressFileAction, + (int, bool, bool), fd, read, write); + return m_opaque_sp->AppendSuppressFileAction(fd, read, write); } void SBLaunchInfo::SetLaunchEventData(const char *data) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetLaunchEventData, (const char *), + data); + m_opaque_sp->SetLaunchEventData(data); } const char *SBLaunchInfo::GetLaunchEventData() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBLaunchInfo, + GetLaunchEventData); + return m_opaque_sp->GetLaunchEventData(); } void SBLaunchInfo::SetDetachOnError(bool enable) { + LLDB_RECORD_METHOD(void, SBLaunchInfo, SetDetachOnError, (bool), enable); + m_opaque_sp->SetDetachOnError(enable); } bool SBLaunchInfo::GetDetachOnError() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBLaunchInfo, GetDetachOnError); + return m_opaque_sp->GetDetachOnError(); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBLaunchInfo>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBLaunchInfo, (const char **)); + LLDB_REGISTER_METHOD(lldb::pid_t, SBLaunchInfo, GetProcessID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBLaunchInfo, GetUserID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBLaunchInfo, GetGroupID, ()); + LLDB_REGISTER_METHOD(bool, SBLaunchInfo, UserIDIsValid, ()); + LLDB_REGISTER_METHOD(bool, SBLaunchInfo, GroupIDIsValid, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetUserID, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetGroupID, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBFileSpec, SBLaunchInfo, GetExecutableFile, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetExecutableFile, + (lldb::SBFileSpec, bool)); + LLDB_REGISTER_METHOD(lldb::SBListener, SBLaunchInfo, GetListener, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetListener, (lldb::SBListener &)); + LLDB_REGISTER_METHOD(uint32_t, SBLaunchInfo, GetNumArguments, ()); + LLDB_REGISTER_METHOD(const char *, SBLaunchInfo, GetArgumentAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetArguments, + (const char **, bool)); + LLDB_REGISTER_METHOD(uint32_t, SBLaunchInfo, GetNumEnvironmentEntries, ()); + LLDB_REGISTER_METHOD(const char *, SBLaunchInfo, GetEnvironmentEntryAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetEnvironmentEntries, + (const char **, bool)); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, Clear, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBLaunchInfo, GetWorkingDirectory, + ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetWorkingDirectory, + (const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBLaunchInfo, GetLaunchFlags, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetLaunchFlags, (uint32_t)); + LLDB_REGISTER_METHOD(const char *, SBLaunchInfo, GetProcessPluginName, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetProcessPluginName, + (const char *)); + LLDB_REGISTER_METHOD(const char *, SBLaunchInfo, GetShell, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetShell, (const char *)); + LLDB_REGISTER_METHOD(bool, SBLaunchInfo, GetShellExpandArguments, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetShellExpandArguments, (bool)); + LLDB_REGISTER_METHOD(uint32_t, SBLaunchInfo, GetResumeCount, ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetResumeCount, (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBLaunchInfo, AddCloseFileAction, (int)); + LLDB_REGISTER_METHOD(bool, SBLaunchInfo, AddDuplicateFileAction, + (int, int)); + LLDB_REGISTER_METHOD(bool, SBLaunchInfo, AddOpenFileAction, + (int, const char *, bool, bool)); + LLDB_REGISTER_METHOD(bool, SBLaunchInfo, AddSuppressFileAction, + (int, bool, bool)); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetLaunchEventData, + (const char *)); + LLDB_REGISTER_METHOD_CONST(const char *, SBLaunchInfo, GetLaunchEventData, + ()); + LLDB_REGISTER_METHOD(void, SBLaunchInfo, SetDetachOnError, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBLaunchInfo, GetDetachOnError, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBLineEntry.cpp b/src/llvm-project/lldb/source/API/SBLineEntry.cpp index 6f59fe3..010a605 100644 --- a/src/llvm-project/lldb/source/API/SBLineEntry.cpp +++ b/src/llvm-project/lldb/source/API/SBLineEntry.cpp
@@ -1,148 +1,142 @@ //===-- SBLineEntry.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <limits.h> - #include "lldb/API/SBLineEntry.h" +#include "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBStream.h" #include "lldb/Host/PosixApi.h" #include "lldb/Symbol/LineEntry.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" +#include <limits.h> + using namespace lldb; using namespace lldb_private; -SBLineEntry::SBLineEntry() : m_opaque_ap() {} +SBLineEntry::SBLineEntry() : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBLineEntry); +} -SBLineEntry::SBLineEntry(const SBLineEntry &rhs) : m_opaque_ap() { - if (rhs.IsValid()) - ref() = rhs.ref(); +SBLineEntry::SBLineEntry(const SBLineEntry &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBLineEntry, (const lldb::SBLineEntry &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBLineEntry::SBLineEntry(const lldb_private::LineEntry *lldb_object_ptr) - : m_opaque_ap() { + : m_opaque_up() { if (lldb_object_ptr) - ref() = *lldb_object_ptr; + m_opaque_up = llvm::make_unique<LineEntry>(*lldb_object_ptr); } const SBLineEntry &SBLineEntry::operator=(const SBLineEntry &rhs) { - if (this != &rhs) { - if (rhs.IsValid()) - ref() = rhs.ref(); - else - m_opaque_ap.reset(); - } - return *this; + LLDB_RECORD_METHOD(const lldb::SBLineEntry &, + SBLineEntry, operator=,(const lldb::SBLineEntry &), rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } void SBLineEntry::SetLineEntry(const lldb_private::LineEntry &lldb_object_ref) { - ref() = lldb_object_ref; + m_opaque_up = llvm::make_unique<LineEntry>(lldb_object_ref); } SBLineEntry::~SBLineEntry() {} SBAddress SBLineEntry::GetStartAddress() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBLineEntry, + GetStartAddress); + SBAddress sb_address; - if (m_opaque_ap) - sb_address.SetAddress(&m_opaque_ap->range.GetBaseAddress()); + if (m_opaque_up) + sb_address.SetAddress(&m_opaque_up->range.GetBaseAddress()); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - StreamString sstr; - const Address *addr = sb_address.get(); - if (addr) - addr->Dump(&sstr, NULL, Address::DumpStyleModuleWithFileAddress, - Address::DumpStyleInvalid, 4); - log->Printf("SBLineEntry(%p)::GetStartAddress () => SBAddress (%p): %s", - static_cast<void *>(m_opaque_ap.get()), - static_cast<void *>(sb_address.get()), sstr.GetData()); - } - - return sb_address; + return LLDB_RECORD_RESULT(sb_address); } SBAddress SBLineEntry::GetEndAddress() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBLineEntry, GetEndAddress); + SBAddress sb_address; - if (m_opaque_ap) { - sb_address.SetAddress(&m_opaque_ap->range.GetBaseAddress()); - sb_address.OffsetAddress(m_opaque_ap->range.GetByteSize()); + if (m_opaque_up) { + sb_address.SetAddress(&m_opaque_up->range.GetBaseAddress()); + sb_address.OffsetAddress(m_opaque_up->range.GetByteSize()); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - StreamString sstr; - const Address *addr = sb_address.get(); - if (addr) - addr->Dump(&sstr, NULL, Address::DumpStyleModuleWithFileAddress, - Address::DumpStyleInvalid, 4); - log->Printf("SBLineEntry(%p)::GetEndAddress () => SBAddress (%p): %s", - static_cast<void *>(m_opaque_ap.get()), - static_cast<void *>(sb_address.get()), sstr.GetData()); - } - return sb_address; + return LLDB_RECORD_RESULT(sb_address); } bool SBLineEntry::IsValid() const { - return m_opaque_ap.get() && m_opaque_ap->IsValid(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBLineEntry, IsValid); + return this->operator bool(); +} +SBLineEntry::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBLineEntry, operator bool); + + return m_opaque_up.get() && m_opaque_up->IsValid(); } SBFileSpec SBLineEntry::GetFileSpec() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBLineEntry, GetFileSpec); SBFileSpec sb_file_spec; - if (m_opaque_ap.get() && m_opaque_ap->file) - sb_file_spec.SetFileSpec(m_opaque_ap->file); + if (m_opaque_up.get() && m_opaque_up->file) + sb_file_spec.SetFileSpec(m_opaque_up->file); - if (log) { - SBStream sstr; - sb_file_spec.GetDescription(sstr); - log->Printf("SBLineEntry(%p)::GetFileSpec () => SBFileSpec(%p): %s", - static_cast<void *>(m_opaque_ap.get()), - static_cast<const void *>(sb_file_spec.get()), sstr.GetData()); - } - - return sb_file_spec; + return LLDB_RECORD_RESULT(sb_file_spec); } uint32_t SBLineEntry::GetLine() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBLineEntry, GetLine); uint32_t line = 0; - if (m_opaque_ap) - line = m_opaque_ap->line; - - if (log) - log->Printf("SBLineEntry(%p)::GetLine () => %u", - static_cast<void *>(m_opaque_ap.get()), line); + if (m_opaque_up) + line = m_opaque_up->line; return line; } uint32_t SBLineEntry::GetColumn() const { - if (m_opaque_ap) - return m_opaque_ap->column; + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBLineEntry, GetColumn); + + if (m_opaque_up) + return m_opaque_up->column; return 0; } void SBLineEntry::SetFileSpec(lldb::SBFileSpec filespec) { + LLDB_RECORD_METHOD(void, SBLineEntry, SetFileSpec, (lldb::SBFileSpec), + filespec); + if (filespec.IsValid()) ref().file = filespec.ref(); else ref().file.Clear(); } -void SBLineEntry::SetLine(uint32_t line) { ref().line = line; } +void SBLineEntry::SetLine(uint32_t line) { + LLDB_RECORD_METHOD(void, SBLineEntry, SetLine, (uint32_t), line); -void SBLineEntry::SetColumn(uint32_t column) { ref().line = column; } + ref().line = line; +} + +void SBLineEntry::SetColumn(uint32_t column) { + LLDB_RECORD_METHOD(void, SBLineEntry, SetColumn, (uint32_t), column); + + ref().line = column; +} bool SBLineEntry::operator==(const SBLineEntry &rhs) const { - lldb_private::LineEntry *lhs_ptr = m_opaque_ap.get(); - lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_ap.get(); + LLDB_RECORD_METHOD_CONST( + bool, SBLineEntry, operator==,(const lldb::SBLineEntry &), 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; @@ -151,8 +145,11 @@ } bool SBLineEntry::operator!=(const SBLineEntry &rhs) const { - lldb_private::LineEntry *lhs_ptr = m_opaque_ap.get(); - lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_ap.get(); + LLDB_RECORD_METHOD_CONST( + bool, SBLineEntry, operator!=,(const lldb::SBLineEntry &), 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; @@ -161,23 +158,26 @@ } const lldb_private::LineEntry *SBLineEntry::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } lldb_private::LineEntry &SBLineEntry::ref() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new lldb_private::LineEntry()); - return *m_opaque_ap; + if (m_opaque_up == nullptr) + m_opaque_up.reset(new lldb_private::LineEntry()); + return *m_opaque_up; } -const lldb_private::LineEntry &SBLineEntry::ref() const { return *m_opaque_ap; } +const lldb_private::LineEntry &SBLineEntry::ref() const { return *m_opaque_up; } bool SBLineEntry::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBLineEntry, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); - if (m_opaque_ap) { + if (m_opaque_up) { char file_path[PATH_MAX * 2]; - m_opaque_ap->file.GetPath(file_path, sizeof(file_path)); + m_opaque_up->file.GetPath(file_path, sizeof(file_path)); strm.Printf("%s:%u", file_path, GetLine()); if (GetColumn() > 0) strm.Printf(":%u", GetColumn()); @@ -187,4 +187,34 @@ return true; } -lldb_private::LineEntry *SBLineEntry::get() { return m_opaque_ap.get(); } +lldb_private::LineEntry *SBLineEntry::get() { return m_opaque_up.get(); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBLineEntry>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBLineEntry, ()); + LLDB_REGISTER_CONSTRUCTOR(SBLineEntry, (const lldb::SBLineEntry &)); + LLDB_REGISTER_METHOD(const lldb::SBLineEntry &, + SBLineEntry, operator=,(const lldb::SBLineEntry &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBLineEntry, GetStartAddress, + ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBLineEntry, GetEndAddress, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBLineEntry, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBLineEntry, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBLineEntry, GetFileSpec, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBLineEntry, GetLine, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBLineEntry, GetColumn, ()); + LLDB_REGISTER_METHOD(void, SBLineEntry, SetFileSpec, (lldb::SBFileSpec)); + LLDB_REGISTER_METHOD(void, SBLineEntry, SetLine, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBLineEntry, SetColumn, (uint32_t)); + LLDB_REGISTER_METHOD_CONST( + bool, SBLineEntry, operator==,(const lldb::SBLineEntry &)); + LLDB_REGISTER_METHOD_CONST( + bool, SBLineEntry, operator!=,(const lldb::SBLineEntry &)); + LLDB_REGISTER_METHOD(bool, SBLineEntry, GetDescription, (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBListener.cpp b/src/llvm-project/lldb/source/API/SBListener.cpp index e671d9f..4fe90f6 100644 --- a/src/llvm-project/lldb/source/API/SBListener.cpp +++ b/src/llvm-project/lldb/source/API/SBListener.cpp
@@ -1,13 +1,13 @@ //===-- SBListener.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBBroadcaster.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBEvent.h" @@ -15,32 +15,34 @@ #include "lldb/Core/Debugger.h" #include "lldb/Utility/Broadcaster.h" #include "lldb/Utility/Listener.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" using namespace lldb; using namespace lldb_private; -SBListener::SBListener() : m_opaque_sp(), m_unused_ptr(NULL) {} +SBListener::SBListener() : m_opaque_sp(), m_unused_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBListener); +} SBListener::SBListener(const char *name) : m_opaque_sp(Listener::MakeListener(name)), m_unused_ptr(nullptr) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf("SBListener::SBListener (name=\"%s\") => SBListener(%p)", name, - static_cast<void *>(m_opaque_sp.get())); + LLDB_RECORD_CONSTRUCTOR(SBListener, (const char *), name); } SBListener::SBListener(const SBListener &rhs) - : m_opaque_sp(rhs.m_opaque_sp), m_unused_ptr(nullptr) {} + : m_opaque_sp(rhs.m_opaque_sp), m_unused_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR(SBListener, (const lldb::SBListener &), rhs); +} const lldb::SBListener &SBListener::operator=(const lldb::SBListener &rhs) { + LLDB_RECORD_METHOD(const lldb::SBListener &, + SBListener, operator=,(const lldb::SBListener &), rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; m_unused_ptr = nullptr; } - return *this; + return LLDB_RECORD_RESULT(*this); } SBListener::SBListener(const lldb::ListenerSP &listener_sp) @@ -48,15 +50,28 @@ SBListener::~SBListener() {} -bool SBListener::IsValid() const { return m_opaque_sp != nullptr; } +bool SBListener::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBListener, IsValid); + return this->operator bool(); +} +SBListener::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBListener, operator bool); + + return m_opaque_sp != nullptr; +} void SBListener::AddEvent(const SBEvent &event) { + LLDB_RECORD_METHOD(void, SBListener, AddEvent, (const lldb::SBEvent &), + event); + EventSP &event_sp = event.GetSP(); if (event_sp) m_opaque_sp->AddEvent(event_sp); } void SBListener::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBListener, Clear); + if (m_opaque_sp) m_opaque_sp->Clear(); } @@ -64,6 +79,10 @@ uint32_t SBListener::StartListeningForEventClass(SBDebugger &debugger, const char *broadcaster_class, uint32_t event_mask) { + LLDB_RECORD_METHOD(uint32_t, SBListener, StartListeningForEventClass, + (lldb::SBDebugger &, const char *, uint32_t), debugger, + broadcaster_class, event_mask); + if (m_opaque_sp) { Debugger *lldb_debugger = debugger.get(); if (!lldb_debugger) @@ -78,6 +97,10 @@ bool SBListener::StopListeningForEventClass(SBDebugger &debugger, const char *broadcaster_class, uint32_t event_mask) { + LLDB_RECORD_METHOD(bool, SBListener, StopListeningForEventClass, + (lldb::SBDebugger &, const char *, uint32_t), debugger, + broadcaster_class, event_mask); + if (m_opaque_sp) { Debugger *lldb_debugger = debugger.get(); if (!lldb_debugger) @@ -91,47 +114,25 @@ uint32_t SBListener::StartListeningForEvents(const SBBroadcaster &broadcaster, uint32_t event_mask) { + LLDB_RECORD_METHOD(uint32_t, SBListener, StartListeningForEvents, + (const lldb::SBBroadcaster &, uint32_t), 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); } - Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); - if (log) { - StreamString sstr_requested; - StreamString sstr_acquired; - - Broadcaster *lldb_broadcaster = broadcaster.get(); - if (lldb_broadcaster) { - const bool got_requested_names = - lldb_broadcaster->GetEventNames(sstr_requested, event_mask, false); - const bool got_acquired_names = lldb_broadcaster->GetEventNames( - sstr_acquired, acquired_event_mask, false); - log->Printf("SBListener(%p)::StartListeneingForEvents " - "(SBBroadcaster(%p): %s, event_mask=0x%8.8x%s%s%s) => " - "0x%8.8x%s%s%s", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(lldb_broadcaster), - lldb_broadcaster->GetBroadcasterName().GetCString(), - event_mask, got_requested_names ? " (" : "", - sstr_requested.GetData(), got_requested_names ? ")" : "", - acquired_event_mask, got_acquired_names ? " (" : "", - sstr_acquired.GetData(), got_acquired_names ? ")" : ""); - } else { - log->Printf("SBListener(%p)::StartListeneingForEvents " - "(SBBroadcaster(%p), event_mask=0x%8.8x) => 0x%8.8x", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(lldb_broadcaster), event_mask, - acquired_event_mask); - } - } - return acquired_event_mask; } bool SBListener::StopListeningForEvents(const SBBroadcaster &broadcaster, uint32_t event_mask) { + LLDB_RECORD_METHOD(bool, SBListener, StopListeningForEvents, + (const lldb::SBBroadcaster &, uint32_t), broadcaster, + event_mask); + if (m_opaque_sp && broadcaster.IsValid()) { return m_opaque_sp->StopListeningForEvents(broadcaster.get(), event_mask); } @@ -139,20 +140,9 @@ } bool SBListener::WaitForEvent(uint32_t timeout_secs, SBEvent &event) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (timeout_secs == UINT32_MAX) { - log->Printf("SBListener(%p)::WaitForEvent (timeout_secs=INFINITE, " - "SBEvent(%p))...", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(event.get())); - } else { - log->Printf( - "SBListener(%p)::WaitForEvent (timeout_secs=%d, SBEvent(%p))...", - static_cast<void *>(m_opaque_sp.get()), timeout_secs, - static_cast<void *>(event.get())); - } - } + LLDB_RECORD_METHOD(bool, SBListener, WaitForEvent, + (uint32_t, lldb::SBEvent &), timeout_secs, event); + bool success = false; if (m_opaque_sp) { @@ -169,27 +159,18 @@ } } - if (log) { - if (timeout_secs == UINT32_MAX) { - log->Printf("SBListener(%p)::WaitForEvent (timeout_secs=INFINITE, " - "SBEvent(%p)) => %i", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(event.get()), success); - } else { - log->Printf( - "SBListener(%p)::WaitForEvent (timeout_secs=%d, SBEvent(%p)) => %i", - static_cast<void *>(m_opaque_sp.get()), timeout_secs, - static_cast<void *>(event.get()), success); - } - } if (!success) - event.reset(NULL); + event.reset(nullptr); return success; } bool SBListener::WaitForEventForBroadcaster(uint32_t num_seconds, const SBBroadcaster &broadcaster, SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, WaitForEventForBroadcaster, + (uint32_t, const lldb::SBBroadcaster &, lldb::SBEvent &), + num_seconds, broadcaster, event); + if (m_opaque_sp && broadcaster.IsValid()) { Timeout<std::micro> timeout(llvm::None); if (num_seconds != UINT32_MAX) @@ -201,13 +182,18 @@ return true; } } - event.reset(NULL); + event.reset(nullptr); return false; } bool SBListener::WaitForEventForBroadcasterWithType( uint32_t num_seconds, const SBBroadcaster &broadcaster, uint32_t event_type_mask, SBEvent &event) { + LLDB_RECORD_METHOD( + bool, SBListener, WaitForEventForBroadcasterWithType, + (uint32_t, const lldb::SBBroadcaster &, uint32_t, lldb::SBEvent &), + num_seconds, broadcaster, event_type_mask, event); + if (m_opaque_sp && broadcaster.IsValid()) { Timeout<std::micro> timeout(llvm::None); if (num_seconds != UINT32_MAX) @@ -219,42 +205,55 @@ return true; } } - event.reset(NULL); + event.reset(nullptr); return false; } bool SBListener::PeekAtNextEvent(SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, PeekAtNextEvent, (lldb::SBEvent &), + event); + if (m_opaque_sp) { event.reset(m_opaque_sp->PeekAtNextEvent()); return event.IsValid(); } - event.reset(NULL); + event.reset(nullptr); return false; } bool SBListener::PeekAtNextEventForBroadcaster(const SBBroadcaster &broadcaster, SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, PeekAtNextEventForBroadcaster, + (const lldb::SBBroadcaster &, lldb::SBEvent &), + broadcaster, event); + if (m_opaque_sp && broadcaster.IsValid()) { event.reset(m_opaque_sp->PeekAtNextEventForBroadcaster(broadcaster.get())); return event.IsValid(); } - event.reset(NULL); + event.reset(nullptr); return false; } bool SBListener::PeekAtNextEventForBroadcasterWithType( const SBBroadcaster &broadcaster, uint32_t event_type_mask, SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, PeekAtNextEventForBroadcasterWithType, + (const lldb::SBBroadcaster &, uint32_t, lldb::SBEvent &), + 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(NULL); + event.reset(nullptr); return false; } bool SBListener::GetNextEvent(SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, GetNextEvent, (lldb::SBEvent &), event); + if (m_opaque_sp) { EventSP event_sp; if (m_opaque_sp->GetEvent(event_sp, std::chrono::seconds(0))) { @@ -262,12 +261,16 @@ return true; } } - event.reset(NULL); + event.reset(nullptr); return false; } bool SBListener::GetNextEventForBroadcaster(const SBBroadcaster &broadcaster, SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, GetNextEventForBroadcaster, + (const lldb::SBBroadcaster &, lldb::SBEvent &), + broadcaster, event); + if (m_opaque_sp && broadcaster.IsValid()) { EventSP event_sp; if (m_opaque_sp->GetEventForBroadcaster(broadcaster.get(), event_sp, @@ -276,13 +279,17 @@ return true; } } - event.reset(NULL); + event.reset(nullptr); return false; } bool SBListener::GetNextEventForBroadcasterWithType( const SBBroadcaster &broadcaster, uint32_t event_type_mask, SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, GetNextEventForBroadcasterWithType, + (const lldb::SBBroadcaster &, uint32_t, lldb::SBEvent &), + broadcaster, event_type_mask, event); + if (m_opaque_sp && broadcaster.IsValid()) { EventSP event_sp; if (m_opaque_sp->GetEventForBroadcasterWithType(broadcaster.get(), @@ -292,11 +299,14 @@ return true; } } - event.reset(NULL); + event.reset(nullptr); return false; } bool SBListener::HandleBroadcastEvent(const SBEvent &event) { + LLDB_RECORD_METHOD(bool, SBListener, HandleBroadcastEvent, + (const lldb::SBEvent &), event); + if (m_opaque_sp) return m_opaque_sp->HandleBroadcastEvent(event.GetSP()); return false; @@ -312,3 +322,52 @@ m_opaque_sp = listener_sp; m_unused_ptr = nullptr; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBListener>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBListener, ()); + LLDB_REGISTER_CONSTRUCTOR(SBListener, (const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBListener, (const lldb::SBListener &)); + LLDB_REGISTER_METHOD(const lldb::SBListener &, + SBListener, operator=,(const lldb::SBListener &)); + LLDB_REGISTER_METHOD_CONST(bool, SBListener, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBListener, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBListener, AddEvent, (const lldb::SBEvent &)); + LLDB_REGISTER_METHOD(void, SBListener, Clear, ()); + LLDB_REGISTER_METHOD(uint32_t, SBListener, StartListeningForEventClass, + (lldb::SBDebugger &, const char *, uint32_t)); + LLDB_REGISTER_METHOD(bool, SBListener, StopListeningForEventClass, + (lldb::SBDebugger &, const char *, uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBListener, StartListeningForEvents, + (const lldb::SBBroadcaster &, uint32_t)); + LLDB_REGISTER_METHOD(bool, SBListener, StopListeningForEvents, + (const lldb::SBBroadcaster &, uint32_t)); + LLDB_REGISTER_METHOD(bool, SBListener, WaitForEvent, + (uint32_t, lldb::SBEvent &)); + LLDB_REGISTER_METHOD( + bool, SBListener, WaitForEventForBroadcaster, + (uint32_t, const lldb::SBBroadcaster &, lldb::SBEvent &)); + LLDB_REGISTER_METHOD( + bool, SBListener, WaitForEventForBroadcasterWithType, + (uint32_t, const lldb::SBBroadcaster &, uint32_t, lldb::SBEvent &)); + LLDB_REGISTER_METHOD(bool, SBListener, PeekAtNextEvent, (lldb::SBEvent &)); + LLDB_REGISTER_METHOD(bool, SBListener, PeekAtNextEventForBroadcaster, + (const lldb::SBBroadcaster &, lldb::SBEvent &)); + LLDB_REGISTER_METHOD( + bool, SBListener, PeekAtNextEventForBroadcasterWithType, + (const lldb::SBBroadcaster &, uint32_t, lldb::SBEvent &)); + LLDB_REGISTER_METHOD(bool, SBListener, GetNextEvent, (lldb::SBEvent &)); + LLDB_REGISTER_METHOD(bool, SBListener, GetNextEventForBroadcaster, + (const lldb::SBBroadcaster &, lldb::SBEvent &)); + LLDB_REGISTER_METHOD( + bool, SBListener, GetNextEventForBroadcasterWithType, + (const lldb::SBBroadcaster &, uint32_t, lldb::SBEvent &)); + LLDB_REGISTER_METHOD(bool, SBListener, HandleBroadcastEvent, + (const lldb::SBEvent &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBMemoryRegionInfo.cpp b/src/llvm-project/lldb/source/API/SBMemoryRegionInfo.cpp index c4dbaec..d25570f 100644 --- a/src/llvm-project/lldb/source/API/SBMemoryRegionInfo.cpp +++ b/src/llvm-project/lldb/source/API/SBMemoryRegionInfo.cpp
@@ -1,13 +1,14 @@ //===-- SBMemoryRegionInfo.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBDefines.h" #include "lldb/API/SBError.h" #include "lldb/API/SBStream.h" @@ -17,82 +18,149 @@ using namespace lldb; using namespace lldb_private; -SBMemoryRegionInfo::SBMemoryRegionInfo() - : m_opaque_ap(new MemoryRegionInfo()) {} +SBMemoryRegionInfo::SBMemoryRegionInfo() : m_opaque_up(new MemoryRegionInfo()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBMemoryRegionInfo); +} SBMemoryRegionInfo::SBMemoryRegionInfo(const MemoryRegionInfo *lldb_object_ptr) - : m_opaque_ap(new MemoryRegionInfo()) { + : m_opaque_up(new MemoryRegionInfo()) { if (lldb_object_ptr) ref() = *lldb_object_ptr; } SBMemoryRegionInfo::SBMemoryRegionInfo(const SBMemoryRegionInfo &rhs) - : m_opaque_ap(new MemoryRegionInfo()) { - ref() = rhs.ref(); + : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBMemoryRegionInfo, + (const lldb::SBMemoryRegionInfo &), rhs); + m_opaque_up = clone(rhs.m_opaque_up); } const SBMemoryRegionInfo &SBMemoryRegionInfo:: operator=(const SBMemoryRegionInfo &rhs) { - if (this != &rhs) { - ref() = rhs.ref(); - } - return *this; + LLDB_RECORD_METHOD( + const lldb::SBMemoryRegionInfo &, + SBMemoryRegionInfo, operator=,(const lldb::SBMemoryRegionInfo &), rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } SBMemoryRegionInfo::~SBMemoryRegionInfo() {} -void SBMemoryRegionInfo::Clear() { m_opaque_ap->Clear(); } +void SBMemoryRegionInfo::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBMemoryRegionInfo, Clear); + + m_opaque_up->Clear(); +} bool SBMemoryRegionInfo::operator==(const SBMemoryRegionInfo &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBMemoryRegionInfo, operator==,(const lldb::SBMemoryRegionInfo &), + rhs); + return ref() == rhs.ref(); } bool SBMemoryRegionInfo::operator!=(const SBMemoryRegionInfo &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBMemoryRegionInfo, operator!=,(const lldb::SBMemoryRegionInfo &), + rhs); + return ref() != rhs.ref(); } -MemoryRegionInfo &SBMemoryRegionInfo::ref() { return *m_opaque_ap; } +MemoryRegionInfo &SBMemoryRegionInfo::ref() { return *m_opaque_up; } -const MemoryRegionInfo &SBMemoryRegionInfo::ref() const { return *m_opaque_ap; } +const MemoryRegionInfo &SBMemoryRegionInfo::ref() const { return *m_opaque_up; } lldb::addr_t SBMemoryRegionInfo::GetRegionBase() { - return m_opaque_ap->GetRange().GetRangeBase(); + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBMemoryRegionInfo, GetRegionBase); + + return m_opaque_up->GetRange().GetRangeBase(); } lldb::addr_t SBMemoryRegionInfo::GetRegionEnd() { - return m_opaque_ap->GetRange().GetRangeEnd(); + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBMemoryRegionInfo, GetRegionEnd); + + return m_opaque_up->GetRange().GetRangeEnd(); } bool SBMemoryRegionInfo::IsReadable() { - return m_opaque_ap->GetReadable() == MemoryRegionInfo::eYes; + LLDB_RECORD_METHOD_NO_ARGS(bool, SBMemoryRegionInfo, IsReadable); + + return m_opaque_up->GetReadable() == MemoryRegionInfo::eYes; } bool SBMemoryRegionInfo::IsWritable() { - return m_opaque_ap->GetWritable() == MemoryRegionInfo::eYes; + LLDB_RECORD_METHOD_NO_ARGS(bool, SBMemoryRegionInfo, IsWritable); + + return m_opaque_up->GetWritable() == MemoryRegionInfo::eYes; } bool SBMemoryRegionInfo::IsExecutable() { - return m_opaque_ap->GetExecutable() == MemoryRegionInfo::eYes; + LLDB_RECORD_METHOD_NO_ARGS(bool, SBMemoryRegionInfo, IsExecutable); + + return m_opaque_up->GetExecutable() == MemoryRegionInfo::eYes; } bool SBMemoryRegionInfo::IsMapped() { - return m_opaque_ap->GetMapped() == MemoryRegionInfo::eYes; + LLDB_RECORD_METHOD_NO_ARGS(bool, SBMemoryRegionInfo, IsMapped); + + return m_opaque_up->GetMapped() == MemoryRegionInfo::eYes; } const char *SBMemoryRegionInfo::GetName() { - return m_opaque_ap->GetName().AsCString(); + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBMemoryRegionInfo, GetName); + + return m_opaque_up->GetName().AsCString(); } bool SBMemoryRegionInfo::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBMemoryRegionInfo, GetDescription, + (lldb::SBStream &), description); + Stream &strm = description.ref(); - const addr_t load_addr = m_opaque_ap->GetRange().base; + 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_ap->GetRange().size); - strm.Printf(m_opaque_ap->GetReadable() ? "R" : "-"); - strm.Printf(m_opaque_ap->GetWritable() ? "W" : "-"); - strm.Printf(m_opaque_ap->GetExecutable() ? "X" : "-"); + 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; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBMemoryRegionInfo>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBMemoryRegionInfo, ()); + LLDB_REGISTER_CONSTRUCTOR(SBMemoryRegionInfo, + (const lldb::SBMemoryRegionInfo &)); + LLDB_REGISTER_METHOD( + const lldb::SBMemoryRegionInfo &, + SBMemoryRegionInfo, operator=,(const lldb::SBMemoryRegionInfo &)); + LLDB_REGISTER_METHOD(void, SBMemoryRegionInfo, Clear, ()); + LLDB_REGISTER_METHOD_CONST( + bool, + SBMemoryRegionInfo, operator==,(const lldb::SBMemoryRegionInfo &)); + LLDB_REGISTER_METHOD_CONST( + bool, + SBMemoryRegionInfo, operator!=,(const lldb::SBMemoryRegionInfo &)); + LLDB_REGISTER_METHOD(lldb::addr_t, SBMemoryRegionInfo, GetRegionBase, ()); + LLDB_REGISTER_METHOD(lldb::addr_t, SBMemoryRegionInfo, GetRegionEnd, ()); + LLDB_REGISTER_METHOD(bool, SBMemoryRegionInfo, IsReadable, ()); + LLDB_REGISTER_METHOD(bool, SBMemoryRegionInfo, IsWritable, ()); + LLDB_REGISTER_METHOD(bool, SBMemoryRegionInfo, IsExecutable, ()); + LLDB_REGISTER_METHOD(bool, SBMemoryRegionInfo, IsMapped, ()); + LLDB_REGISTER_METHOD(const char *, SBMemoryRegionInfo, GetName, ()); + LLDB_REGISTER_METHOD(bool, SBMemoryRegionInfo, GetDescription, + (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBMemoryRegionInfoList.cpp b/src/llvm-project/lldb/source/API/SBMemoryRegionInfoList.cpp index 1cefc9d..32a3afb 100644 --- a/src/llvm-project/lldb/source/API/SBMemoryRegionInfoList.cpp +++ b/src/llvm-project/lldb/source/API/SBMemoryRegionInfoList.cpp
@@ -1,17 +1,16 @@ //===-- SBMemoryRegionInfoList.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBMemoryRegionInfo.h" #include "lldb/API/SBStream.h" #include "lldb/Target/MemoryRegionInfo.h" -#include "lldb/Utility/Log.h" #include <vector> @@ -65,69 +64,103 @@ MemoryRegionInfos m_regions; }; -MemoryRegionInfos &SBMemoryRegionInfoList::ref() { - return m_opaque_ap->Ref(); -} +MemoryRegionInfos &SBMemoryRegionInfoList::ref() { return m_opaque_up->Ref(); } const MemoryRegionInfos &SBMemoryRegionInfoList::ref() const { - return m_opaque_ap->Ref(); + return m_opaque_up->Ref(); } SBMemoryRegionInfoList::SBMemoryRegionInfoList() - : m_opaque_ap(new MemoryRegionInfoListImpl()) {} + : m_opaque_up(new MemoryRegionInfoListImpl()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBMemoryRegionInfoList); +} SBMemoryRegionInfoList::SBMemoryRegionInfoList( const SBMemoryRegionInfoList &rhs) - : m_opaque_ap(new MemoryRegionInfoListImpl(*rhs.m_opaque_ap)) {} + : m_opaque_up(new MemoryRegionInfoListImpl(*rhs.m_opaque_up)) { + LLDB_RECORD_CONSTRUCTOR(SBMemoryRegionInfoList, + (const lldb::SBMemoryRegionInfoList &), rhs); +} SBMemoryRegionInfoList::~SBMemoryRegionInfoList() {} const SBMemoryRegionInfoList &SBMemoryRegionInfoList:: operator=(const SBMemoryRegionInfoList &rhs) { + LLDB_RECORD_METHOD( + const lldb::SBMemoryRegionInfoList &, + SBMemoryRegionInfoList, operator=,(const lldb::SBMemoryRegionInfoList &), + rhs); + if (this != &rhs) { - *m_opaque_ap = *rhs.m_opaque_ap; + *m_opaque_up = *rhs.m_opaque_up; } - return *this; + return LLDB_RECORD_RESULT(*this); } uint32_t SBMemoryRegionInfoList::GetSize() const { - return m_opaque_ap->GetSize(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBMemoryRegionInfoList, GetSize); + + return m_opaque_up->GetSize(); } bool SBMemoryRegionInfoList::GetMemoryRegionAtIndex( uint32_t idx, SBMemoryRegionInfo ®ion_info) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBMemoryRegionInfoList, GetMemoryRegionAtIndex, + (uint32_t, lldb::SBMemoryRegionInfo &), idx, region_info); - bool result = m_opaque_ap->GetMemoryRegionInfoAtIndex(idx, region_info.ref()); - - if (log) { - SBStream sstr; - region_info.GetDescription(sstr); - log->Printf("SBMemoryRegionInfoList::GetMemoryRegionAtIndex (this.ap=%p, " - "idx=%d) => SBMemoryRegionInfo (this.ap=%p, '%s')", - static_cast<void *>(m_opaque_ap.get()), idx, - static_cast<void *>(region_info.m_opaque_ap.get()), - sstr.GetData()); - } - - return result; + return m_opaque_up->GetMemoryRegionInfoAtIndex(idx, region_info.ref()); } -void SBMemoryRegionInfoList::Clear() { m_opaque_ap->Clear(); } +void SBMemoryRegionInfoList::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBMemoryRegionInfoList, Clear); + + m_opaque_up->Clear(); +} void SBMemoryRegionInfoList::Append(SBMemoryRegionInfo &sb_region) { - m_opaque_ap->Append(sb_region.ref()); + LLDB_RECORD_METHOD(void, SBMemoryRegionInfoList, Append, + (lldb::SBMemoryRegionInfo &), sb_region); + + m_opaque_up->Append(sb_region.ref()); } void SBMemoryRegionInfoList::Append(SBMemoryRegionInfoList &sb_region_list) { - m_opaque_ap->Append(*sb_region_list); + LLDB_RECORD_METHOD(void, SBMemoryRegionInfoList, Append, + (lldb::SBMemoryRegionInfoList &), sb_region_list); + + m_opaque_up->Append(*sb_region_list); } const MemoryRegionInfoListImpl *SBMemoryRegionInfoList::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const MemoryRegionInfoListImpl &SBMemoryRegionInfoList::operator*() const { - assert(m_opaque_ap.get()); - return *m_opaque_ap; + assert(m_opaque_up.get()); + return *m_opaque_up; +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBMemoryRegionInfoList>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBMemoryRegionInfoList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBMemoryRegionInfoList, + (const lldb::SBMemoryRegionInfoList &)); + LLDB_REGISTER_METHOD( + const lldb::SBMemoryRegionInfoList &, + SBMemoryRegionInfoList, operator=,( + const lldb::SBMemoryRegionInfoList &)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBMemoryRegionInfoList, GetSize, ()); + LLDB_REGISTER_METHOD(bool, SBMemoryRegionInfoList, GetMemoryRegionAtIndex, + (uint32_t, lldb::SBMemoryRegionInfo &)); + LLDB_REGISTER_METHOD(void, SBMemoryRegionInfoList, Clear, ()); + LLDB_REGISTER_METHOD(void, SBMemoryRegionInfoList, Append, + (lldb::SBMemoryRegionInfo &)); + LLDB_REGISTER_METHOD(void, SBMemoryRegionInfoList, Append, + (lldb::SBMemoryRegionInfoList &)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBModule.cpp b/src/llvm-project/lldb/source/API/SBModule.cpp index 3198079..4bd32bc 100644 --- a/src/llvm-project/lldb/source/API/SBModule.cpp +++ b/src/llvm-project/lldb/source/API/SBModule.cpp
@@ -1,13 +1,13 @@ //===-- SBModule.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBModuleSpec.h" @@ -25,28 +25,36 @@ #include "lldb/Symbol/TypeSystem.h" #include "lldb/Symbol/VariableList.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" using namespace lldb; using namespace lldb_private; -SBModule::SBModule() : m_opaque_sp() {} +SBModule::SBModule() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBModule); +} SBModule::SBModule(const lldb::ModuleSP &module_sp) : m_opaque_sp(module_sp) {} SBModule::SBModule(const SBModuleSpec &module_spec) : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR(SBModule, (const lldb::SBModuleSpec &), module_spec); + ModuleSP module_sp; - Status error = ModuleList::GetSharedModule(*module_spec.m_opaque_ap, - module_sp, NULL, NULL, NULL); + 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) {} +SBModule::SBModule(const SBModule &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBModule, (const lldb::SBModule &), rhs); +} SBModule::SBModule(lldb::SBProcess &process, lldb::addr_t header_addr) : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR(SBModule, (lldb::SBProcess &, lldb::addr_t), process, + header_addr); + ProcessSP process_sp(process.GetSP()); if (process_sp) { m_opaque_sp = process_sp->ReadModuleFromMemory(FileSpec(), header_addr); @@ -60,52 +68,61 @@ } const SBModule &SBModule::operator=(const SBModule &rhs) { + LLDB_RECORD_METHOD(const lldb::SBModule &, + SBModule, operator=,(const lldb::SBModule &), rhs); + if (this != &rhs) m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBModule::~SBModule() {} -bool SBModule::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBModule::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBModule, IsValid); + return this->operator bool(); +} +SBModule::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBModule, operator bool); -void SBModule::Clear() { m_opaque_sp.reset(); } + return m_opaque_sp.get() != nullptr; +} + +void SBModule::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBModule, Clear); + + m_opaque_sp.reset(); +} SBFileSpec SBModule::GetFileSpec() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBModule, GetFileSpec); SBFileSpec file_spec; ModuleSP module_sp(GetSP()); if (module_sp) file_spec.SetFileSpec(module_sp->GetFileSpec()); - if (log) - log->Printf("SBModule(%p)::GetFileSpec () => SBFileSpec(%p)", - static_cast<void *>(module_sp.get()), - static_cast<const void *>(file_spec.get())); - - return file_spec; + return LLDB_RECORD_RESULT(file_spec); } lldb::SBFileSpec SBModule::GetPlatformFileSpec() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBModule, + GetPlatformFileSpec); + SBFileSpec file_spec; ModuleSP module_sp(GetSP()); if (module_sp) file_spec.SetFileSpec(module_sp->GetPlatformFileSpec()); - if (log) - log->Printf("SBModule(%p)::GetPlatformFileSpec () => SBFileSpec(%p)", - static_cast<void *>(module_sp.get()), - static_cast<const void *>(file_spec.get())); - - return file_spec; + return LLDB_RECORD_RESULT(file_spec); } bool SBModule::SetPlatformFileSpec(const lldb::SBFileSpec &platform_file) { + LLDB_RECORD_METHOD(bool, SBModule, SetPlatformFileSpec, + (const lldb::SBFileSpec &), platform_file); + bool result = false; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); ModuleSP module_sp(GetSP()); if (module_sp) { @@ -113,23 +130,24 @@ result = true; } - if (log) - log->Printf("SBModule(%p)::SetPlatformFileSpec (SBFileSpec(%p (%s)) => %i", - static_cast<void *>(module_sp.get()), - static_cast<const void *>(platform_file.get()), - platform_file->GetPath().c_str(), result); return result; } lldb::SBFileSpec SBModule::GetRemoteInstallFileSpec() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFileSpec, SBModule, + GetRemoteInstallFileSpec); + SBFileSpec sb_file_spec; ModuleSP module_sp(GetSP()); if (module_sp) sb_file_spec.SetFileSpec(module_sp->GetRemoteInstallFileSpec()); - return sb_file_spec; + return LLDB_RECORD_RESULT(sb_file_spec); } bool SBModule::SetRemoteInstallFileSpec(lldb::SBFileSpec &file) { + LLDB_RECORD_METHOD(bool, SBModule, SetRemoteInstallFileSpec, + (lldb::SBFileSpec &), file); + ModuleSP module_sp(GetSP()); if (module_sp) { module_sp->SetRemoteInstallFileSpec(file.ref()); @@ -139,30 +157,20 @@ } const uint8_t *SBModule::GetUUIDBytes() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(const uint8_t *, SBModule, GetUUIDBytes); - const uint8_t *uuid_bytes = NULL; + const uint8_t *uuid_bytes = nullptr; ModuleSP module_sp(GetSP()); if (module_sp) uuid_bytes = module_sp->GetUUID().GetBytes().data(); - if (log) { - if (uuid_bytes) { - StreamString s; - module_sp->GetUUID().Dump(&s); - log->Printf("SBModule(%p)::GetUUIDBytes () => %s", - static_cast<void *>(module_sp.get()), s.GetData()); - } else - log->Printf("SBModule(%p)::GetUUIDBytes () => NULL", - static_cast<void *>(module_sp.get())); - } return uuid_bytes; } const char *SBModule::GetUUIDString() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBModule, GetUUIDString); - const char *uuid_cstr = NULL; + const char *uuid_cstr = nullptr; ModuleSP module_sp(GetSP()); if (module_sp) { // We are going to return a "const char *" value through the public API, so @@ -173,25 +181,25 @@ } if (uuid_cstr && uuid_cstr[0]) { - if (log) - log->Printf("SBModule(%p)::GetUUIDString () => %s", - static_cast<void *>(module_sp.get()), uuid_cstr); return uuid_cstr; } - if (log) - log->Printf("SBModule(%p)::GetUUIDString () => NULL", - static_cast<void *>(module_sp.get())); - return NULL; + return nullptr; } bool SBModule::operator==(const SBModule &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBModule, operator==,(const lldb::SBModule &), + 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_RECORD_METHOD_CONST(bool, SBModule, operator!=,(const lldb::SBModule &), + rhs); + if (m_opaque_sp) return m_opaque_sp.get() != rhs.m_opaque_sp.get(); return false; @@ -202,6 +210,9 @@ void SBModule::SetSP(const ModuleSP &module_sp) { m_opaque_sp = module_sp; } SBAddress SBModule::ResolveFileAddress(lldb::addr_t vm_addr) { + LLDB_RECORD_METHOD(lldb::SBAddress, SBModule, ResolveFileAddress, + (lldb::addr_t), vm_addr); + lldb::SBAddress sb_addr; ModuleSP module_sp(GetSP()); if (module_sp) { @@ -209,21 +220,28 @@ if (module_sp->ResolveFileAddress(vm_addr, addr)) sb_addr.ref() = addr; } - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); } SBSymbolContext SBModule::ResolveSymbolContextForAddress(const SBAddress &addr, uint32_t resolve_scope) { + LLDB_RECORD_METHOD(lldb::SBSymbolContext, SBModule, + ResolveSymbolContextForAddress, + (const lldb::SBAddress &, uint32_t), 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; + return LLDB_RECORD_RESULT(sb_sc); } bool SBModule::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBModule, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); ModuleSP module_sp(GetSP()); @@ -236,6 +254,8 @@ } uint32_t SBModule::GetNumCompileUnits() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBModule, GetNumCompileUnits); + ModuleSP module_sp(GetSP()); if (module_sp) { return module_sp->GetNumCompileUnits(); @@ -244,24 +264,29 @@ } SBCompileUnit SBModule::GetCompileUnitAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBCompileUnit, SBModule, GetCompileUnitAtIndex, + (uint32_t), 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; + return LLDB_RECORD_RESULT(sb_cu); } -SBSymbolContextList -SBModule::FindCompileUnits(const SBFileSpec &sb_file_spec) { +SBSymbolContextList SBModule::FindCompileUnits(const SBFileSpec &sb_file_spec) { + LLDB_RECORD_METHOD(lldb::SBSymbolContextList, SBModule, FindCompileUnits, + (const lldb::SBFileSpec &), sb_file_spec); + SBSymbolContextList sb_sc_list; const ModuleSP module_sp(GetSP()); if (sb_file_spec.IsValid() && module_sp) { const bool append = true; module_sp->FindCompileUnits(*sb_file_spec, append, *sb_sc_list); } - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); } static Symtab *GetUnifiedSymbolTable(const lldb::ModuleSP &module_sp) { @@ -270,10 +295,12 @@ if (symbols) return symbols->GetSymtab(); } - return NULL; + return nullptr; } size_t SBModule::GetNumSymbols() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBModule, GetNumSymbols); + ModuleSP module_sp(GetSP()); if (module_sp) { Symtab *symtab = GetUnifiedSymbolTable(module_sp); @@ -284,16 +311,21 @@ } SBSymbol SBModule::GetSymbolAtIndex(size_t idx) { + LLDB_RECORD_METHOD(lldb::SBSymbol, SBModule, GetSymbolAtIndex, (size_t), idx); + SBSymbol sb_symbol; ModuleSP module_sp(GetSP()); Symtab *symtab = GetUnifiedSymbolTable(module_sp); if (symtab) sb_symbol.SetSymbol(symtab->SymbolAtIndex(idx)); - return sb_symbol; + return LLDB_RECORD_RESULT(sb_symbol); } lldb::SBSymbol SBModule::FindSymbol(const char *name, lldb::SymbolType symbol_type) { + LLDB_RECORD_METHOD(lldb::SBSymbol, SBModule, FindSymbol, + (const char *, lldb::SymbolType), name, symbol_type); + SBSymbol sb_symbol; if (name && name[0]) { ModuleSP module_sp(GetSP()); @@ -303,11 +335,14 @@ ConstString(name), symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny)); } - return sb_symbol; + return LLDB_RECORD_RESULT(sb_symbol); } lldb::SBSymbolContextList SBModule::FindSymbols(const char *name, lldb::SymbolType symbol_type) { + LLDB_RECORD_METHOD(lldb::SBSymbolContextList, SBModule, FindSymbols, + (const char *, lldb::SymbolType), name, symbol_type); + SBSymbolContextList sb_sc_list; if (name && name[0]) { ModuleSP module_sp(GetSP()); @@ -328,10 +363,12 @@ } } } - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); } size_t SBModule::GetNumSections() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBModule, GetNumSections); + ModuleSP module_sp(GetSP()); if (module_sp) { // Give the symbol vendor a chance to add to the unified section list. @@ -344,6 +381,9 @@ } SBSection SBModule::GetSectionAtIndex(size_t idx) { + LLDB_RECORD_METHOD(lldb::SBSection, SBModule, GetSectionAtIndex, (size_t), + idx); + SBSection sb_section; ModuleSP module_sp(GetSP()); if (module_sp) { @@ -354,11 +394,14 @@ if (section_list) sb_section.SetSP(section_list->GetSectionAtIndex(idx)); } - return sb_section; + return LLDB_RECORD_RESULT(sb_section); } lldb::SBSymbolContextList SBModule::FindFunctions(const char *name, uint32_t name_type_mask) { + LLDB_RECORD_METHOD(lldb::SBSymbolContextList, SBModule, FindFunctions, + (const char *, uint32_t), name, name_type_mask); + lldb::SBSymbolContextList sb_sc_list; ModuleSP module_sp(GetSP()); if (name && module_sp) { @@ -366,20 +409,24 @@ const bool symbols_ok = true; const bool inlines_ok = true; FunctionNameType type = static_cast<FunctionNameType>(name_type_mask); - module_sp->FindFunctions(ConstString(name), NULL, type, symbols_ok, + module_sp->FindFunctions(ConstString(name), nullptr, type, symbols_ok, inlines_ok, append, *sb_sc_list); } - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); } SBValueList SBModule::FindGlobalVariables(SBTarget &target, const char *name, uint32_t max_matches) { + LLDB_RECORD_METHOD(lldb::SBValueList, SBModule, FindGlobalVariables, + (lldb::SBTarget &, const char *, uint32_t), target, name, + max_matches); + SBValueList sb_value_list; ModuleSP module_sp(GetSP()); if (name && module_sp) { VariableList variable_list; const uint32_t match_count = module_sp->FindGlobalVariables( - ConstString(name), NULL, max_matches, variable_list); + ConstString(name), nullptr, max_matches, variable_list); if (match_count > 0) { for (uint32_t i = 0; i < match_count; ++i) { @@ -393,18 +440,24 @@ } } - return sb_value_list; + return LLDB_RECORD_RESULT(sb_value_list); } lldb::SBValue SBModule::FindFirstGlobalVariable(lldb::SBTarget &target, const char *name) { + LLDB_RECORD_METHOD(lldb::SBValue, SBModule, FindFirstGlobalVariable, + (lldb::SBTarget &, const char *), 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(); + return LLDB_RECORD_RESULT(sb_value_list.GetValueAtIndex(0)); + return LLDB_RECORD_RESULT(SBValue()); } lldb::SBType SBModule::FindFirstType(const char *name_cstr) { + LLDB_RECORD_METHOD(lldb::SBType, SBModule, FindFirstType, (const char *), + name_cstr); + SBType sb_type; ModuleSP module_sp(GetSP()); if (name_cstr && module_sp) { @@ -421,21 +474,27 @@ sb_type = SBType(type_system->GetBuiltinTypeByName(name)); } } - return sb_type; + return LLDB_RECORD_RESULT(sb_type); } lldb::SBType SBModule::GetBasicType(lldb::BasicType type) { + LLDB_RECORD_METHOD(lldb::SBType, SBModule, GetBasicType, (lldb::BasicType), + type); + ModuleSP module_sp(GetSP()); if (module_sp) { TypeSystem *type_system = module_sp->GetTypeSystemForLanguage(eLanguageTypeC); if (type_system) - return SBType(type_system->GetBasicTypeFromAST(type)); + return LLDB_RECORD_RESULT(SBType(type_system->GetBasicTypeFromAST(type))); } - return SBType(); + return LLDB_RECORD_RESULT(SBType()); } lldb::SBTypeList SBModule::FindTypes(const char *type) { + LLDB_RECORD_METHOD(lldb::SBTypeList, SBModule, FindTypes, (const char *), + type); + SBTypeList retval; ModuleSP module_sp(GetSP()); @@ -464,40 +523,49 @@ } } - return retval; + return LLDB_RECORD_RESULT(retval); } lldb::SBType SBModule::GetTypeByID(lldb::user_id_t uid) { + LLDB_RECORD_METHOD(lldb::SBType, SBModule, GetTypeByID, (lldb::user_id_t), + uid); + ModuleSP module_sp(GetSP()); if (module_sp) { SymbolVendor *vendor = module_sp->GetSymbolVendor(); if (vendor) { Type *type_ptr = vendor->ResolveTypeUID(uid); if (type_ptr) - return SBType(type_ptr->shared_from_this()); + return LLDB_RECORD_RESULT(SBType(type_ptr->shared_from_this())); } } - return SBType(); + return LLDB_RECORD_RESULT(SBType()); } lldb::SBTypeList SBModule::GetTypes(uint32_t type_mask) { + LLDB_RECORD_METHOD(lldb::SBTypeList, SBModule, GetTypes, (uint32_t), + type_mask); + SBTypeList sb_type_list; ModuleSP module_sp(GetSP()); if (!module_sp) - return sb_type_list; + return LLDB_RECORD_RESULT(sb_type_list); SymbolVendor *vendor = module_sp->GetSymbolVendor(); if (!vendor) - return sb_type_list; + return LLDB_RECORD_RESULT(sb_type_list); TypeClass type_class = static_cast<TypeClass>(type_mask); TypeList type_list; - vendor->GetTypes(NULL, type_class, type_list); - sb_type_list.m_opaque_ap->Append(type_list); - return sb_type_list; + vendor->GetTypes(nullptr, type_class, type_list); + sb_type_list.m_opaque_up->Append(type_list); + return LLDB_RECORD_RESULT(sb_type_list); } SBSection SBModule::FindSection(const char *sect_name) { + LLDB_RECORD_METHOD(lldb::SBSection, SBModule, FindSection, (const char *), + sect_name); + SBSection sb_section; ModuleSP module_sp(GetSP()); @@ -513,10 +581,12 @@ } } } - return sb_section; + return LLDB_RECORD_RESULT(sb_section); } lldb::ByteOrder SBModule::GetByteOrder() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::ByteOrder, SBModule, GetByteOrder); + ModuleSP module_sp(GetSP()); if (module_sp) return module_sp->GetArchitecture().GetByteOrder(); @@ -524,6 +594,8 @@ } const char *SBModule::GetTriple() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBModule, GetTriple); + ModuleSP module_sp(GetSP()); if (module_sp) { std::string triple(module_sp->GetArchitecture().GetTriple().str()); @@ -533,10 +605,12 @@ ConstString const_triple(triple.c_str()); return const_triple.GetCString(); } - return NULL; + return nullptr; } uint32_t SBModule::GetAddressByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBModule, GetAddressByteSize); + ModuleSP module_sp(GetSP()); if (module_sp) return module_sp->GetArchitecture().GetAddressByteSize(); @@ -544,6 +618,9 @@ } uint32_t SBModule::GetVersion(uint32_t *versions, uint32_t num_versions) { + LLDB_RECORD_METHOD(uint32_t, SBModule, GetVersion, (uint32_t *, uint32_t), + versions, num_versions); + llvm::VersionTuple version; if (ModuleSP module_sp = GetSP()) version = module_sp->GetVersion(); @@ -570,6 +647,9 @@ } lldb::SBFileSpec SBModule::GetSymbolFileSpec() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBModule, + GetSymbolFileSpec); + lldb::SBFileSpec sb_file_spec; ModuleSP module_sp(GetSP()); if (module_sp) { @@ -577,10 +657,13 @@ if (symbol_vendor_ptr) sb_file_spec.SetFileSpec(symbol_vendor_ptr->GetMainFileSpec()); } - return sb_file_spec; + return LLDB_RECORD_RESULT(sb_file_spec); } lldb::SBAddress SBModule::GetObjectFileHeaderAddress() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBModule, + GetObjectFileHeaderAddress); + lldb::SBAddress sb_addr; ModuleSP module_sp(GetSP()); if (module_sp) { @@ -588,10 +671,13 @@ if (objfile_ptr) sb_addr.ref() = objfile_ptr->GetBaseAddress(); } - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); } lldb::SBAddress SBModule::GetObjectFileEntryPointAddress() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBModule, + GetObjectFileEntryPointAddress); + lldb::SBAddress sb_addr; ModuleSP module_sp(GetSP()); if (module_sp) { @@ -599,5 +685,84 @@ if (objfile_ptr) sb_addr.ref() = objfile_ptr->GetEntryPointAddress(); } - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBModule>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBModule, ()); + LLDB_REGISTER_CONSTRUCTOR(SBModule, (const lldb::SBModuleSpec &)); + LLDB_REGISTER_CONSTRUCTOR(SBModule, (const lldb::SBModule &)); + LLDB_REGISTER_CONSTRUCTOR(SBModule, (lldb::SBProcess &, lldb::addr_t)); + LLDB_REGISTER_METHOD(const lldb::SBModule &, + SBModule, operator=,(const lldb::SBModule &)); + LLDB_REGISTER_METHOD_CONST(bool, SBModule, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBModule, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBModule, Clear, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBModule, GetFileSpec, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBModule, GetPlatformFileSpec, + ()); + LLDB_REGISTER_METHOD(bool, SBModule, SetPlatformFileSpec, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBFileSpec, SBModule, GetRemoteInstallFileSpec, + ()); + LLDB_REGISTER_METHOD(bool, SBModule, SetRemoteInstallFileSpec, + (lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD_CONST(const char *, SBModule, GetUUIDString, ()); + LLDB_REGISTER_METHOD_CONST(bool, + SBModule, operator==,(const lldb::SBModule &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBModule, operator!=,(const lldb::SBModule &)); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBModule, ResolveFileAddress, + (lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContext, SBModule, + ResolveSymbolContextForAddress, + (const lldb::SBAddress &, uint32_t)); + LLDB_REGISTER_METHOD(bool, SBModule, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(uint32_t, SBModule, GetNumCompileUnits, ()); + LLDB_REGISTER_METHOD(lldb::SBCompileUnit, SBModule, GetCompileUnitAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContextList, SBModule, FindCompileUnits, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(size_t, SBModule, GetNumSymbols, ()); + LLDB_REGISTER_METHOD(lldb::SBSymbol, SBModule, GetSymbolAtIndex, (size_t)); + LLDB_REGISTER_METHOD(lldb::SBSymbol, SBModule, FindSymbol, + (const char *, lldb::SymbolType)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContextList, SBModule, FindSymbols, + (const char *, lldb::SymbolType)); + LLDB_REGISTER_METHOD(size_t, SBModule, GetNumSections, ()); + LLDB_REGISTER_METHOD(lldb::SBSection, SBModule, GetSectionAtIndex, + (size_t)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContextList, SBModule, FindFunctions, + (const char *, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBModule, FindGlobalVariables, + (lldb::SBTarget &, const char *, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBModule, FindFirstGlobalVariable, + (lldb::SBTarget &, const char *)); + LLDB_REGISTER_METHOD(lldb::SBType, SBModule, FindFirstType, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBType, SBModule, GetBasicType, + (lldb::BasicType)); + LLDB_REGISTER_METHOD(lldb::SBTypeList, SBModule, FindTypes, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBType, SBModule, GetTypeByID, + (lldb::user_id_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeList, SBModule, GetTypes, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBSection, SBModule, FindSection, + (const char *)); + LLDB_REGISTER_METHOD(lldb::ByteOrder, SBModule, GetByteOrder, ()); + LLDB_REGISTER_METHOD(const char *, SBModule, GetTriple, ()); + LLDB_REGISTER_METHOD(uint32_t, SBModule, GetAddressByteSize, ()); + LLDB_REGISTER_METHOD(uint32_t, SBModule, GetVersion, + (uint32_t *, uint32_t)); + LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBModule, GetSymbolFileSpec, + ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBModule, + GetObjectFileHeaderAddress, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBModule, + GetObjectFileEntryPointAddress, ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBModuleSpec.cpp b/src/llvm-project/lldb/source/API/SBModuleSpec.cpp index 65492f5..a5e9ad2 100644 --- a/src/llvm-project/lldb/source/API/SBModuleSpec.cpp +++ b/src/llvm-project/lldb/source/API/SBModuleSpec.cpp
@@ -1,13 +1,14 @@ //===-- SBModuleSpec.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBStream.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" @@ -18,58 +19,100 @@ using namespace lldb; using namespace lldb_private; -SBModuleSpec::SBModuleSpec() : m_opaque_ap(new lldb_private::ModuleSpec()) {} +SBModuleSpec::SBModuleSpec() : m_opaque_up(new lldb_private::ModuleSpec()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBModuleSpec); +} -SBModuleSpec::SBModuleSpec(const SBModuleSpec &rhs) - : m_opaque_ap(new lldb_private::ModuleSpec(*rhs.m_opaque_ap)) {} +SBModuleSpec::SBModuleSpec(const SBModuleSpec &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBModuleSpec, (const lldb::SBModuleSpec &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} const SBModuleSpec &SBModuleSpec::operator=(const SBModuleSpec &rhs) { + LLDB_RECORD_METHOD(const lldb::SBModuleSpec &, + SBModuleSpec, operator=,(const lldb::SBModuleSpec &), rhs); + if (this != &rhs) - *m_opaque_ap = *(rhs.m_opaque_ap); - return *this; + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } SBModuleSpec::~SBModuleSpec() {} -bool SBModuleSpec::IsValid() const { return m_opaque_ap->operator bool(); } +bool SBModuleSpec::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBModuleSpec, IsValid); + return this->operator bool(); +} +SBModuleSpec::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBModuleSpec, operator bool); -void SBModuleSpec::Clear() { m_opaque_ap->Clear(); } + return m_opaque_up->operator bool(); +} + +void SBModuleSpec::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBModuleSpec, Clear); + + m_opaque_up->Clear(); +} SBFileSpec SBModuleSpec::GetFileSpec() { - SBFileSpec sb_spec(m_opaque_ap->GetFileSpec()); - return sb_spec; + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFileSpec, SBModuleSpec, GetFileSpec); + + SBFileSpec sb_spec(m_opaque_up->GetFileSpec()); + return LLDB_RECORD_RESULT(sb_spec); } void SBModuleSpec::SetFileSpec(const lldb::SBFileSpec &sb_spec) { - m_opaque_ap->GetFileSpec() = *sb_spec; + LLDB_RECORD_METHOD(void, SBModuleSpec, SetFileSpec, + (const lldb::SBFileSpec &), sb_spec); + + m_opaque_up->GetFileSpec() = *sb_spec; } lldb::SBFileSpec SBModuleSpec::GetPlatformFileSpec() { - return SBFileSpec(m_opaque_ap->GetPlatformFileSpec()); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFileSpec, SBModuleSpec, + GetPlatformFileSpec); + + return LLDB_RECORD_RESULT(SBFileSpec(m_opaque_up->GetPlatformFileSpec())); } void SBModuleSpec::SetPlatformFileSpec(const lldb::SBFileSpec &sb_spec) { - m_opaque_ap->GetPlatformFileSpec() = *sb_spec; + LLDB_RECORD_METHOD(void, SBModuleSpec, SetPlatformFileSpec, + (const lldb::SBFileSpec &), sb_spec); + + m_opaque_up->GetPlatformFileSpec() = *sb_spec; } lldb::SBFileSpec SBModuleSpec::GetSymbolFileSpec() { - return SBFileSpec(m_opaque_ap->GetSymbolFileSpec()); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFileSpec, SBModuleSpec, GetSymbolFileSpec); + + return LLDB_RECORD_RESULT(SBFileSpec(m_opaque_up->GetSymbolFileSpec())); } void SBModuleSpec::SetSymbolFileSpec(const lldb::SBFileSpec &sb_spec) { - m_opaque_ap->GetSymbolFileSpec() = *sb_spec; + LLDB_RECORD_METHOD(void, SBModuleSpec, SetSymbolFileSpec, + (const lldb::SBFileSpec &), sb_spec); + + m_opaque_up->GetSymbolFileSpec() = *sb_spec; } const char *SBModuleSpec::GetObjectName() { - return m_opaque_ap->GetObjectName().GetCString(); + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBModuleSpec, GetObjectName); + + return m_opaque_up->GetObjectName().GetCString(); } void SBModuleSpec::SetObjectName(const char *name) { - m_opaque_ap->GetObjectName().SetCString(name); + LLDB_RECORD_METHOD(void, SBModuleSpec, SetObjectName, (const char *), name); + + m_opaque_up->GetObjectName().SetCString(name); } const char *SBModuleSpec::GetTriple() { - std::string triple(m_opaque_ap->GetArchitecture().GetTriple().str()); + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBModuleSpec, GetTriple); + + 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 @@ -78,82 +121,180 @@ } void SBModuleSpec::SetTriple(const char *triple) { - m_opaque_ap->GetArchitecture().SetTriple(triple); + LLDB_RECORD_METHOD(void, SBModuleSpec, SetTriple, (const char *), triple); + + m_opaque_up->GetArchitecture().SetTriple(triple); } const uint8_t *SBModuleSpec::GetUUIDBytes() { - return m_opaque_ap->GetUUID().GetBytes().data(); + return m_opaque_up->GetUUID().GetBytes().data(); } size_t SBModuleSpec::GetUUIDLength() { - return m_opaque_ap->GetUUID().GetBytes().size(); + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBModuleSpec, GetUUIDLength); + + return m_opaque_up->GetUUID().GetBytes().size(); } bool SBModuleSpec::SetUUIDBytes(const uint8_t *uuid, size_t uuid_len) { - m_opaque_ap->GetUUID() = UUID::fromOptionalData(uuid, uuid_len); - return m_opaque_ap->GetUUID().IsValid(); + m_opaque_up->GetUUID() = UUID::fromOptionalData(uuid, uuid_len); + return m_opaque_up->GetUUID().IsValid(); } bool SBModuleSpec::GetDescription(lldb::SBStream &description) { - m_opaque_ap->Dump(description.ref()); + LLDB_RECORD_METHOD(bool, SBModuleSpec, GetDescription, (lldb::SBStream &), + description); + + m_opaque_up->Dump(description.ref()); return true; } -SBModuleSpecList::SBModuleSpecList() : m_opaque_ap(new ModuleSpecList()) {} +SBModuleSpecList::SBModuleSpecList() : m_opaque_up(new ModuleSpecList()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBModuleSpecList); +} SBModuleSpecList::SBModuleSpecList(const SBModuleSpecList &rhs) - : m_opaque_ap(new ModuleSpecList(*rhs.m_opaque_ap)) {} + : m_opaque_up(new ModuleSpecList(*rhs.m_opaque_up)) { + LLDB_RECORD_CONSTRUCTOR(SBModuleSpecList, (const lldb::SBModuleSpecList &), + rhs); +} SBModuleSpecList &SBModuleSpecList::operator=(const SBModuleSpecList &rhs) { + LLDB_RECORD_METHOD( + lldb::SBModuleSpecList &, + SBModuleSpecList, operator=,(const lldb::SBModuleSpecList &), rhs); + if (this != &rhs) - *m_opaque_ap = *rhs.m_opaque_ap; - return *this; + *m_opaque_up = *rhs.m_opaque_up; + return LLDB_RECORD_RESULT(*this); } SBModuleSpecList::~SBModuleSpecList() {} SBModuleSpecList SBModuleSpecList::GetModuleSpecifications(const char *path) { + LLDB_RECORD_STATIC_METHOD(lldb::SBModuleSpecList, SBModuleSpecList, + GetModuleSpecifications, (const char *), 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_ap); - return specs; + ObjectFile::GetModuleSpecifications(file_spec, 0, 0, *specs.m_opaque_up); + return LLDB_RECORD_RESULT(specs); } void SBModuleSpecList::Append(const SBModuleSpec &spec) { - m_opaque_ap->Append(*spec.m_opaque_ap); + LLDB_RECORD_METHOD(void, SBModuleSpecList, Append, + (const lldb::SBModuleSpec &), spec); + + m_opaque_up->Append(*spec.m_opaque_up); } void SBModuleSpecList::Append(const SBModuleSpecList &spec_list) { - m_opaque_ap->Append(*spec_list.m_opaque_ap); + LLDB_RECORD_METHOD(void, SBModuleSpecList, Append, + (const lldb::SBModuleSpecList &), spec_list); + + m_opaque_up->Append(*spec_list.m_opaque_up); } -size_t SBModuleSpecList::GetSize() { return m_opaque_ap->GetSize(); } +size_t SBModuleSpecList::GetSize() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBModuleSpecList, GetSize); + + return m_opaque_up->GetSize(); +} SBModuleSpec SBModuleSpecList::GetSpecAtIndex(size_t i) { + LLDB_RECORD_METHOD(lldb::SBModuleSpec, SBModuleSpecList, GetSpecAtIndex, + (size_t), i); + SBModuleSpec sb_module_spec; - m_opaque_ap->GetModuleSpecAtIndex(i, *sb_module_spec.m_opaque_ap); - return sb_module_spec; + m_opaque_up->GetModuleSpecAtIndex(i, *sb_module_spec.m_opaque_up); + return LLDB_RECORD_RESULT(sb_module_spec); } SBModuleSpec SBModuleSpecList::FindFirstMatchingSpec(const SBModuleSpec &match_spec) { + LLDB_RECORD_METHOD(lldb::SBModuleSpec, SBModuleSpecList, + FindFirstMatchingSpec, (const lldb::SBModuleSpec &), + match_spec); + SBModuleSpec sb_module_spec; - m_opaque_ap->FindMatchingModuleSpec(*match_spec.m_opaque_ap, - *sb_module_spec.m_opaque_ap); - return sb_module_spec; + m_opaque_up->FindMatchingModuleSpec(*match_spec.m_opaque_up, + *sb_module_spec.m_opaque_up); + return LLDB_RECORD_RESULT(sb_module_spec); } SBModuleSpecList SBModuleSpecList::FindMatchingSpecs(const SBModuleSpec &match_spec) { + LLDB_RECORD_METHOD(lldb::SBModuleSpecList, SBModuleSpecList, + FindMatchingSpecs, (const lldb::SBModuleSpec &), + match_spec); + SBModuleSpecList specs; - m_opaque_ap->FindMatchingModuleSpecs(*match_spec.m_opaque_ap, - *specs.m_opaque_ap); - return specs; + m_opaque_up->FindMatchingModuleSpecs(*match_spec.m_opaque_up, + *specs.m_opaque_up); + return LLDB_RECORD_RESULT(specs); } bool SBModuleSpecList::GetDescription(lldb::SBStream &description) { - m_opaque_ap->Dump(description.ref()); + LLDB_RECORD_METHOD(bool, SBModuleSpecList, GetDescription, (lldb::SBStream &), + description); + + m_opaque_up->Dump(description.ref()); return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBModuleSpec>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBModuleSpec, ()); + LLDB_REGISTER_CONSTRUCTOR(SBModuleSpec, (const lldb::SBModuleSpec &)); + LLDB_REGISTER_METHOD(const lldb::SBModuleSpec &, + SBModuleSpec, operator=,(const lldb::SBModuleSpec &)); + LLDB_REGISTER_METHOD_CONST(bool, SBModuleSpec, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBModuleSpec, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBModuleSpec, Clear, ()); + LLDB_REGISTER_METHOD(lldb::SBFileSpec, SBModuleSpec, GetFileSpec, ()); + LLDB_REGISTER_METHOD(void, SBModuleSpec, SetFileSpec, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBFileSpec, SBModuleSpec, GetPlatformFileSpec, + ()); + LLDB_REGISTER_METHOD(void, SBModuleSpec, SetPlatformFileSpec, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBFileSpec, SBModuleSpec, GetSymbolFileSpec, ()); + LLDB_REGISTER_METHOD(void, SBModuleSpec, SetSymbolFileSpec, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(const char *, SBModuleSpec, GetObjectName, ()); + LLDB_REGISTER_METHOD(void, SBModuleSpec, SetObjectName, (const char *)); + LLDB_REGISTER_METHOD(const char *, SBModuleSpec, GetTriple, ()); + LLDB_REGISTER_METHOD(void, SBModuleSpec, SetTriple, (const char *)); + LLDB_REGISTER_METHOD(size_t, SBModuleSpec, GetUUIDLength, ()); + LLDB_REGISTER_METHOD(bool, SBModuleSpec, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_CONSTRUCTOR(SBModuleSpecList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBModuleSpecList, + (const lldb::SBModuleSpecList &)); + LLDB_REGISTER_METHOD( + lldb::SBModuleSpecList &, + SBModuleSpecList, operator=,(const lldb::SBModuleSpecList &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBModuleSpecList, SBModuleSpecList, + GetModuleSpecifications, (const char *)); + LLDB_REGISTER_METHOD(void, SBModuleSpecList, Append, + (const lldb::SBModuleSpec &)); + LLDB_REGISTER_METHOD(void, SBModuleSpecList, Append, + (const lldb::SBModuleSpecList &)); + LLDB_REGISTER_METHOD(size_t, SBModuleSpecList, GetSize, ()); + LLDB_REGISTER_METHOD(lldb::SBModuleSpec, SBModuleSpecList, GetSpecAtIndex, + (size_t)); + LLDB_REGISTER_METHOD(lldb::SBModuleSpec, SBModuleSpecList, + FindFirstMatchingSpec, (const lldb::SBModuleSpec &)); + LLDB_REGISTER_METHOD(lldb::SBModuleSpecList, SBModuleSpecList, + FindMatchingSpecs, (const lldb::SBModuleSpec &)); + LLDB_REGISTER_METHOD(bool, SBModuleSpecList, GetDescription, + (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBPlatform.cpp b/src/llvm-project/lldb/source/API/SBPlatform.cpp index aedad87..f3708d8 100644 --- a/src/llvm-project/lldb/source/API/SBPlatform.cpp +++ b/src/llvm-project/lldb/source/API/SBPlatform.cpp
@@ -1,13 +1,13 @@ //===-- SBPlatform.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBError.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBLaunchInfo.h" @@ -26,11 +26,9 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // PlatformConnectOptions -//---------------------------------------------------------------------- struct PlatformConnectOptions { - PlatformConnectOptions(const char *url = NULL) + PlatformConnectOptions(const char *url = nullptr) : m_url(), m_rsync_options(), m_rsync_remote_path_prefix(), m_rsync_enabled(false), m_rsync_omit_hostname_from_remote_path(false), m_local_cache_directory() { @@ -48,11 +46,9 @@ ConstString m_local_cache_directory; }; -//---------------------------------------------------------------------- // PlatformShellCommand -//---------------------------------------------------------------------- struct PlatformShellCommand { - PlatformShellCommand(const char *shell_command = NULL) + PlatformShellCommand(const char *shell_command = nullptr) : m_command(), m_working_dir(), m_status(0), m_signo(0) { if (shell_command && shell_command[0]) m_command = shell_command; @@ -67,31 +63,45 @@ int m_signo; Timeout<std::ratio<1>> m_timeout = llvm::None; }; -//---------------------------------------------------------------------- // SBPlatformConnectOptions -//---------------------------------------------------------------------- SBPlatformConnectOptions::SBPlatformConnectOptions(const char *url) - : m_opaque_ptr(new PlatformConnectOptions(url)) {} + : m_opaque_ptr(new PlatformConnectOptions(url)) { + LLDB_RECORD_CONSTRUCTOR(SBPlatformConnectOptions, (const char *), url); +} SBPlatformConnectOptions::SBPlatformConnectOptions( const SBPlatformConnectOptions &rhs) : m_opaque_ptr(new PlatformConnectOptions()) { + LLDB_RECORD_CONSTRUCTOR(SBPlatformConnectOptions, + (const lldb::SBPlatformConnectOptions &), rhs); + *m_opaque_ptr = *rhs.m_opaque_ptr; } SBPlatformConnectOptions::~SBPlatformConnectOptions() { delete m_opaque_ptr; } void SBPlatformConnectOptions::operator=(const SBPlatformConnectOptions &rhs) { + LLDB_RECORD_METHOD( + void, + SBPlatformConnectOptions, operator=,( + const lldb::SBPlatformConnectOptions &), + rhs); + *m_opaque_ptr = *rhs.m_opaque_ptr; } const char *SBPlatformConnectOptions::GetURL() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatformConnectOptions, GetURL); + if (m_opaque_ptr->m_url.empty()) - return NULL; + return nullptr; return m_opaque_ptr->m_url.c_str(); } void SBPlatformConnectOptions::SetURL(const char *url) { + LLDB_RECORD_METHOD(void, SBPlatformConnectOptions, SetURL, (const char *), + url); + if (url && url[0]) m_opaque_ptr->m_url = url; else @@ -99,12 +109,18 @@ } bool SBPlatformConnectOptions::GetRsyncEnabled() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBPlatformConnectOptions, GetRsyncEnabled); + 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_RECORD_METHOD(void, SBPlatformConnectOptions, EnableRsync, + (const char *, const char *, bool), 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; @@ -120,47 +136,66 @@ } void SBPlatformConnectOptions::DisableRsync() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBPlatformConnectOptions, DisableRsync); + m_opaque_ptr->m_rsync_enabled = false; } const char *SBPlatformConnectOptions::GetLocalCacheDirectory() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatformConnectOptions, + GetLocalCacheDirectory); + return m_opaque_ptr->m_local_cache_directory.GetCString(); } void SBPlatformConnectOptions::SetLocalCacheDirectory(const char *path) { + LLDB_RECORD_METHOD(void, SBPlatformConnectOptions, SetLocalCacheDirectory, + (const char *), 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_command) - : m_opaque_ptr(new PlatformShellCommand(shell_command)) {} + : m_opaque_ptr(new PlatformShellCommand(shell_command)) { + LLDB_RECORD_CONSTRUCTOR(SBPlatformShellCommand, (const char *), + shell_command); +} SBPlatformShellCommand::SBPlatformShellCommand( const SBPlatformShellCommand &rhs) : m_opaque_ptr(new PlatformShellCommand()) { + LLDB_RECORD_CONSTRUCTOR(SBPlatformShellCommand, + (const lldb::SBPlatformShellCommand &), rhs); + *m_opaque_ptr = *rhs.m_opaque_ptr; } SBPlatformShellCommand::~SBPlatformShellCommand() { delete m_opaque_ptr; } void SBPlatformShellCommand::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBPlatformShellCommand, Clear); + m_opaque_ptr->m_output = std::string(); m_opaque_ptr->m_status = 0; m_opaque_ptr->m_signo = 0; } const char *SBPlatformShellCommand::GetCommand() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatformShellCommand, GetCommand); + if (m_opaque_ptr->m_command.empty()) - return NULL; + return nullptr; return m_opaque_ptr->m_command.c_str(); } void SBPlatformShellCommand::SetCommand(const char *shell_command) { + LLDB_RECORD_METHOD(void, SBPlatformShellCommand, SetCommand, (const char *), + shell_command); + if (shell_command && shell_command[0]) m_opaque_ptr->m_command = shell_command; else @@ -168,12 +203,18 @@ } const char *SBPlatformShellCommand::GetWorkingDirectory() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatformShellCommand, + GetWorkingDirectory); + if (m_opaque_ptr->m_working_dir.empty()) - return NULL; + return nullptr; return m_opaque_ptr->m_working_dir.c_str(); } void SBPlatformShellCommand::SetWorkingDirectory(const char *path) { + LLDB_RECORD_METHOD(void, SBPlatformShellCommand, SetWorkingDirectory, + (const char *), path); + if (path && path[0]) m_opaque_ptr->m_working_dir = path; else @@ -181,34 +222,52 @@ } uint32_t SBPlatformShellCommand::GetTimeoutSeconds() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBPlatformShellCommand, + GetTimeoutSeconds); + if (m_opaque_ptr->m_timeout) return m_opaque_ptr->m_timeout->count(); return UINT32_MAX; } void SBPlatformShellCommand::SetTimeoutSeconds(uint32_t sec) { + LLDB_RECORD_METHOD(void, SBPlatformShellCommand, SetTimeoutSeconds, + (uint32_t), sec); + if (sec == UINT32_MAX) m_opaque_ptr->m_timeout = llvm::None; else m_opaque_ptr->m_timeout = std::chrono::seconds(sec); } -int SBPlatformShellCommand::GetSignal() { return m_opaque_ptr->m_signo; } +int SBPlatformShellCommand::GetSignal() { + LLDB_RECORD_METHOD_NO_ARGS(int, SBPlatformShellCommand, GetSignal); -int SBPlatformShellCommand::GetStatus() { return m_opaque_ptr->m_status; } + return m_opaque_ptr->m_signo; +} + +int SBPlatformShellCommand::GetStatus() { + LLDB_RECORD_METHOD_NO_ARGS(int, SBPlatformShellCommand, GetStatus); + + return m_opaque_ptr->m_status; +} const char *SBPlatformShellCommand::GetOutput() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatformShellCommand, GetOutput); + if (m_opaque_ptr->m_output.empty()) - return NULL; + return nullptr; return m_opaque_ptr->m_output.c_str(); } -//---------------------------------------------------------------------- // SBPlatform -//---------------------------------------------------------------------- -SBPlatform::SBPlatform() : m_opaque_sp() {} +SBPlatform::SBPlatform() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBPlatform); +} SBPlatform::SBPlatform(const char *platform_name) : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR(SBPlatform, (const char *), platform_name); + Status error; if (platform_name && platform_name[0]) m_opaque_sp = Platform::Create(ConstString(platform_name), error); @@ -216,15 +275,29 @@ SBPlatform::~SBPlatform() {} -bool SBPlatform::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBPlatform::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBPlatform, IsValid); + return this->operator bool(); +} +SBPlatform::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBPlatform, operator bool); -void SBPlatform::Clear() { m_opaque_sp.reset(); } + return m_opaque_sp.get() != nullptr; +} + +void SBPlatform::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBPlatform, Clear); + + m_opaque_sp.reset(); +} const char *SBPlatform::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatform, GetName); + PlatformSP platform_sp(GetSP()); if (platform_sp) return platform_sp->GetName().GetCString(); - return NULL; + return nullptr; } lldb::PlatformSP SBPlatform::GetSP() const { return m_opaque_sp; } @@ -234,13 +307,18 @@ } const char *SBPlatform::GetWorkingDirectory() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatform, GetWorkingDirectory); + PlatformSP platform_sp(GetSP()); if (platform_sp) return platform_sp->GetWorkingDirectory().GetCString(); - return NULL; + return nullptr; } bool SBPlatform::SetWorkingDirectory(const char *path) { + LLDB_RECORD_METHOD(bool, SBPlatform, SetWorkingDirectory, (const char *), + path); + PlatformSP platform_sp(GetSP()); if (platform_sp) { if (path) @@ -253,6 +331,9 @@ } SBError SBPlatform::ConnectRemote(SBPlatformConnectOptions &connect_options) { + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, ConnectRemote, + (lldb::SBPlatformConnectOptions &), connect_options); + SBError sb_error; PlatformSP platform_sp(GetSP()); if (platform_sp && connect_options.GetURL()) { @@ -263,16 +344,20 @@ } else { sb_error.SetErrorString("invalid platform"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } void SBPlatform::DisconnectRemote() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBPlatform, DisconnectRemote); + PlatformSP platform_sp(GetSP()); if (platform_sp) platform_sp->DisconnectRemote(); } bool SBPlatform::IsConnected() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBPlatform, IsConnected); + PlatformSP platform_sp(GetSP()); if (platform_sp) return platform_sp->IsConnected(); @@ -280,6 +365,8 @@ } const char *SBPlatform::GetTriple() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatform, GetTriple); + PlatformSP platform_sp(GetSP()); if (platform_sp) { ArchSpec arch(platform_sp->GetSystemArchitecture()); @@ -289,10 +376,12 @@ return ConstString(arch.GetTriple().getTriple().c_str()).GetCString(); } } - return NULL; + return nullptr; } const char *SBPlatform::GetOSBuild() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatform, GetOSBuild); + PlatformSP platform_sp(GetSP()); if (platform_sp) { std::string s; @@ -304,10 +393,12 @@ } } } - return NULL; + return nullptr; } const char *SBPlatform::GetOSDescription() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatform, GetOSDescription); + PlatformSP platform_sp(GetSP()); if (platform_sp) { std::string s; @@ -319,17 +410,21 @@ } } } - return NULL; + return nullptr; } const char *SBPlatform::GetHostname() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBPlatform, GetHostname); + PlatformSP platform_sp(GetSP()); if (platform_sp) return platform_sp->GetHostname(); - return NULL; + return nullptr; } uint32_t SBPlatform::GetOSMajorVersion() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBPlatform, GetOSMajorVersion); + llvm::VersionTuple version; if (PlatformSP platform_sp = GetSP()) version = platform_sp->GetOSVersion(); @@ -337,6 +432,8 @@ } uint32_t SBPlatform::GetOSMinorVersion() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBPlatform, GetOSMinorVersion); + llvm::VersionTuple version; if (PlatformSP platform_sp = GetSP()) version = platform_sp->GetOSVersion(); @@ -344,6 +441,8 @@ } uint32_t SBPlatform::GetOSUpdateVersion() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBPlatform, GetOSUpdateVersion); + llvm::VersionTuple version; if (PlatformSP platform_sp = GetSP()) version = platform_sp->GetOSVersion(); @@ -351,6 +450,9 @@ } SBError SBPlatform::Get(SBFileSpec &src, SBFileSpec &dst) { + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, Get, + (lldb::SBFileSpec &, lldb::SBFileSpec &), src, dst); + SBError sb_error; PlatformSP platform_sp(GetSP()); if (platform_sp) { @@ -358,50 +460,60 @@ } else { sb_error.SetErrorString("invalid platform"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBPlatform::Put(SBFileSpec &src, SBFileSpec &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; - } + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, Put, + (lldb::SBFileSpec &, lldb::SBFileSpec &), src, dst); + return LLDB_RECORD_RESULT( + 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); - } + 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; - }); + Status error; + error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", + src.ref().GetPath().c_str()); + return error; + })); } SBError SBPlatform::Install(SBFileSpec &src, SBFileSpec &dst) { - return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { - if (src.Exists()) - return platform_sp->Install(src.ref(), dst.ref()); + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, Install, + (lldb::SBFileSpec &, lldb::SBFileSpec &), src, dst); + return LLDB_RECORD_RESULT( + 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; - }); + Status error; + error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", + src.ref().GetPath().c_str()); + return error; + })); } SBError SBPlatform::Run(SBPlatformShellCommand &shell_command) { - return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, Run, + (lldb::SBPlatformShellCommand &), shell_command); + return LLDB_RECORD_RESULT(ExecuteConnected([&](const lldb::PlatformSP + &platform_sp) { const char *command = shell_command.GetCommand(); if (!command) return Status("invalid shell command (empty)"); const char *working_dir = shell_command.GetWorkingDirectory(); - if (working_dir == NULL) { + if (working_dir == nullptr) { working_dir = platform_sp->GetWorkingDirectory().GetCString(); if (working_dir) shell_command.SetWorkingDirectory(working_dir); @@ -411,22 +523,27 @@ &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) { - 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; - }); + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, Launch, (lldb::SBLaunchInfo &), + launch_info); + return LLDB_RECORD_RESULT( + ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + ProcessLaunchInfo info = launch_info.ref(); + Status error = platform_sp->LaunchProcess(info); + launch_info.set_ref(info); + return error; + })); } SBError SBPlatform::Kill(const lldb::pid_t pid) { - return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { - return platform_sp->KillProcess(pid); - }); + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, Kill, (const lldb::pid_t), pid); + return LLDB_RECORD_RESULT( + ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + return platform_sp->KillProcess(pid); + })); } SBError SBPlatform::ExecuteConnected( @@ -445,6 +562,9 @@ } SBError SBPlatform::MakeDirectory(const char *path, uint32_t file_permissions) { + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, MakeDirectory, + (const char *, uint32_t), path, file_permissions); + SBError sb_error; PlatformSP platform_sp(GetSP()); if (platform_sp) { @@ -453,10 +573,13 @@ } else { sb_error.SetErrorString("invalid platform"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } uint32_t SBPlatform::GetFilePermissions(const char *path) { + LLDB_RECORD_METHOD(uint32_t, SBPlatform, GetFilePermissions, (const char *), + path); + PlatformSP platform_sp(GetSP()); if (platform_sp) { uint32_t file_permissions = 0; @@ -468,6 +591,9 @@ SBError SBPlatform::SetFilePermissions(const char *path, uint32_t file_permissions) { + LLDB_RECORD_METHOD(lldb::SBError, SBPlatform, SetFilePermissions, + (const char *, uint32_t), path, file_permissions); + SBError sb_error; PlatformSP platform_sp(GetSP()); if (platform_sp) { @@ -476,12 +602,107 @@ } else { sb_error.SetErrorString("invalid platform"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBUnixSignals SBPlatform::GetUnixSignals() const { - if (auto platform_sp = GetSP()) - return SBUnixSignals{platform_sp}; + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBUnixSignals, SBPlatform, + GetUnixSignals); - return {}; + if (auto platform_sp = GetSP()) + return LLDB_RECORD_RESULT(SBUnixSignals{platform_sp}); + + return LLDB_RECORD_RESULT(SBUnixSignals()); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBPlatformConnectOptions>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBPlatformConnectOptions, (const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBPlatformConnectOptions, + (const lldb::SBPlatformConnectOptions &)); + LLDB_REGISTER_METHOD( + void, + SBPlatformConnectOptions, operator=,( + const lldb::SBPlatformConnectOptions &)); + LLDB_REGISTER_METHOD(const char *, SBPlatformConnectOptions, GetURL, ()); + LLDB_REGISTER_METHOD(void, SBPlatformConnectOptions, SetURL, + (const char *)); + LLDB_REGISTER_METHOD(bool, SBPlatformConnectOptions, GetRsyncEnabled, ()); + LLDB_REGISTER_METHOD(void, SBPlatformConnectOptions, EnableRsync, + (const char *, const char *, bool)); + LLDB_REGISTER_METHOD(void, SBPlatformConnectOptions, DisableRsync, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatformConnectOptions, + GetLocalCacheDirectory, ()); + LLDB_REGISTER_METHOD(void, SBPlatformConnectOptions, SetLocalCacheDirectory, + (const char *)); +} + +template <> +void RegisterMethods<SBPlatformShellCommand>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBPlatformShellCommand, (const char *)); + LLDB_REGISTER_CONSTRUCTOR(SBPlatformShellCommand, + (const lldb::SBPlatformShellCommand &)); + LLDB_REGISTER_METHOD(void, SBPlatformShellCommand, Clear, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatformShellCommand, GetCommand, ()); + LLDB_REGISTER_METHOD(void, SBPlatformShellCommand, SetCommand, + (const char *)); + LLDB_REGISTER_METHOD(const char *, SBPlatformShellCommand, + GetWorkingDirectory, ()); + LLDB_REGISTER_METHOD(void, SBPlatformShellCommand, SetWorkingDirectory, + (const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBPlatformShellCommand, GetTimeoutSeconds, + ()); + LLDB_REGISTER_METHOD(void, SBPlatformShellCommand, SetTimeoutSeconds, + (uint32_t)); + LLDB_REGISTER_METHOD(int, SBPlatformShellCommand, GetSignal, ()); + LLDB_REGISTER_METHOD(int, SBPlatformShellCommand, GetStatus, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatformShellCommand, GetOutput, ()); +} + +template <> +void RegisterMethods<SBPlatform>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBPlatform, ()); + LLDB_REGISTER_CONSTRUCTOR(SBPlatform, (const char *)); + LLDB_REGISTER_METHOD_CONST(bool, SBPlatform, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBPlatform, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBPlatform, Clear, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatform, GetName, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatform, GetWorkingDirectory, ()); + LLDB_REGISTER_METHOD(bool, SBPlatform, SetWorkingDirectory, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, ConnectRemote, + (lldb::SBPlatformConnectOptions &)); + LLDB_REGISTER_METHOD(void, SBPlatform, DisconnectRemote, ()); + LLDB_REGISTER_METHOD(bool, SBPlatform, IsConnected, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatform, GetTriple, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatform, GetOSBuild, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatform, GetOSDescription, ()); + LLDB_REGISTER_METHOD(const char *, SBPlatform, GetHostname, ()); + LLDB_REGISTER_METHOD(uint32_t, SBPlatform, GetOSMajorVersion, ()); + LLDB_REGISTER_METHOD(uint32_t, SBPlatform, GetOSMinorVersion, ()); + LLDB_REGISTER_METHOD(uint32_t, SBPlatform, GetOSUpdateVersion, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, Get, + (lldb::SBFileSpec &, lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, Put, + (lldb::SBFileSpec &, lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, Install, + (lldb::SBFileSpec &, lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, Run, + (lldb::SBPlatformShellCommand &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, Launch, + (lldb::SBLaunchInfo &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, Kill, (const lldb::pid_t)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, MakeDirectory, + (const char *, uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBPlatform, GetFilePermissions, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBPlatform, SetFilePermissions, + (const char *, uint32_t)); + LLDB_REGISTER_METHOD_CONST(lldb::SBUnixSignals, SBPlatform, GetUnixSignals, + ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBProcess.cpp b/src/llvm-project/lldb/source/API/SBProcess.cpp index cb11246..4226ff7 100644 --- a/src/llvm-project/lldb/source/API/SBProcess.cpp +++ b/src/llvm-project/lldb/source/API/SBProcess.cpp
@@ -1,13 +1,13 @@ //===-- SBProcess.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include <inttypes.h> @@ -25,7 +25,7 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/Args.h" -#include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/State.h" #include "lldb/Utility/Stream.h" @@ -49,33 +49,43 @@ using namespace lldb; using namespace lldb_private; -SBProcess::SBProcess() : m_opaque_wp() {} - -//---------------------------------------------------------------------- -// SBProcess constructor -//---------------------------------------------------------------------- - -SBProcess::SBProcess(const SBProcess &rhs) : m_opaque_wp(rhs.m_opaque_wp) {} - -SBProcess::SBProcess(const lldb::ProcessSP &process_sp) - : m_opaque_wp(process_sp) {} - -const SBProcess &SBProcess::operator=(const SBProcess &rhs) { - if (this != &rhs) - m_opaque_wp = rhs.m_opaque_wp; - return *this; +SBProcess::SBProcess() : m_opaque_wp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBProcess); } -//---------------------------------------------------------------------- +// SBProcess constructor + +SBProcess::SBProcess(const SBProcess &rhs) : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_RECORD_CONSTRUCTOR(SBProcess, (const lldb::SBProcess &), rhs); +} + +SBProcess::SBProcess(const lldb::ProcessSP &process_sp) + : m_opaque_wp(process_sp) { + LLDB_RECORD_CONSTRUCTOR(SBProcess, (const lldb::ProcessSP &), process_sp); +} + +const SBProcess &SBProcess::operator=(const SBProcess &rhs) { + LLDB_RECORD_METHOD(const lldb::SBProcess &, + SBProcess, operator=,(const lldb::SBProcess &), rhs); + + if (this != &rhs) + m_opaque_wp = rhs.m_opaque_wp; + return LLDB_RECORD_RESULT(*this); +} + // Destructor -//---------------------------------------------------------------------- SBProcess::~SBProcess() {} const char *SBProcess::GetBroadcasterClassName() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBProcess, + GetBroadcasterClassName); + return Process::GetStaticBroadcasterClass().AsCString(); } const char *SBProcess::GetPluginName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBProcess, GetPluginName); + ProcessSP process_sp(GetSP()); if (process_sp) { return process_sp->GetPluginName().GetCString(); @@ -84,6 +94,8 @@ } const char *SBProcess::GetShortPluginName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBProcess, GetShortPluginName); + ProcessSP process_sp(GetSP()); if (process_sp) { return process_sp->GetPluginName().GetCString(); @@ -95,9 +107,19 @@ void SBProcess::SetSP(const ProcessSP &process_sp) { m_opaque_wp = process_sp; } -void SBProcess::Clear() { m_opaque_wp.reset(); } +void SBProcess::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBProcess, Clear); + + m_opaque_wp.reset(); +} bool SBProcess::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBProcess, IsValid); + return this->operator bool(); +} +SBProcess::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBProcess, operator bool); + ProcessSP process_sp(m_opaque_wp.lock()); return ((bool)process_sp && process_sp->IsValid()); } @@ -108,18 +130,12 @@ const char *working_directory, uint32_t launch_flags, bool stop_at_entry, lldb::SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::RemoteLaunch (argv=%p, envp=%p, stdin=%s, " - "stdout=%s, stderr=%s, working-dir=%s, launch_flags=0x%x, " - "stop_at_entry=%i, &error (%p))...", - static_cast<void *>(m_opaque_wp.lock().get()), - static_cast<void *>(argv), static_cast<void *>(envp), - stdin_path ? stdin_path : "NULL", - stdout_path ? stdout_path : "NULL", - stderr_path ? stderr_path : "NULL", - working_directory ? working_directory : "NULL", launch_flags, - stop_at_entry, static_cast<void *>(error.get())); + LLDB_RECORD_METHOD(bool, SBProcess, RemoteLaunch, + (const char **, const char **, const char *, const char *, + const char *, const char *, uint32_t, bool, + lldb::SBError &), + argv, envp, stdin_path, stdout_path, stderr_path, + working_directory, launch_flags, stop_at_entry, error); ProcessSP process_sp(GetSP()); if (process_sp) { @@ -146,19 +162,14 @@ error.SetErrorString("unable to attach pid"); } - if (log) { - SBStream sstr; - error.GetDescription(sstr); - log->Printf("SBProcess(%p)::RemoteLaunch (...) => SBError (%p): %s", - static_cast<void *>(process_sp.get()), - static_cast<void *>(error.get()), sstr.GetData()); - } - return error.Success(); } bool SBProcess::RemoteAttachToProcessWithID(lldb::pid_t pid, lldb::SBError &error) { + LLDB_RECORD_METHOD(bool, SBProcess, RemoteAttachToProcessWithID, + (lldb::pid_t, lldb::SBError &), pid, error); + ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -175,21 +186,11 @@ error.SetErrorString("unable to attach pid"); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - SBStream sstr; - error.GetDescription(sstr); - log->Printf("SBProcess(%p)::RemoteAttachToProcessWithID (%" PRIu64 - ") => SBError (%p): %s", - static_cast<void *>(process_sp.get()), pid, - static_cast<void *>(error.get()), sstr.GetData()); - } - return error.Success(); } uint32_t SBProcess::GetNumThreads() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetNumThreads); uint32_t num_threads = 0; ProcessSP process_sp(GetSP()); @@ -202,15 +203,12 @@ num_threads = process_sp->GetThreadList().GetSize(can_update); } - if (log) - log->Printf("SBProcess(%p)::GetNumThreads () => %d", - static_cast<void *>(process_sp.get()), num_threads); - return num_threads; } SBThread SBProcess::GetSelectedThread() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBThread, SBProcess, + GetSelectedThread); SBThread sb_thread; ThreadSP thread_sp; @@ -222,17 +220,13 @@ sb_thread.SetThread(thread_sp); } - if (log) - log->Printf("SBProcess(%p)::GetSelectedThread () => SBThread(%p)", - static_cast<void *>(process_sp.get()), - static_cast<void *>(thread_sp.get())); - - return sb_thread; + return LLDB_RECORD_RESULT(sb_thread); } SBThread SBProcess::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, CreateOSPluginThread, + (lldb::tid_t, lldb::addr_t), tid, context); SBThread sb_thread; ThreadSP thread_sp; @@ -244,17 +238,11 @@ sb_thread.SetThread(thread_sp); } - if (log) - log->Printf("SBProcess(%p)::CreateOSPluginThread (tid=0x%" PRIx64 - ", context=0x%" PRIx64 ") => SBThread(%p)", - static_cast<void *>(process_sp.get()), tid, context, - static_cast<void *>(thread_sp.get())); - - return sb_thread; + return LLDB_RECORD_RESULT(sb_thread); } SBTarget SBProcess::GetTarget() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBTarget, SBProcess, GetTarget); SBTarget sb_target; TargetSP target_sp; @@ -264,16 +252,12 @@ sb_target.SetSP(target_sp); } - if (log) - log->Printf("SBProcess(%p)::GetTarget () => SBTarget(%p)", - static_cast<void *>(process_sp.get()), - static_cast<void *>(target_sp.get())); - - return sb_target; + return LLDB_RECORD_RESULT(sb_target); } size_t SBProcess::PutSTDIN(const char *src, size_t src_len) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(size_t, SBProcess, PutSTDIN, (const char *, size_t), src, + src_len); size_t ret_val = 0; ProcessSP process_sp(GetSP()); @@ -282,16 +266,13 @@ ret_val = process_sp->PutSTDIN(src, src_len, error); } - if (log) - log->Printf("SBProcess(%p)::PutSTDIN (src=\"%s\", src_len=%" PRIu64 - ") => %" PRIu64, - static_cast<void *>(process_sp.get()), src, - static_cast<uint64_t>(src_len), static_cast<uint64_t>(ret_val)); - return ret_val; } size_t SBProcess::GetSTDOUT(char *dst, size_t dst_len) const { + LLDB_RECORD_METHOD_CONST(size_t, SBProcess, GetSTDOUT, (char *, size_t), dst, + dst_len); + size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -299,18 +280,13 @@ bytes_read = process_sp->GetSTDOUT(dst, dst_len, error); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf( - "SBProcess(%p)::GetSTDOUT (dst=\"%.*s\", dst_len=%" PRIu64 - ") => %" PRIu64, - static_cast<void *>(process_sp.get()), static_cast<int>(bytes_read), - dst, static_cast<uint64_t>(dst_len), static_cast<uint64_t>(bytes_read)); - return bytes_read; } size_t SBProcess::GetSTDERR(char *dst, size_t dst_len) const { + LLDB_RECORD_METHOD_CONST(size_t, SBProcess, GetSTDERR, (char *, size_t), dst, + dst_len); + size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -318,18 +294,13 @@ bytes_read = process_sp->GetSTDERR(dst, dst_len, error); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf( - "SBProcess(%p)::GetSTDERR (dst=\"%.*s\", dst_len=%" PRIu64 - ") => %" PRIu64, - static_cast<void *>(process_sp.get()), static_cast<int>(bytes_read), - dst, static_cast<uint64_t>(dst_len), static_cast<uint64_t>(bytes_read)); - return bytes_read; } size_t SBProcess::GetAsyncProfileData(char *dst, size_t dst_len) const { + LLDB_RECORD_METHOD_CONST(size_t, SBProcess, GetAsyncProfileData, + (char *, size_t), dst, dst_len); + size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -337,20 +308,14 @@ bytes_read = process_sp->GetAsyncProfileData(dst, dst_len, error); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf( - "SBProcess(%p)::GetAsyncProfileData (dst=\"%.*s\", dst_len=%" PRIu64 - ") => %" PRIu64, - static_cast<void *>(process_sp.get()), static_cast<int>(bytes_read), - dst, static_cast<uint64_t>(dst_len), static_cast<uint64_t>(bytes_read)); - return bytes_read; } lldb::SBTrace SBProcess::StartTrace(SBTraceOptions &options, lldb::SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBTrace, SBProcess, StartTrace, + (lldb::SBTraceOptions &, lldb::SBError &), options, error); + ProcessSP process_sp(GetSP()); error.Clear(); SBTrace trace_instance; @@ -362,13 +327,15 @@ } else { uid = process_sp->StartTrace(*(options.m_traceoptions_sp), error.ref()); trace_instance.SetTraceUID(uid); - LLDB_LOG(log, "SBProcess::returned uid - {0}", uid); } - return trace_instance; + return LLDB_RECORD_RESULT(trace_instance); } void SBProcess::ReportEventState(const SBEvent &event, FILE *out) const { - if (out == NULL) + LLDB_RECORD_METHOD_CONST(void, SBProcess, ReportEventState, + (const lldb::SBEvent &, FILE *), event, out); + + if (out == nullptr) return; ProcessSP process_sp(GetSP()); @@ -386,6 +353,10 @@ void SBProcess::AppendEventStateReport(const SBEvent &event, SBCommandReturnObject &result) { + LLDB_RECORD_METHOD(void, SBProcess, AppendEventStateReport, + (const lldb::SBEvent &, lldb::SBCommandReturnObject &), + event, result); + ProcessSP process_sp(GetSP()); if (process_sp) { const StateType event_state = SBProcess::GetStateFromEvent(event); @@ -398,6 +369,9 @@ } bool SBProcess::SetSelectedThread(const SBThread &thread) { + LLDB_RECORD_METHOD(bool, SBProcess, SetSelectedThread, + (const lldb::SBThread &), thread); + ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -409,7 +383,9 @@ } bool SBProcess::SetSelectedThreadByID(lldb::tid_t tid) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBProcess, SetSelectedThreadByID, (lldb::tid_t), + tid); + bool ret_val = false; ProcessSP process_sp(GetSP()); @@ -419,17 +395,12 @@ ret_val = process_sp->GetThreadList().SetSelectedThreadByID(tid); } - if (log) - log->Printf("SBProcess(%p)::SetSelectedThreadByID (tid=0x%4.4" PRIx64 - ") => %s", - static_cast<void *>(process_sp.get()), tid, - (ret_val ? "true" : "false")); - return ret_val; } bool SBProcess::SetSelectedThreadByIndexID(uint32_t index_id) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBProcess, SetSelectedThreadByIndexID, (uint32_t), + index_id); bool ret_val = false; ProcessSP process_sp(GetSP()); @@ -439,16 +410,13 @@ ret_val = process_sp->GetThreadList().SetSelectedThreadByIndexID(index_id); } - if (log) - log->Printf("SBProcess(%p)::SetSelectedThreadByID (tid=0x%x) => %s", - static_cast<void *>(process_sp.get()), index_id, - (ret_val ? "true" : "false")); return ret_val; } SBThread SBProcess::GetThreadAtIndex(size_t index) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, GetThreadAtIndex, (size_t), + index); SBThread sb_thread; ThreadSP thread_sp; @@ -462,17 +430,11 @@ sb_thread.SetThread(thread_sp); } - if (log) - log->Printf("SBProcess(%p)::GetThreadAtIndex (index=%d) => SBThread(%p)", - static_cast<void *>(process_sp.get()), - static_cast<uint32_t>(index), - static_cast<void *>(thread_sp.get())); - - return sb_thread; + return LLDB_RECORD_RESULT(sb_thread); } uint32_t SBProcess::GetNumQueues() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetNumQueues); uint32_t num_queues = 0; ProcessSP process_sp(GetSP()); @@ -485,15 +447,12 @@ } } - if (log) - log->Printf("SBProcess(%p)::GetNumQueues () => %d", - static_cast<void *>(process_sp.get()), num_queues); - return num_queues; } SBQueue SBProcess::GetQueueAtIndex(size_t index) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBQueue, SBProcess, GetQueueAtIndex, (size_t), + index); SBQueue sb_queue; QueueSP queue_sp; @@ -508,16 +467,13 @@ } } - if (log) - log->Printf("SBProcess(%p)::GetQueueAtIndex (index=%d) => SBQueue(%p)", - static_cast<void *>(process_sp.get()), - static_cast<uint32_t>(index), - static_cast<void *>(queue_sp.get())); - - return sb_queue; + return LLDB_RECORD_RESULT(sb_queue); } uint32_t SBProcess::GetStopID(bool include_expression_stops) { + LLDB_RECORD_METHOD(uint32_t, SBProcess, GetStopID, (bool), + include_expression_stops); + ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -531,7 +487,8 @@ } SBEvent SBProcess::GetStopEventForStopID(uint32_t stop_id) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBEvent, SBProcess, GetStopEventForStopID, + (uint32_t), stop_id); SBEvent sb_event; EventSP event_sp; @@ -543,16 +500,11 @@ sb_event.reset(event_sp); } - if (log) - log->Printf("SBProcess(%p)::GetStopEventForStopID (stop_id=%" PRIu32 - ") => SBEvent(%p)", - static_cast<void *>(process_sp.get()), stop_id, - static_cast<void *>(event_sp.get())); - - return sb_event; + return LLDB_RECORD_RESULT(sb_event); } StateType SBProcess::GetState() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::StateType, SBProcess, GetState); StateType ret_val = eStateInvalid; ProcessSP process_sp(GetSP()); @@ -562,16 +514,12 @@ ret_val = process_sp->GetState(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetState () => %s", - static_cast<void *>(process_sp.get()), - lldb_private::StateAsCString(ret_val)); - return ret_val; } int SBProcess::GetExitStatus() { + LLDB_RECORD_METHOD_NO_ARGS(int, SBProcess, GetExitStatus); + int exit_status = 0; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -579,94 +527,74 @@ process_sp->GetTarget().GetAPIMutex()); exit_status = process_sp->GetExitStatus(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetExitStatus () => %i (0x%8.8x)", - static_cast<void *>(process_sp.get()), exit_status, - exit_status); return exit_status; } const char *SBProcess::GetExitDescription() { - const char *exit_desc = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBProcess, GetExitDescription); + + const char *exit_desc = nullptr; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); exit_desc = process_sp->GetExitDescription(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetExitDescription () => %s", - static_cast<void *>(process_sp.get()), exit_desc); return exit_desc; } lldb::pid_t SBProcess::GetProcessID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::pid_t, SBProcess, GetProcessID); + lldb::pid_t ret_val = LLDB_INVALID_PROCESS_ID; ProcessSP process_sp(GetSP()); if (process_sp) ret_val = process_sp->GetID(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetProcessID () => %" PRIu64, - static_cast<void *>(process_sp.get()), ret_val); - return ret_val; } uint32_t SBProcess::GetUniqueID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetUniqueID); + uint32_t ret_val = 0; ProcessSP process_sp(GetSP()); if (process_sp) ret_val = process_sp->GetUniqueID(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetUniqueID () => %" PRIu32, - static_cast<void *>(process_sp.get()), ret_val); return ret_val; } ByteOrder SBProcess::GetByteOrder() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::ByteOrder, SBProcess, GetByteOrder); + ByteOrder byteOrder = eByteOrderInvalid; ProcessSP process_sp(GetSP()); if (process_sp) byteOrder = process_sp->GetTarget().GetArchitecture().GetByteOrder(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetByteOrder () => %d", - static_cast<void *>(process_sp.get()), byteOrder); return byteOrder; } uint32_t SBProcess::GetAddressByteSize() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBProcess, GetAddressByteSize); + uint32_t size = 0; ProcessSP process_sp(GetSP()); if (process_sp) size = process_sp->GetTarget().GetArchitecture().GetAddressByteSize(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetAddressByteSize () => %d", - static_cast<void *>(process_sp.get()), size); return size; } SBError SBProcess::Continue() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Continue); SBError sb_error; ProcessSP process_sp(GetSP()); - if (log) - log->Printf("SBProcess(%p)::Continue ()...", - static_cast<void *>(process_sp.get())); - if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); @@ -674,22 +602,16 @@ if (process_sp->GetTarget().GetDebugger().GetAsyncExecution()) sb_error.ref() = process_sp->Resume(); else - sb_error.ref() = process_sp->ResumeSynchronous(NULL); + sb_error.ref() = process_sp->ResumeSynchronous(nullptr); } else sb_error.SetErrorString("SBProcess is invalid"); - if (log) { - SBStream sstr; - sb_error.GetDescription(sstr); - log->Printf("SBProcess(%p)::Continue () => SBError (%p): %s", - static_cast<void *>(process_sp.get()), - static_cast<void *>(sb_error.get()), sstr.GetData()); - } - - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Destroy() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Destroy); + SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -699,19 +621,12 @@ } else sb_error.SetErrorString("SBProcess is invalid"); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - SBStream sstr; - sb_error.GetDescription(sstr); - log->Printf("SBProcess(%p)::Destroy () => SBError (%p): %s", - static_cast<void *>(process_sp.get()), - static_cast<void *>(sb_error.get()), sstr.GetData()); - } - - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Stop() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Stop); + SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -721,19 +636,12 @@ } else sb_error.SetErrorString("SBProcess is invalid"); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - SBStream sstr; - sb_error.GetDescription(sstr); - log->Printf("SBProcess(%p)::Stop () => SBError (%p): %s", - static_cast<void *>(process_sp.get()), - static_cast<void *>(sb_error.get()), sstr.GetData()); - } - - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Kill() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Kill); + SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -743,25 +651,20 @@ } else sb_error.SetErrorString("SBProcess is invalid"); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - SBStream sstr; - sb_error.GetDescription(sstr); - log->Printf("SBProcess(%p)::Kill () => SBError (%p): %s", - static_cast<void *>(process_sp.get()), - static_cast<void *>(sb_error.get()), sstr.GetData()); - } - - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Detach() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Detach); + // FIXME: This should come from a process default. bool keep_stopped = false; - return Detach(keep_stopped); + return LLDB_RECORD_RESULT(Detach(keep_stopped)); } SBError SBProcess::Detach(bool keep_stopped) { + LLDB_RECORD_METHOD(lldb::SBError, SBProcess, Detach, (bool), keep_stopped); + SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -771,10 +674,12 @@ } else sb_error.SetErrorString("SBProcess is invalid"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Signal(int signo) { + LLDB_RECORD_METHOD(lldb::SBError, SBProcess, Signal, (int), signo); + SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -783,25 +688,22 @@ sb_error.SetError(process_sp->Signal(signo)); } else sb_error.SetErrorString("SBProcess is invalid"); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - SBStream sstr; - sb_error.GetDescription(sstr); - log->Printf("SBProcess(%p)::Signal (signo=%i) => SBError (%p): %s", - static_cast<void *>(process_sp.get()), signo, - static_cast<void *>(sb_error.get()), sstr.GetData()); - } - return sb_error; + + return LLDB_RECORD_RESULT(sb_error); } SBUnixSignals SBProcess::GetUnixSignals() { - if (auto process_sp = GetSP()) - return SBUnixSignals{process_sp}; + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBUnixSignals, SBProcess, GetUnixSignals); - return {}; + if (auto process_sp = GetSP()) + return LLDB_RECORD_RESULT(SBUnixSignals{process_sp}); + + return LLDB_RECORD_RESULT(SBUnixSignals{}); } void SBProcess::SendAsyncInterrupt() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBProcess, SendAsyncInterrupt); + ProcessSP process_sp(GetSP()); if (process_sp) { process_sp->SendAsyncInterrupt(); @@ -809,6 +711,9 @@ } SBThread SBProcess::GetThreadByID(tid_t tid) { + LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, GetThreadByID, (lldb::tid_t), + tid); + SBThread sb_thread; ThreadSP thread_sp; ProcessSP process_sp(GetSP()); @@ -821,17 +726,13 @@ sb_thread.SetThread(thread_sp); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetThreadByID (tid=0x%4.4" PRIx64 - ") => SBThread (%p)", - static_cast<void *>(process_sp.get()), tid, - static_cast<void *>(thread_sp.get())); - - return sb_thread; + return LLDB_RECORD_RESULT(sb_thread); } SBThread SBProcess::GetThreadByIndexID(uint32_t index_id) { + LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, GetThreadByIndexID, (uint32_t), + index_id); + SBThread sb_thread; ThreadSP thread_sp; ProcessSP process_sp(GetSP()); @@ -845,51 +746,48 @@ sb_thread.SetThread(thread_sp); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetThreadByID (tid=0x%x) => SBThread (%p)", - static_cast<void *>(process_sp.get()), index_id, - static_cast<void *>(thread_sp.get())); - - return sb_thread; + return LLDB_RECORD_RESULT(sb_thread); } StateType SBProcess::GetStateFromEvent(const SBEvent &event) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_STATIC_METHOD(lldb::StateType, SBProcess, GetStateFromEvent, + (const lldb::SBEvent &), event); StateType ret_val = Process::ProcessEventData::GetStateFromEvent(event.get()); - if (log) - log->Printf("SBProcess::GetStateFromEvent (event.sp=%p) => %s", - static_cast<void *>(event.get()), - lldb_private::StateAsCString(ret_val)); - return ret_val; } bool SBProcess::GetRestartedFromEvent(const SBEvent &event) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_STATIC_METHOD(bool, SBProcess, GetRestartedFromEvent, + (const lldb::SBEvent &), event); bool ret_val = Process::ProcessEventData::GetRestartedFromEvent(event.get()); - if (log) - log->Printf("SBProcess::%s (event.sp=%p) => %d", __FUNCTION__, - static_cast<void *>(event.get()), ret_val); - return ret_val; } size_t SBProcess::GetNumRestartedReasonsFromEvent(const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(size_t, SBProcess, GetNumRestartedReasonsFromEvent, + (const lldb::SBEvent &), event); + return Process::ProcessEventData::GetNumRestartedReasons(event.get()); } const char * SBProcess::GetRestartedReasonAtIndexFromEvent(const lldb::SBEvent &event, size_t idx) { + LLDB_RECORD_STATIC_METHOD(const char *, SBProcess, + GetRestartedReasonAtIndexFromEvent, + (const lldb::SBEvent &, size_t), event, idx); + return Process::ProcessEventData::GetRestartedReasonAtIndex(event.get(), idx); } SBProcess SBProcess::GetProcessFromEvent(const SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(lldb::SBProcess, SBProcess, GetProcessFromEvent, + (const lldb::SBEvent &), event); + ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event.get()); if (!process_sp) { @@ -897,24 +795,37 @@ process_sp = EventDataStructuredData::GetProcessFromEvent(event.get()); } - return SBProcess(process_sp); + return LLDB_RECORD_RESULT(SBProcess(process_sp)); } bool SBProcess::GetInterruptedFromEvent(const SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(bool, SBProcess, GetInterruptedFromEvent, + (const lldb::SBEvent &), event); + return Process::ProcessEventData::GetInterruptedFromEvent(event.get()); } lldb::SBStructuredData SBProcess::GetStructuredDataFromEvent(const lldb::SBEvent &event) { - return SBStructuredData(event.GetSP()); + LLDB_RECORD_STATIC_METHOD(lldb::SBStructuredData, SBProcess, + GetStructuredDataFromEvent, (const lldb::SBEvent &), + event); + + return LLDB_RECORD_RESULT(SBStructuredData(event.GetSP())); } bool SBProcess::EventIsProcessEvent(const SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(bool, SBProcess, EventIsProcessEvent, + (const lldb::SBEvent &), event); + return (event.GetBroadcasterClass() == SBProcess::GetBroadcasterClass()) && !EventIsStructuredDataEvent(event); } bool SBProcess::EventIsStructuredDataEvent(const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(bool, SBProcess, EventIsStructuredDataEvent, + (const lldb::SBEvent &), event); + EventSP event_sp = event.GetSP(); EventData *event_data = event_sp ? event_sp->GetData() : nullptr; return event_data && (event_data->GetFlavor() == @@ -922,38 +833,35 @@ } SBBroadcaster SBProcess::GetBroadcaster() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBroadcaster, SBProcess, + GetBroadcaster); + ProcessSP process_sp(GetSP()); SBBroadcaster broadcaster(process_sp.get(), false); - if (log) - log->Printf("SBProcess(%p)::GetBroadcaster () => SBBroadcaster (%p)", - static_cast<void *>(process_sp.get()), - static_cast<void *>(broadcaster.get())); - return broadcaster; + return LLDB_RECORD_RESULT(broadcaster); } const char *SBProcess::GetBroadcasterClass() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBProcess, + GetBroadcasterClass); + return Process::GetStaticBroadcasterClass().AsCString(); } size_t SBProcess::ReadMemory(addr_t addr, void *dst, size_t dst_len, SBError &sb_error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_DUMMY(size_t, SBProcess, ReadMemory, + (lldb::addr_t, void *, size_t, lldb::SBError &), addr, dst, + dst_len, sb_error); size_t bytes_read = 0; ProcessSP process_sp(GetSP()); - if (log) - log->Printf("SBProcess(%p)::ReadMemory (addr=0x%" PRIx64 - ", dst=%p, dst_len=%" PRIu64 ", SBError (%p))...", - static_cast<void *>(process_sp.get()), addr, - static_cast<void *>(dst), static_cast<uint64_t>(dst_len), - static_cast<void *>(sb_error.get())); if (process_sp) { Process::StopLocker stop_locker; @@ -962,31 +870,21 @@ process_sp->GetTarget().GetAPIMutex()); bytes_read = process_sp->ReadMemory(addr, dst, dst_len, sb_error.ref()); } else { - if (log) - log->Printf("SBProcess(%p)::ReadMemory() => error: process is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } - if (log) { - SBStream sstr; - sb_error.GetDescription(sstr); - log->Printf("SBProcess(%p)::ReadMemory (addr=0x%" PRIx64 - ", dst=%p, dst_len=%" PRIu64 ", SBError (%p): %s) => %" PRIu64, - static_cast<void *>(process_sp.get()), addr, - static_cast<void *>(dst), static_cast<uint64_t>(dst_len), - static_cast<void *>(sb_error.get()), sstr.GetData(), - static_cast<uint64_t>(bytes_read)); - } - return bytes_read; } size_t SBProcess::ReadCStringFromMemory(addr_t addr, void *buf, size_t size, lldb::SBError &sb_error) { + LLDB_RECORD_DUMMY(size_t, SBProcess, ReadCStringFromMemory, + (lldb::addr_t, void *, size_t, lldb::SBError &), addr, buf, + size, sb_error); + size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -997,11 +895,6 @@ bytes_read = process_sp->ReadCStringFromMemory(addr, (char *)buf, size, sb_error.ref()); } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::ReadCStringFromMemory() => error: process " - "is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } else { @@ -1012,6 +905,10 @@ uint64_t SBProcess::ReadUnsignedFromMemory(addr_t addr, uint32_t byte_size, lldb::SBError &sb_error) { + LLDB_RECORD_METHOD(uint64_t, SBProcess, ReadUnsignedFromMemory, + (lldb::addr_t, uint32_t, lldb::SBError &), addr, byte_size, + sb_error); + uint64_t value = 0; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -1022,11 +919,6 @@ value = process_sp->ReadUnsignedIntegerFromMemory(addr, byte_size, 0, sb_error.ref()); } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::ReadUnsignedFromMemory() => error: process " - "is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } else { @@ -1037,6 +929,9 @@ lldb::addr_t SBProcess::ReadPointerFromMemory(addr_t addr, lldb::SBError &sb_error) { + LLDB_RECORD_METHOD(lldb::addr_t, SBProcess, ReadPointerFromMemory, + (lldb::addr_t, lldb::SBError &), addr, sb_error); + lldb::addr_t ptr = LLDB_INVALID_ADDRESS; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -1046,11 +941,6 @@ process_sp->GetTarget().GetAPIMutex()); ptr = process_sp->ReadPointerFromMemory(addr, sb_error.ref()); } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::ReadPointerFromMemory() => error: process " - "is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } else { @@ -1061,19 +951,14 @@ size_t SBProcess::WriteMemory(addr_t addr, const void *src, size_t src_len, SBError &sb_error) { + LLDB_RECORD_DUMMY(size_t, SBProcess, WriteMemory, + (lldb::addr_t, const void *, size_t, lldb::SBError &), addr, + src, src_len, sb_error); + size_t bytes_written = 0; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - ProcessSP process_sp(GetSP()); - if (log) - log->Printf("SBProcess(%p)::WriteMemory (addr=0x%" PRIx64 - ", src=%p, src_len=%" PRIu64 ", SBError (%p))...", - static_cast<void *>(process_sp.get()), addr, - static_cast<const void *>(src), static_cast<uint64_t>(src_len), - static_cast<void *>(sb_error.get())); - if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { @@ -1082,28 +967,17 @@ bytes_written = process_sp->WriteMemory(addr, src, src_len, sb_error.ref()); } else { - if (log) - log->Printf("SBProcess(%p)::WriteMemory() => error: process is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } - if (log) { - SBStream sstr; - sb_error.GetDescription(sstr); - log->Printf("SBProcess(%p)::WriteMemory (addr=0x%" PRIx64 - ", src=%p, src_len=%" PRIu64 ", SBError (%p): %s) => %" PRIu64, - static_cast<void *>(process_sp.get()), addr, - static_cast<const void *>(src), static_cast<uint64_t>(src_len), - static_cast<void *>(sb_error.get()), sstr.GetData(), - static_cast<uint64_t>(bytes_written)); - } - return bytes_written; } bool SBProcess::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBProcess, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); ProcessSP process_sp(GetSP()); @@ -1111,7 +985,7 @@ char path[PATH_MAX]; GetTarget().GetExecutable().GetPath(path, sizeof(path)); Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); - const char *exe_name = NULL; + const char *exe_name = nullptr; if (exe_module) exe_name = exe_module->GetFileSpec().GetFilename().AsCString(); @@ -1127,7 +1001,9 @@ uint32_t SBProcess::GetNumSupportedHardwareWatchpoints(lldb::SBError &sb_error) const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(uint32_t, SBProcess, + GetNumSupportedHardwareWatchpoints, + (lldb::SBError &), sb_error); uint32_t num = 0; ProcessSP process_sp(GetSP()); @@ -1135,9 +1011,6 @@ std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->GetWatchpointSupportInfo(num)); - if (log) - log->Printf("SBProcess(%p)::GetNumSupportedHardwareWatchpoints () => %u", - static_cast<void *>(process_sp.get()), num); } else { sb_error.SetErrorString("SBProcess is invalid"); } @@ -1146,39 +1019,34 @@ uint32_t SBProcess::LoadImage(lldb::SBFileSpec &sb_remote_image_spec, lldb::SBError &sb_error) { + LLDB_RECORD_METHOD(uint32_t, SBProcess, LoadImage, + (lldb::SBFileSpec &, lldb::SBError &), + 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) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD( + uint32_t, SBProcess, LoadImage, + (const lldb::SBFileSpec &, const lldb::SBFileSpec &, lldb::SBError &), + 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())) { - if (log) - log->Printf("SBProcess(%p)::LoadImage() => calling Platform::LoadImage" - "for: %s", - static_cast<void *>(process_sp.get()), - sb_local_image_spec.GetFilename()); - 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 { - if (log) - log->Printf("SBProcess(%p)::LoadImage() => error: process is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } - } else { - if (log) - log->Printf("SBProcess(%p)::LoadImage() => error: called with invalid" - " process", - static_cast<void *>(process_sp.get())); + } else { sb_error.SetErrorString("process is invalid"); } return LLDB_INVALID_IMAGE_TOKEN; @@ -1186,19 +1054,17 @@ uint32_t SBProcess::LoadImageUsingPaths(const lldb::SBFileSpec &image_spec, SBStringList &paths, - lldb::SBFileSpec &loaded_path, + lldb::SBFileSpec &loaded_path, lldb::SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(uint32_t, SBProcess, LoadImageUsingPaths, + (const lldb::SBFileSpec &, lldb::SBStringList &, + lldb::SBFileSpec &, lldb::SBError &), + image_spec, paths, loaded_path, error); + ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { - if (log) - log->Printf("SBProcess(%p)::LoadImageUsingPaths() => " - "calling Platform::LoadImageUsingPaths for: %s", - static_cast<void *>(process_sp.get()), - image_spec.GetFilename()); - std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); @@ -1208,34 +1074,26 @@ 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; + + 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 { - if (log) - log->Printf("SBProcess(%p)::LoadImageUsingPaths() => error: " - "process is running", - static_cast<void *>(process_sp.get())); error.SetErrorString("process is running"); } - } else { - if (log) - log->Printf("SBProcess(%p)::LoadImageUsingPaths() => error: " - "called with invalid process", - static_cast<void *>(process_sp.get())); + } else { error.SetErrorString("process is invalid"); } - + return LLDB_INVALID_IMAGE_TOKEN; } lldb::SBError SBProcess::UnloadImage(uint32_t image_token) { + LLDB_RECORD_METHOD(lldb::SBError, SBProcess, UnloadImage, (uint32_t), + image_token); + lldb::SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -1247,18 +1105,17 @@ sb_error.SetError( platform_sp->UnloadImage(process_sp.get(), image_token)); } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::UnloadImage() => error: process is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } else sb_error.SetErrorString("invalid process"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } lldb::SBError SBProcess::SendEventData(const char *event_data) { + LLDB_RECORD_METHOD(lldb::SBError, SBProcess, SendEventData, (const char *), + event_data); + lldb::SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -1268,19 +1125,16 @@ process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->SendEventData(event_data)); } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf( - "SBProcess(%p)::SendEventData() => error: process is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } else sb_error.SetErrorString("invalid process"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } uint32_t SBProcess::GetNumExtendedBacktraceTypes() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetNumExtendedBacktraceTypes); + ProcessSP process_sp(GetSP()); if (process_sp && process_sp->GetSystemRuntime()) { SystemRuntime *runtime = process_sp->GetSystemRuntime(); @@ -1290,6 +1144,9 @@ } const char *SBProcess::GetExtendedBacktraceTypeAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(const char *, SBProcess, GetExtendedBacktraceTypeAtIndex, + (uint32_t), idx); + ProcessSP process_sp(GetSP()); if (process_sp && process_sp->GetSystemRuntime()) { SystemRuntime *runtime = process_sp->GetSystemRuntime(); @@ -1297,28 +1154,28 @@ runtime->GetExtendedBacktraceTypes(); if (idx < names.size()) { return names[idx].AsCString(); - } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetExtendedBacktraceTypeAtIndex() => " - "error: requested extended backtrace name out of bounds", - static_cast<void *>(process_sp.get())); } } - return NULL; + return nullptr; } SBThreadCollection SBProcess::GetHistoryThreads(addr_t addr) { + LLDB_RECORD_METHOD(lldb::SBThreadCollection, SBProcess, GetHistoryThreads, + (lldb::addr_t), addr); + ProcessSP process_sp(GetSP()); SBThreadCollection threads; if (process_sp) { threads = SBThreadCollection(process_sp->GetHistoryThreads(addr)); } - return threads; + return LLDB_RECORD_RESULT(threads); } bool SBProcess::IsInstrumentationRuntimePresent( InstrumentationRuntimeType type) { + LLDB_RECORD_METHOD(bool, SBProcess, IsInstrumentationRuntimePresent, + (lldb::InstrumentationRuntimeType), type); + ProcessSP process_sp(GetSP()); if (!process_sp) return false; @@ -1333,11 +1190,14 @@ } lldb::SBError SBProcess::SaveCore(const char *file_name) { + LLDB_RECORD_METHOD(lldb::SBError, SBProcess, SaveCore, (const char *), + file_name); + lldb::SBError error; ProcessSP process_sp(GetSP()); if (!process_sp) { error.SetErrorString("SBProcess is invalid"); - return error; + return LLDB_RECORD_RESULT(error); } std::lock_guard<std::recursive_mutex> guard( @@ -1345,17 +1205,21 @@ if (process_sp->GetState() != eStateStopped) { error.SetErrorString("the process is not stopped"); - return error; + return LLDB_RECORD_RESULT(error); } FileSpec core_file(file_name); error.ref() = PluginManager::SaveCore(process_sp, core_file); - return error; + return LLDB_RECORD_RESULT(error); } lldb::SBError SBProcess::GetMemoryRegionInfo(lldb::addr_t load_addr, SBMemoryRegionInfo &sb_region_info) { + LLDB_RECORD_METHOD(lldb::SBError, SBProcess, GetMemoryRegionInfo, + (lldb::addr_t, lldb::SBMemoryRegionInfo &), load_addr, + sb_region_info); + lldb::SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { @@ -1367,20 +1231,18 @@ sb_error.ref() = process_sp->GetMemoryRegionInfo(load_addr, sb_region_info.ref()); } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf( - "SBProcess(%p)::GetMemoryRegionInfo() => error: process is running", - static_cast<void *>(process_sp.get())); sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } lldb::SBMemoryRegionInfoList SBProcess::GetMemoryRegions() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBMemoryRegionInfoList, SBProcess, + GetMemoryRegions); + lldb::SBMemoryRegionInfoList sb_region_list; ProcessSP process_sp(GetSP()); @@ -1390,23 +1252,153 @@ process_sp->GetTarget().GetAPIMutex()); process_sp->GetMemoryRegions(sb_region_list.ref()); - } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf( - "SBProcess(%p)::GetMemoryRegionInfo() => error: process is running", - static_cast<void *>(process_sp.get())); } - return sb_region_list; + return LLDB_RECORD_RESULT(sb_region_list); } lldb::SBProcessInfo SBProcess::GetProcessInfo() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBProcessInfo, SBProcess, GetProcessInfo); + 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; + return LLDB_RECORD_RESULT(sb_proc_info); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBProcess>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBProcess, ()); + LLDB_REGISTER_CONSTRUCTOR(SBProcess, (const lldb::SBProcess &)); + LLDB_REGISTER_CONSTRUCTOR(SBProcess, (const lldb::ProcessSP &)); + LLDB_REGISTER_METHOD(const lldb::SBProcess &, + SBProcess, operator=,(const lldb::SBProcess &)); + LLDB_REGISTER_STATIC_METHOD(const char *, SBProcess, + GetBroadcasterClassName, ()); + LLDB_REGISTER_METHOD(const char *, SBProcess, GetPluginName, ()); + LLDB_REGISTER_METHOD(const char *, SBProcess, GetShortPluginName, ()); + LLDB_REGISTER_METHOD(void, SBProcess, Clear, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBProcess, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBProcess, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBProcess, RemoteLaunch, + (const char **, const char **, const char *, + const char *, const char *, const char *, uint32_t, + bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(bool, SBProcess, RemoteAttachToProcessWithID, + (lldb::pid_t, lldb::SBError &)); + LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetNumThreads, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBThread, SBProcess, GetSelectedThread, + ()); + LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, CreateOSPluginThread, + (lldb::tid_t, lldb::addr_t)); + LLDB_REGISTER_METHOD_CONST(lldb::SBTarget, SBProcess, GetTarget, ()); + LLDB_REGISTER_METHOD(size_t, SBProcess, PutSTDIN, (const char *, size_t)); + LLDB_REGISTER_METHOD_CONST(size_t, SBProcess, GetSTDOUT, (char *, size_t)); + LLDB_REGISTER_METHOD_CONST(size_t, SBProcess, GetSTDERR, (char *, size_t)); + LLDB_REGISTER_METHOD_CONST(size_t, SBProcess, GetAsyncProfileData, + (char *, size_t)); + LLDB_REGISTER_METHOD(lldb::SBTrace, SBProcess, StartTrace, + (lldb::SBTraceOptions &, lldb::SBError &)); + LLDB_REGISTER_METHOD_CONST(void, SBProcess, ReportEventState, + (const lldb::SBEvent &, FILE *)); + LLDB_REGISTER_METHOD( + void, SBProcess, AppendEventStateReport, + (const lldb::SBEvent &, lldb::SBCommandReturnObject &)); + LLDB_REGISTER_METHOD(bool, SBProcess, SetSelectedThread, + (const lldb::SBThread &)); + LLDB_REGISTER_METHOD(bool, SBProcess, SetSelectedThreadByID, (lldb::tid_t)); + LLDB_REGISTER_METHOD(bool, SBProcess, SetSelectedThreadByIndexID, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, GetThreadAtIndex, (size_t)); + LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetNumQueues, ()); + LLDB_REGISTER_METHOD(lldb::SBQueue, SBProcess, GetQueueAtIndex, (size_t)); + LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetStopID, (bool)); + LLDB_REGISTER_METHOD(lldb::SBEvent, SBProcess, GetStopEventForStopID, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::StateType, SBProcess, GetState, ()); + LLDB_REGISTER_METHOD(int, SBProcess, GetExitStatus, ()); + LLDB_REGISTER_METHOD(const char *, SBProcess, GetExitDescription, ()); + LLDB_REGISTER_METHOD(lldb::pid_t, SBProcess, GetProcessID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetUniqueID, ()); + LLDB_REGISTER_METHOD_CONST(lldb::ByteOrder, SBProcess, GetByteOrder, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBProcess, GetAddressByteSize, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Continue, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Destroy, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Stop, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Kill, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Detach, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Detach, (bool)); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Signal, (int)); + LLDB_REGISTER_METHOD(lldb::SBUnixSignals, SBProcess, GetUnixSignals, ()); + LLDB_REGISTER_METHOD(void, SBProcess, SendAsyncInterrupt, ()); + LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, GetThreadByID, + (lldb::tid_t)); + LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, GetThreadByIndexID, + (uint32_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::StateType, SBProcess, GetStateFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, GetRestartedFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(size_t, SBProcess, + GetNumRestartedReasonsFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(const char *, SBProcess, + GetRestartedReasonAtIndexFromEvent, + (const lldb::SBEvent &, size_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBProcess, SBProcess, GetProcessFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, GetInterruptedFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBStructuredData, SBProcess, + GetStructuredDataFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, EventIsProcessEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, EventIsStructuredDataEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBBroadcaster, SBProcess, GetBroadcaster, + ()); + LLDB_REGISTER_STATIC_METHOD(const char *, SBProcess, GetBroadcasterClass, + ()); + LLDB_REGISTER_METHOD(uint64_t, SBProcess, ReadUnsignedFromMemory, + (lldb::addr_t, uint32_t, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::addr_t, SBProcess, ReadPointerFromMemory, + (lldb::addr_t, lldb::SBError &)); + LLDB_REGISTER_METHOD(bool, SBProcess, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBProcess, + GetNumSupportedHardwareWatchpoints, + (lldb::SBError &)); + LLDB_REGISTER_METHOD(uint32_t, SBProcess, LoadImage, + (lldb::SBFileSpec &, lldb::SBError &)); + LLDB_REGISTER_METHOD( + uint32_t, SBProcess, LoadImage, + (const lldb::SBFileSpec &, const lldb::SBFileSpec &, lldb::SBError &)); + LLDB_REGISTER_METHOD(uint32_t, SBProcess, LoadImageUsingPaths, + (const lldb::SBFileSpec &, lldb::SBStringList &, + lldb::SBFileSpec &, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, UnloadImage, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, SendEventData, + (const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetNumExtendedBacktraceTypes, ()); + LLDB_REGISTER_METHOD(const char *, SBProcess, + GetExtendedBacktraceTypeAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBThreadCollection, SBProcess, GetHistoryThreads, + (lldb::addr_t)); + LLDB_REGISTER_METHOD(bool, SBProcess, IsInstrumentationRuntimePresent, + (lldb::InstrumentationRuntimeType)); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, SaveCore, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, GetMemoryRegionInfo, + (lldb::addr_t, lldb::SBMemoryRegionInfo &)); + LLDB_REGISTER_METHOD(lldb::SBMemoryRegionInfoList, SBProcess, + GetMemoryRegions, ()); + LLDB_REGISTER_METHOD(lldb::SBProcessInfo, SBProcess, GetProcessInfo, ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBProcessInfo.cpp b/src/llvm-project/lldb/source/API/SBProcessInfo.cpp index 2b3ebfb..be242ec 100644 --- a/src/llvm-project/lldb/source/API/SBProcessInfo.cpp +++ b/src/llvm-project/lldb/source/API/SBProcessInfo.cpp
@@ -1,145 +1,210 @@ //===-- SBProcessInfo.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBFileSpec.h" -#include "lldb/Target/Process.h" +#include "lldb/Utility/ProcessInfo.h" using namespace lldb; using namespace lldb_private; -SBProcessInfo::SBProcessInfo() : m_opaque_ap() {} +SBProcessInfo::SBProcessInfo() : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBProcessInfo); +} -SBProcessInfo::SBProcessInfo(const SBProcessInfo &rhs) : m_opaque_ap() { - if (rhs.IsValid()) { - ref() = *rhs.m_opaque_ap; - } +SBProcessInfo::SBProcessInfo(const SBProcessInfo &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBProcessInfo, (const lldb::SBProcessInfo &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBProcessInfo::~SBProcessInfo() {} SBProcessInfo &SBProcessInfo::operator=(const SBProcessInfo &rhs) { - if (this != &rhs) { - if (rhs.IsValid()) - ref() = *rhs.m_opaque_ap; - else - m_opaque_ap.reset(); - } - return *this; + LLDB_RECORD_METHOD(lldb::SBProcessInfo &, + SBProcessInfo, operator=,(const lldb::SBProcessInfo &), + rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } ProcessInstanceInfo &SBProcessInfo::ref() { - if (m_opaque_ap == nullptr) { - m_opaque_ap.reset(new ProcessInstanceInfo()); + if (m_opaque_up == nullptr) { + m_opaque_up.reset(new ProcessInstanceInfo()); } - return *m_opaque_ap; + return *m_opaque_up; } void SBProcessInfo::SetProcessInfo(const ProcessInstanceInfo &proc_info_ref) { ref() = proc_info_ref; } -bool SBProcessInfo::IsValid() const { return m_opaque_ap != nullptr; } +bool SBProcessInfo::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBProcessInfo, IsValid); + return this->operator bool(); +} +SBProcessInfo::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBProcessInfo, operator bool); + + return m_opaque_up != nullptr; +} const char *SBProcessInfo::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBProcessInfo, GetName); + const char *name = nullptr; - if (m_opaque_ap) { - name = m_opaque_ap->GetName(); + if (m_opaque_up) { + name = m_opaque_up->GetName(); } return name; } SBFileSpec SBProcessInfo::GetExecutableFile() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFileSpec, SBProcessInfo, + GetExecutableFile); + SBFileSpec file_spec; - if (m_opaque_ap) { - file_spec.SetFileSpec(m_opaque_ap->GetExecutableFile()); + if (m_opaque_up) { + file_spec.SetFileSpec(m_opaque_up->GetExecutableFile()); } - return file_spec; + return LLDB_RECORD_RESULT(file_spec); } lldb::pid_t SBProcessInfo::GetProcessID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::pid_t, SBProcessInfo, GetProcessID); + lldb::pid_t proc_id = LLDB_INVALID_PROCESS_ID; - if (m_opaque_ap) { - proc_id = m_opaque_ap->GetProcessID(); + if (m_opaque_up) { + proc_id = m_opaque_up->GetProcessID(); } return proc_id; } uint32_t SBProcessInfo::GetUserID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcessInfo, GetUserID); + uint32_t user_id = UINT32_MAX; - if (m_opaque_ap) { - user_id = m_opaque_ap->GetUserID(); + if (m_opaque_up) { + user_id = m_opaque_up->GetUserID(); } return user_id; } uint32_t SBProcessInfo::GetGroupID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcessInfo, GetGroupID); + uint32_t group_id = UINT32_MAX; - if (m_opaque_ap) { - group_id = m_opaque_ap->GetGroupID(); + if (m_opaque_up) { + group_id = m_opaque_up->GetGroupID(); } return group_id; } bool SBProcessInfo::UserIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBProcessInfo, UserIDIsValid); + bool is_valid = false; - if (m_opaque_ap) { - is_valid = m_opaque_ap->UserIDIsValid(); + if (m_opaque_up) { + is_valid = m_opaque_up->UserIDIsValid(); } return is_valid; } bool SBProcessInfo::GroupIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBProcessInfo, GroupIDIsValid); + bool is_valid = false; - if (m_opaque_ap) { - is_valid = m_opaque_ap->GroupIDIsValid(); + if (m_opaque_up) { + is_valid = m_opaque_up->GroupIDIsValid(); } return is_valid; } uint32_t SBProcessInfo::GetEffectiveUserID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcessInfo, GetEffectiveUserID); + uint32_t user_id = UINT32_MAX; - if (m_opaque_ap) { - user_id = m_opaque_ap->GetEffectiveUserID(); + if (m_opaque_up) { + user_id = m_opaque_up->GetEffectiveUserID(); } return user_id; } uint32_t SBProcessInfo::GetEffectiveGroupID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcessInfo, GetEffectiveGroupID); + uint32_t group_id = UINT32_MAX; - if (m_opaque_ap) { - group_id = m_opaque_ap->GetEffectiveGroupID(); + if (m_opaque_up) { + group_id = m_opaque_up->GetEffectiveGroupID(); } return group_id; } bool SBProcessInfo::EffectiveUserIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBProcessInfo, EffectiveUserIDIsValid); + bool is_valid = false; - if (m_opaque_ap) { - is_valid = m_opaque_ap->EffectiveUserIDIsValid(); + if (m_opaque_up) { + is_valid = m_opaque_up->EffectiveUserIDIsValid(); } return is_valid; } bool SBProcessInfo::EffectiveGroupIDIsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBProcessInfo, EffectiveGroupIDIsValid); + bool is_valid = false; - if (m_opaque_ap) { - is_valid = m_opaque_ap->EffectiveGroupIDIsValid(); + if (m_opaque_up) { + is_valid = m_opaque_up->EffectiveGroupIDIsValid(); } return is_valid; } lldb::pid_t SBProcessInfo::GetParentProcessID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::pid_t, SBProcessInfo, GetParentProcessID); + lldb::pid_t proc_id = LLDB_INVALID_PROCESS_ID; - if (m_opaque_ap) { - proc_id = m_opaque_ap->GetParentProcessID(); + if (m_opaque_up) { + proc_id = m_opaque_up->GetParentProcessID(); } return proc_id; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBProcessInfo>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBProcessInfo, ()); + LLDB_REGISTER_CONSTRUCTOR(SBProcessInfo, (const lldb::SBProcessInfo &)); + LLDB_REGISTER_METHOD( + lldb::SBProcessInfo &, + SBProcessInfo, operator=,(const lldb::SBProcessInfo &)); + LLDB_REGISTER_METHOD_CONST(bool, SBProcessInfo, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBProcessInfo, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBProcessInfo, GetName, ()); + LLDB_REGISTER_METHOD(lldb::SBFileSpec, SBProcessInfo, GetExecutableFile, + ()); + LLDB_REGISTER_METHOD(lldb::pid_t, SBProcessInfo, GetProcessID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBProcessInfo, GetUserID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBProcessInfo, GetGroupID, ()); + LLDB_REGISTER_METHOD(bool, SBProcessInfo, UserIDIsValid, ()); + LLDB_REGISTER_METHOD(bool, SBProcessInfo, GroupIDIsValid, ()); + LLDB_REGISTER_METHOD(uint32_t, SBProcessInfo, GetEffectiveUserID, ()); + LLDB_REGISTER_METHOD(uint32_t, SBProcessInfo, GetEffectiveGroupID, ()); + LLDB_REGISTER_METHOD(bool, SBProcessInfo, EffectiveUserIDIsValid, ()); + LLDB_REGISTER_METHOD(bool, SBProcessInfo, EffectiveGroupIDIsValid, ()); + LLDB_REGISTER_METHOD(lldb::pid_t, SBProcessInfo, GetParentProcessID, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBQueue.cpp b/src/llvm-project/lldb/source/API/SBQueue.cpp index b4a3cd0..7d1581c 100644 --- a/src/llvm-project/lldb/source/API/SBQueue.cpp +++ b/src/llvm-project/lldb/source/API/SBQueue.cpp
@@ -1,14 +1,14 @@ //===-- SBQueue.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <inttypes.h> +#include "SBReproducerPrivate.h" #include "lldb/API/SBQueue.h" #include "lldb/API/SBProcess.h" @@ -19,7 +19,6 @@ #include "lldb/Target/Queue.h" #include "lldb/Target/QueueItem.h" #include "lldb/Target/Thread.h" -#include "lldb/Utility/Log.h" using namespace lldb; using namespace lldb_private; @@ -50,7 +49,7 @@ ~QueueImpl() {} - bool IsValid() { return m_queue_wp.lock() != NULL; } + bool IsValid() { return m_queue_wp.lock() != nullptr; } void Clear() { m_queue_wp.reset(); @@ -71,10 +70,6 @@ if (queue_sp) { result = queue_sp->GetID(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(%p)::GetQueueID () => 0x%" PRIx64, - static_cast<const void *>(this), result); return result; } @@ -84,25 +79,15 @@ if (queue_sp) { result = queue_sp->GetIndexID(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueueImpl(%p)::GetIndexID () => %d", - static_cast<const void *>(this), result); return result; } const char *GetName() const { - const char *name = NULL; + const char *name = nullptr; lldb::QueueSP queue_sp = m_queue_wp.lock(); if (queue_sp.get()) { name = queue_sp->GetName(); } - - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueueImpl(%p)::GetName () => %s", - static_cast<const void *>(this), name ? name : "NULL"); - return name; } @@ -232,12 +217,18 @@ }; } -SBQueue::SBQueue() : m_opaque_sp(new QueueImpl()) {} +SBQueue::SBQueue() : m_opaque_sp(new QueueImpl()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBQueue); +} SBQueue::SBQueue(const QueueSP &queue_sp) - : m_opaque_sp(new QueueImpl(queue_sp)) {} + : m_opaque_sp(new QueueImpl(queue_sp)) { + LLDB_RECORD_CONSTRUCTOR(SBQueue, (const lldb::QueueSP &), queue_sp); +} SBQueue::SBQueue(const SBQueue &rhs) { + LLDB_RECORD_CONSTRUCTOR(SBQueue, (const lldb::SBQueue &), rhs); + if (&rhs == this) return; @@ -245,25 +236,28 @@ } const lldb::SBQueue &SBQueue::operator=(const lldb::SBQueue &rhs) { + LLDB_RECORD_METHOD(const lldb::SBQueue &, + SBQueue, operator=,(const lldb::SBQueue &), rhs); + m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBQueue::~SBQueue() {} bool SBQueue::IsValid() const { - bool is_valid = m_opaque_sp->IsValid(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::IsValid() == %s", - m_opaque_sp->GetQueueID(), is_valid ? "true" : "false"); - return is_valid; + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBQueue, IsValid); + return this->operator bool(); +} +SBQueue::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBQueue, operator bool); + + return m_opaque_sp->IsValid(); } void SBQueue::Clear() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::Clear()", m_opaque_sp->GetQueueID()); + LLDB_RECORD_METHOD_NO_ARGS(void, SBQueue, Clear); + m_opaque_sp->Clear(); } @@ -272,76 +266,94 @@ } lldb::queue_id_t SBQueue::GetQueueID() const { - lldb::queue_id_t qid = m_opaque_sp->GetQueueID(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetQueueID() == 0x%" PRIx64, - m_opaque_sp->GetQueueID(), (uint64_t)qid); - return qid; + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::queue_id_t, SBQueue, GetQueueID); + + return m_opaque_sp->GetQueueID(); } uint32_t SBQueue::GetIndexID() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBQueue, GetIndexID); + uint32_t index_id = m_opaque_sp->GetIndexID(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetIndexID() == 0x%" PRIx32, - m_opaque_sp->GetQueueID(), index_id); return index_id; } const char *SBQueue::GetName() const { - const char *name = m_opaque_sp->GetName(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetName() == %s", - m_opaque_sp->GetQueueID(), name ? name : ""); - return name; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBQueue, GetName); + + return m_opaque_sp->GetName(); } uint32_t SBQueue::GetNumThreads() { - uint32_t numthreads = m_opaque_sp->GetNumThreads(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetNumThreads() == %d", - m_opaque_sp->GetQueueID(), numthreads); - return numthreads; + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBQueue, GetNumThreads); + + return m_opaque_sp->GetNumThreads(); } SBThread SBQueue::GetThreadAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBThread, SBQueue, GetThreadAtIndex, (uint32_t), + idx); + SBThread th = m_opaque_sp->GetThreadAtIndex(idx); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetThreadAtIndex(%d)", - m_opaque_sp->GetQueueID(), idx); - return th; + return LLDB_RECORD_RESULT(th); } uint32_t SBQueue::GetNumPendingItems() { - uint32_t pending_items = m_opaque_sp->GetNumPendingItems(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetNumPendingItems() == %d", - m_opaque_sp->GetQueueID(), pending_items); - return pending_items; + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBQueue, GetNumPendingItems); + + return m_opaque_sp->GetNumPendingItems(); } SBQueueItem SBQueue::GetPendingItemAtIndex(uint32_t idx) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetPendingItemAtIndex(%d)", - m_opaque_sp->GetQueueID(), idx); - return m_opaque_sp->GetPendingItemAtIndex(idx); + LLDB_RECORD_METHOD(lldb::SBQueueItem, SBQueue, GetPendingItemAtIndex, + (uint32_t), idx); + + return LLDB_RECORD_RESULT(m_opaque_sp->GetPendingItemAtIndex(idx)); } uint32_t SBQueue::GetNumRunningItems() { - uint32_t running_items = m_opaque_sp->GetNumRunningItems(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetNumRunningItems() == %d", - m_opaque_sp->GetQueueID(), running_items); - return running_items; + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBQueue, GetNumRunningItems); + + return m_opaque_sp->GetNumRunningItems(); } -SBProcess SBQueue::GetProcess() { return m_opaque_sp->GetProcess(); } +SBProcess SBQueue::GetProcess() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBProcess, SBQueue, GetProcess); -lldb::QueueKind SBQueue::GetKind() { return m_opaque_sp->GetKind(); } + return LLDB_RECORD_RESULT(m_opaque_sp->GetProcess()); +} + +lldb::QueueKind SBQueue::GetKind() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::QueueKind, SBQueue, GetKind); + + return m_opaque_sp->GetKind(); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBQueue>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBQueue, ()); + LLDB_REGISTER_CONSTRUCTOR(SBQueue, (const lldb::QueueSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBQueue, (const lldb::SBQueue &)); + LLDB_REGISTER_METHOD(const lldb::SBQueue &, + SBQueue, operator=,(const lldb::SBQueue &)); + LLDB_REGISTER_METHOD_CONST(bool, SBQueue, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBQueue, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBQueue, Clear, ()); + LLDB_REGISTER_METHOD_CONST(lldb::queue_id_t, SBQueue, GetQueueID, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBQueue, GetIndexID, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBQueue, GetName, ()); + LLDB_REGISTER_METHOD(uint32_t, SBQueue, GetNumThreads, ()); + LLDB_REGISTER_METHOD(lldb::SBThread, SBQueue, GetThreadAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBQueue, GetNumPendingItems, ()); + LLDB_REGISTER_METHOD(lldb::SBQueueItem, SBQueue, GetPendingItemAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBQueue, GetNumRunningItems, ()); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBQueue, GetProcess, ()); + LLDB_REGISTER_METHOD(lldb::QueueKind, SBQueue, GetKind, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBQueueItem.cpp b/src/llvm-project/lldb/source/API/SBQueueItem.cpp index aac5844..5f2cbd1 100644 --- a/src/llvm-project/lldb/source/API/SBQueueItem.cpp +++ b/src/llvm-project/lldb/source/API/SBQueueItem.cpp
@@ -1,14 +1,14 @@ //===-- SBQueueItem.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBQueueItem.h" #include "lldb/API/SBThread.h" @@ -16,93 +16,88 @@ #include "lldb/Target/Process.h" #include "lldb/Target/QueueItem.h" #include "lldb/Target/Thread.h" -#include "lldb/Utility/Log.h" using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Constructors -//---------------------------------------------------------------------- -SBQueueItem::SBQueueItem() : m_queue_item_sp() {} +SBQueueItem::SBQueueItem() : m_queue_item_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBQueueItem); +} SBQueueItem::SBQueueItem(const QueueItemSP &queue_item_sp) - : m_queue_item_sp(queue_item_sp) {} + : m_queue_item_sp(queue_item_sp) { + LLDB_RECORD_CONSTRUCTOR(SBQueueItem, (const lldb::QueueItemSP &), + queue_item_sp); +} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SBQueueItem::~SBQueueItem() { m_queue_item_sp.reset(); } bool SBQueueItem::IsValid() const { - bool is_valid = m_queue_item_sp.get() != NULL; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueueItem(%p)::IsValid() == %s", - static_cast<void *>(m_queue_item_sp.get()), - is_valid ? "true" : "false"); - return is_valid; + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBQueueItem, IsValid); + return this->operator bool(); +} +SBQueueItem::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBQueueItem, operator bool); + + return m_queue_item_sp.get() != nullptr; } void SBQueueItem::Clear() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueueItem(%p)::Clear()", - static_cast<void *>(m_queue_item_sp.get())); + LLDB_RECORD_METHOD_NO_ARGS(void, SBQueueItem, Clear); + m_queue_item_sp.reset(); } void SBQueueItem::SetQueueItem(const QueueItemSP &queue_item_sp) { + LLDB_RECORD_METHOD(void, SBQueueItem, SetQueueItem, + (const lldb::QueueItemSP &), queue_item_sp); + m_queue_item_sp = queue_item_sp; } lldb::QueueItemKind SBQueueItem::GetKind() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::QueueItemKind, SBQueueItem, GetKind); + QueueItemKind result = eQueueItemKindUnknown; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (m_queue_item_sp) { result = m_queue_item_sp->GetKind(); } - if (log) - log->Printf("SBQueueItem(%p)::GetKind() == %d", - static_cast<void *>(m_queue_item_sp.get()), - static_cast<int>(result)); return result; } void SBQueueItem::SetKind(lldb::QueueItemKind kind) { + LLDB_RECORD_METHOD(void, SBQueueItem, SetKind, (lldb::QueueItemKind), kind); + if (m_queue_item_sp) { m_queue_item_sp->SetKind(kind); } } SBAddress SBQueueItem::GetAddress() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBQueueItem, GetAddress); + SBAddress result; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (m_queue_item_sp) { result.SetAddress(&m_queue_item_sp->GetAddress()); } - if (log) { - StreamString sstr; - const Address *addr = result.get(); - if (addr) - addr->Dump(&sstr, NULL, Address::DumpStyleModuleWithFileAddress, - Address::DumpStyleInvalid, 4); - log->Printf("SBQueueItem(%p)::GetAddress() == SBAddress(%p): %s", - static_cast<void *>(m_queue_item_sp.get()), - static_cast<void *>(result.get()), sstr.GetData()); - } - return result; + return LLDB_RECORD_RESULT(result); } void SBQueueItem::SetAddress(SBAddress addr) { + LLDB_RECORD_METHOD(void, SBQueueItem, SetAddress, (lldb::SBAddress), addr); + if (m_queue_item_sp) { m_queue_item_sp->SetAddress(addr.ref()); } } SBThread SBQueueItem::GetExtendedBacktraceThread(const char *type) { + LLDB_RECORD_METHOD(lldb::SBThread, SBQueueItem, GetExtendedBacktraceThread, + (const char *), type); + SBThread result; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (m_queue_item_sp) { ProcessSP process_sp = m_queue_item_sp->GetProcessSP(); Process::StopLocker stop_locker; @@ -115,19 +110,31 @@ // retains the object process_sp->GetExtendedThreadList().AddThread(thread_sp); result.SetThread(thread_sp); - if (log) { - const char *queue_name = thread_sp->GetQueueName(); - if (queue_name == NULL) - queue_name = ""; - log->Printf( - "SBQueueItem(%p)::GetExtendedBacktraceThread() = new extended " - "Thread created (%p) with queue_id 0x%" PRIx64 " queue name '%s'", - static_cast<void *>(m_queue_item_sp.get()), - static_cast<void *>(thread_sp.get()), - static_cast<uint64_t>(thread_sp->GetQueueID()), queue_name); - } } } } - return result; + return LLDB_RECORD_RESULT(result); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBQueueItem>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBQueueItem, ()); + LLDB_REGISTER_CONSTRUCTOR(SBQueueItem, (const lldb::QueueItemSP &)); + LLDB_REGISTER_METHOD_CONST(bool, SBQueueItem, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBQueueItem, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBQueueItem, Clear, ()); + LLDB_REGISTER_METHOD(void, SBQueueItem, SetQueueItem, + (const lldb::QueueItemSP &)); + LLDB_REGISTER_METHOD_CONST(lldb::QueueItemKind, SBQueueItem, GetKind, ()); + LLDB_REGISTER_METHOD(void, SBQueueItem, SetKind, (lldb::QueueItemKind)); + LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBQueueItem, GetAddress, ()); + LLDB_REGISTER_METHOD(void, SBQueueItem, SetAddress, (lldb::SBAddress)); + LLDB_REGISTER_METHOD(lldb::SBThread, SBQueueItem, + GetExtendedBacktraceThread, (const char *)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBReproducer.cpp b/src/llvm-project/lldb/source/API/SBReproducer.cpp new file mode 100644 index 0000000..439ee5a --- /dev/null +++ b/src/llvm-project/lldb/source/API/SBReproducer.cpp
@@ -0,0 +1,153 @@ +//===-- SBReproducer.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 "SBReproducerPrivate.h" + +#include "SBReproducerPrivate.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/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/API/SBReproducer.h" + +#include "lldb/Host/FileSystem.h" + +using namespace lldb; +using namespace lldb_private; +using namespace lldb_private::repro; + +SBRegistry::SBRegistry() { + Registry& R = *this; + + RegisterMethods<SBAddress>(R); + RegisterMethods<SBAttachInfo>(R); + RegisterMethods<SBBlock>(R); + RegisterMethods<SBBreakpoint>(R); + RegisterMethods<SBBreakpointList>(R); + RegisterMethods<SBBreakpointLocation>(R); + RegisterMethods<SBBreakpointName>(R); + RegisterMethods<SBBroadcaster>(R); + RegisterMethods<SBCommandInterpreterRunOptions>(R); + RegisterMethods<SBCommandReturnObject>(R); + RegisterMethods<SBCommunication>(R); + RegisterMethods<SBCompileUnit>(R); + RegisterMethods<SBData>(R); + RegisterMethods<SBInputReader>(R); + RegisterMethods<SBDebugger>(R); + RegisterMethods<SBDeclaration>(R); + RegisterMethods<SBError>(R); + RegisterMethods<SBEvent>(R); + RegisterMethods<SBExecutionContext>(R); + RegisterMethods<SBExpressionOptions>(R); + RegisterMethods<SBFileSpec>(R); + RegisterMethods<SBFileSpecList>(R); + RegisterMethods<SBFrame>(R); + RegisterMethods<SBFunction>(R); + RegisterMethods<SBHostOS>(R); + RegisterMethods<SBInstruction>(R); + RegisterMethods<SBInstructionList>(R); + RegisterMethods<SBLanguageRuntime>(R); + RegisterMethods<SBLaunchInfo>(R); + RegisterMethods<SBLineEntry>(R); + RegisterMethods<SBListener>(R); + RegisterMethods<SBMemoryRegionInfo>(R); + RegisterMethods<SBMemoryRegionInfoList>(R); + RegisterMethods<SBModule>(R); + RegisterMethods<SBModuleSpec>(R); + RegisterMethods<SBPlatformConnectOptions>(R); + RegisterMethods<SBPlatformShellCommand>(R); + RegisterMethods<SBPlatform>(R); + RegisterMethods<SBProcess>(R); + RegisterMethods<SBProcessInfo>(R); + RegisterMethods<SBQueue>(R); + RegisterMethods<SBQueueItem>(R); + RegisterMethods<SBSection>(R); + RegisterMethods<SBSourceManager>(R); + RegisterMethods<SBStream>(R); + RegisterMethods<SBStringList>(R); + RegisterMethods<SBStructuredData>(R); + RegisterMethods<SBSymbol>(R); + RegisterMethods<SBSymbolContext>(R); + RegisterMethods<SBSymbolContextList>(R); + RegisterMethods<SBTarget>(R); + RegisterMethods<SBThread>(R); + RegisterMethods<SBThreadCollection>(R); + RegisterMethods<SBThreadPlan>(R); + RegisterMethods<SBTrace>(R); + RegisterMethods<SBTraceOptions>(R); + RegisterMethods<SBType>(R); + RegisterMethods<SBTypeCategory>(R); + RegisterMethods<SBTypeEnumMember>(R); + RegisterMethods<SBTypeFilter>(R); + RegisterMethods<SBTypeFormat>(R); + RegisterMethods<SBTypeNameSpecifier>(R); + RegisterMethods<SBTypeSummaryOptions>(R); + RegisterMethods<SBTypeSummary>(R); + RegisterMethods<SBTypeSynthetic>(R); + RegisterMethods<SBUnixSignals>(R); + RegisterMethods<SBValue>(R); + RegisterMethods<SBValueList>(R); + RegisterMethods<SBVariablesOptions>(R); + RegisterMethods<SBWatchpoint>(R); +} + +const char *SBReproducer::Capture() { + static std::string error; + if (auto e = Reproducer::Initialize(ReproducerMode::Capture, llvm::None)) { + error = llvm::toString(std::move(e)); + return error.c_str(); + } + return nullptr; +} + +const char *SBReproducer::Capture(const char *path) { + static std::string error; + if (auto e = + Reproducer::Initialize(ReproducerMode::Capture, FileSpec(path))) { + error = llvm::toString(std::move(e)); + return error.c_str(); + } + return nullptr; +} + +const char *SBReproducer::Replay(const char *path) { + static std::string error; + if (auto e = Reproducer::Initialize(ReproducerMode::Replay, FileSpec(path))) { + error = llvm::toString(std::move(e)); + return error.c_str(); + } + + repro::Loader *loader = repro::Reproducer::Instance().GetLoader(); + if (!loader) { + error = "unable to get replay loader."; + return error.c_str(); + } + + FileSpec file = loader->GetFile<SBProvider::Info>(); + if (!file) { + error = "unable to get replay data from reproducer."; + return error.c_str(); + } + + SBRegistry registry; + registry.Replay(file); + + return nullptr; +} + +char lldb_private::repro::SBProvider::ID = 0; +const char *SBProvider::Info::name = "sbapi"; +const char *SBProvider::Info::file = "sbapi.bin";
diff --git a/src/llvm-project/lldb/source/API/SBReproducerPrivate.h b/src/llvm-project/lldb/source/API/SBReproducerPrivate.h new file mode 100644 index 0000000..84b6ce9 --- /dev/null +++ b/src/llvm-project/lldb/source/API/SBReproducerPrivate.h
@@ -0,0 +1,75 @@ +//===-- SBReproducerPrivate.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_API_SBREPRODUCER_PRIVATE_H +#define LLDB_API_SBREPRODUCER_PRIVATE_H + +#include "lldb/API/SBReproducer.h" + +#include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Log.h" +#include "lldb/Utility/Reproducer.h" +#include "lldb/Utility/ReproducerInstrumentation.h" + +#include "llvm/ADT/DenseMap.h" + +#define LLDB_GET_INSTRUMENTATION_DATA() \ + lldb_private::repro::GetInstrumentationData() + +namespace lldb_private { +namespace repro { + +class SBRegistry : public Registry { +public: + SBRegistry(); +}; + +class SBProvider : public Provider<SBProvider> { +public: + struct Info { + static const char *name; + static const char *file; + }; + + SBProvider(const FileSpec &directory) + : Provider(directory), + m_stream(directory.CopyByAppendingPathComponent("sbapi.bin").GetPath(), + m_ec, llvm::sys::fs::OpenFlags::F_None), + m_serializer(m_stream) {} + + Serializer &GetSerializer() { return m_serializer; } + Registry &GetRegistry() { return m_registry; } + + static char ID; + +private: + std::error_code m_ec; + llvm::raw_fd_ostream m_stream; + Serializer m_serializer; + SBRegistry m_registry; +}; + +inline InstrumentationData GetInstrumentationData() { + if (!lldb_private::repro::Reproducer::Initialized()) + return {}; + + if (auto *g = lldb_private::repro::Reproducer::Instance().GetGenerator()) { + auto &p = g->GetOrCreate<SBProvider>(); + return {p.GetSerializer(), p.GetRegistry()}; + } + + return {}; +} + +template <typename T> void RegisterMethods(Registry &R); + +} // namespace repro +} // namespace lldb_private + +#endif
diff --git a/src/llvm-project/lldb/source/API/SBSection.cpp b/src/llvm-project/lldb/source/API/SBSection.cpp index 7193857..14e1e14 100644 --- a/src/llvm-project/lldb/source/API/SBSection.cpp +++ b/src/llvm-project/lldb/source/API/SBSection.cpp
@@ -1,13 +1,13 @@ //===-- SBSection.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBTarget.h" #include "lldb/Core/Module.h" @@ -15,15 +15,18 @@ #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/DataBuffer.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" using namespace lldb; using namespace lldb_private; -SBSection::SBSection() : m_opaque_wp() {} +SBSection::SBSection() : m_opaque_wp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBSection); +} -SBSection::SBSection(const SBSection &rhs) : m_opaque_wp(rhs.m_opaque_wp) {} +SBSection::SBSection(const SBSection &rhs) : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_RECORD_CONSTRUCTOR(SBSection, (const lldb::SBSection &), rhs); +} SBSection::SBSection(const lldb::SectionSP §ion_sp) : m_opaque_wp() // Don't init with section_sp otherwise this will throw if @@ -34,25 +37,38 @@ } const SBSection &SBSection::operator=(const SBSection &rhs) { + LLDB_RECORD_METHOD(const lldb::SBSection &, + SBSection, operator=,(const lldb::SBSection &), rhs); + m_opaque_wp = rhs.m_opaque_wp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBSection::~SBSection() {} bool SBSection::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSection, IsValid); + return this->operator bool(); +} +SBSection::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSection, operator bool); + SectionSP section_sp(GetSP()); - return section_sp && section_sp->GetModule().get() != NULL; + return section_sp && section_sp->GetModule().get() != nullptr; } const char *SBSection::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBSection, GetName); + SectionSP section_sp(GetSP()); if (section_sp) return section_sp->GetName().GetCString(); - return NULL; + return nullptr; } lldb::SBSection SBSection::GetParent() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSection, SBSection, GetParent); + lldb::SBSection sb_section; SectionSP section_sp(GetSP()); if (section_sp) { @@ -60,10 +76,13 @@ if (parent_section_sp) sb_section.SetSP(parent_section_sp); } - return sb_section; + return LLDB_RECORD_RESULT(sb_section); } lldb::SBSection SBSection::FindSubSection(const char *sect_name) { + LLDB_RECORD_METHOD(lldb::SBSection, SBSection, FindSubSection, (const char *), + sect_name); + lldb::SBSection sb_section; if (sect_name) { SectionSP section_sp(GetSP()); @@ -73,10 +92,12 @@ section_sp->GetChildren().FindSectionByName(const_sect_name)); } } - return sb_section; + return LLDB_RECORD_RESULT(sb_section); } size_t SBSection::GetNumSubSections() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBSection, GetNumSubSections); + SectionSP section_sp(GetSP()); if (section_sp) return section_sp->GetChildren().GetSize(); @@ -84,11 +105,14 @@ } lldb::SBSection SBSection::GetSubSectionAtIndex(size_t idx) { + LLDB_RECORD_METHOD(lldb::SBSection, SBSection, GetSubSectionAtIndex, (size_t), + idx); + lldb::SBSection sb_section; SectionSP section_sp(GetSP()); if (section_sp) sb_section.SetSP(section_sp->GetChildren().GetSectionAtIndex(idx)); - return sb_section; + return LLDB_RECORD_RESULT(sb_section); } lldb::SectionSP SBSection::GetSP() const { return m_opaque_wp.lock(); } @@ -98,6 +122,8 @@ } lldb::addr_t SBSection::GetFileAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBSection, GetFileAddress); + lldb::addr_t file_addr = LLDB_INVALID_ADDRESS; SectionSP section_sp(GetSP()); if (section_sp) @@ -106,6 +132,9 @@ } lldb::addr_t SBSection::GetLoadAddress(lldb::SBTarget &sb_target) { + LLDB_RECORD_METHOD(lldb::addr_t, SBSection, GetLoadAddress, + (lldb::SBTarget &), sb_target); + TargetSP target_sp(sb_target.GetSP()); if (target_sp) { SectionSP section_sp(GetSP()); @@ -116,6 +145,8 @@ } lldb::addr_t SBSection::GetByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBSection, GetByteSize); + SectionSP section_sp(GetSP()); if (section_sp) return section_sp->GetByteSize(); @@ -123,6 +154,8 @@ } uint64_t SBSection::GetFileOffset() { + LLDB_RECORD_METHOD_NO_ARGS(uint64_t, SBSection, GetFileOffset); + SectionSP section_sp(GetSP()); if (section_sp) { ModuleSP module_sp(section_sp->GetModule()); @@ -136,15 +169,24 @@ } uint64_t SBSection::GetFileByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint64_t, SBSection, GetFileByteSize); + SectionSP section_sp(GetSP()); if (section_sp) return section_sp->GetFileSize(); return 0; } -SBData SBSection::GetSectionData() { return GetSectionData(0, UINT64_MAX); } +SBData SBSection::GetSectionData() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBData, SBSection, GetSectionData); + + return LLDB_RECORD_RESULT(GetSectionData(0, UINT64_MAX)); +} SBData SBSection::GetSectionData(uint64_t offset, uint64_t size) { + LLDB_RECORD_METHOD(lldb::SBData, SBSection, GetSectionData, + (uint64_t, uint64_t), offset, size); + SBData sb_data; SectionSP section_sp(GetSP()); if (section_sp) { @@ -178,26 +220,30 @@ } } } - return sb_data; + return LLDB_RECORD_RESULT(sb_data); } SectionType SBSection::GetSectionType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SectionType, SBSection, GetSectionType); + SectionSP section_sp(GetSP()); if (section_sp.get()) return section_sp->GetType(); return eSectionTypeInvalid; } -uint32_t -SBSection::GetPermissions() const -{ - SectionSP section_sp(GetSP()); - if (section_sp) - return section_sp->GetPermissions(); - return 0; +uint32_t SBSection::GetPermissions() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBSection, GetPermissions); + + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetPermissions(); + return 0; } uint32_t SBSection::GetTargetByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBSection, GetTargetByteSize); + SectionSP section_sp(GetSP()); if (section_sp.get()) return section_sp->GetTargetByteSize(); @@ -205,6 +251,9 @@ } bool SBSection::operator==(const SBSection &rhs) { + LLDB_RECORD_METHOD(bool, SBSection, operator==,(const lldb::SBSection &), + rhs); + SectionSP lhs_section_sp(GetSP()); SectionSP rhs_section_sp(rhs.GetSP()); if (lhs_section_sp && rhs_section_sp) @@ -213,12 +262,18 @@ } bool SBSection::operator!=(const SBSection &rhs) { + LLDB_RECORD_METHOD(bool, SBSection, operator!=,(const lldb::SBSection &), + 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_RECORD_METHOD(bool, SBSection, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); SectionSP section_sp(GetSP()); @@ -233,3 +288,41 @@ return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBSection>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBSection, ()); + LLDB_REGISTER_CONSTRUCTOR(SBSection, (const lldb::SBSection &)); + LLDB_REGISTER_METHOD(const lldb::SBSection &, + SBSection, operator=,(const lldb::SBSection &)); + LLDB_REGISTER_METHOD_CONST(bool, SBSection, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBSection, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBSection, GetName, ()); + LLDB_REGISTER_METHOD(lldb::SBSection, SBSection, GetParent, ()); + LLDB_REGISTER_METHOD(lldb::SBSection, SBSection, FindSubSection, + (const char *)); + LLDB_REGISTER_METHOD(size_t, SBSection, GetNumSubSections, ()); + LLDB_REGISTER_METHOD(lldb::SBSection, SBSection, GetSubSectionAtIndex, + (size_t)); + LLDB_REGISTER_METHOD(lldb::addr_t, SBSection, GetFileAddress, ()); + LLDB_REGISTER_METHOD(lldb::addr_t, SBSection, GetLoadAddress, + (lldb::SBTarget &)); + LLDB_REGISTER_METHOD(lldb::addr_t, SBSection, GetByteSize, ()); + LLDB_REGISTER_METHOD(uint64_t, SBSection, GetFileOffset, ()); + LLDB_REGISTER_METHOD(uint64_t, SBSection, GetFileByteSize, ()); + LLDB_REGISTER_METHOD(lldb::SBData, SBSection, GetSectionData, ()); + LLDB_REGISTER_METHOD(lldb::SBData, SBSection, GetSectionData, + (uint64_t, uint64_t)); + LLDB_REGISTER_METHOD(lldb::SectionType, SBSection, GetSectionType, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBSection, GetPermissions, ()); + LLDB_REGISTER_METHOD(uint32_t, SBSection, GetTargetByteSize, ()); + LLDB_REGISTER_METHOD(bool, SBSection, operator==,(const lldb::SBSection &)); + LLDB_REGISTER_METHOD(bool, SBSection, operator!=,(const lldb::SBSection &)); + LLDB_REGISTER_METHOD(bool, SBSection, GetDescription, (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBSourceManager.cpp b/src/llvm-project/lldb/source/API/SBSourceManager.cpp index 1d47cc0..9c4ce3c 100644 --- a/src/llvm-project/lldb/source/API/SBSourceManager.cpp +++ b/src/llvm-project/lldb/source/API/SBSourceManager.cpp
@@ -1,13 +1,13 @@ //===-- SBSourceManager.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBTarget.h" @@ -72,24 +72,36 @@ using namespace lldb_private; SBSourceManager::SBSourceManager(const SBDebugger &debugger) { - m_opaque_ap.reset(new SourceManagerImpl(debugger.get_sp())); + LLDB_RECORD_CONSTRUCTOR(SBSourceManager, (const lldb::SBDebugger &), + debugger); + + m_opaque_up.reset(new SourceManagerImpl(debugger.get_sp())); } SBSourceManager::SBSourceManager(const SBTarget &target) { - m_opaque_ap.reset(new SourceManagerImpl(target.GetSP())); + LLDB_RECORD_CONSTRUCTOR(SBSourceManager, (const lldb::SBTarget &), target); + + m_opaque_up.reset(new SourceManagerImpl(target.GetSP())); } SBSourceManager::SBSourceManager(const SBSourceManager &rhs) { + LLDB_RECORD_CONSTRUCTOR(SBSourceManager, (const lldb::SBSourceManager &), + rhs); + if (&rhs == this) return; - m_opaque_ap.reset(new SourceManagerImpl(*(rhs.m_opaque_ap.get()))); + m_opaque_up.reset(new SourceManagerImpl(*(rhs.m_opaque_up.get()))); } const lldb::SBSourceManager &SBSourceManager:: operator=(const lldb::SBSourceManager &rhs) { - m_opaque_ap.reset(new SourceManagerImpl(*(rhs.m_opaque_ap.get()))); - return *this; + LLDB_RECORD_METHOD(const lldb::SBSourceManager &, + SBSourceManager, operator=,(const lldb::SBSourceManager &), + rhs); + + m_opaque_up.reset(new SourceManagerImpl(*(rhs.m_opaque_up.get()))); + return LLDB_RECORD_RESULT(*this); } SBSourceManager::~SBSourceManager() {} @@ -97,6 +109,12 @@ 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_RECORD_METHOD(size_t, SBSourceManager, DisplaySourceLinesWithLineNumbers, + (const lldb::SBFileSpec &, uint32_t, uint32_t, uint32_t, + const char *, lldb::SBStream &), + 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, @@ -107,10 +125,40 @@ const SBFileSpec &file, uint32_t line, uint32_t column, uint32_t context_before, uint32_t context_after, const char *current_line_cstr, SBStream &s) { - if (m_opaque_ap == NULL) + LLDB_RECORD_METHOD( + size_t, SBSourceManager, DisplaySourceLinesWithLineNumbersAndColumn, + (const lldb::SBFileSpec &, uint32_t, uint32_t, uint32_t, uint32_t, + const char *, lldb::SBStream &), + file, line, column, context_before, context_after, current_line_cstr, s); + + if (m_opaque_up == nullptr) return 0; - return m_opaque_ap->DisplaySourceLinesWithLineNumbers( + return m_opaque_up->DisplaySourceLinesWithLineNumbers( file.ref(), line, column, context_before, context_after, current_line_cstr, s.get()); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBSourceManager>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBSourceManager, (const lldb::SBDebugger &)); + LLDB_REGISTER_CONSTRUCTOR(SBSourceManager, (const lldb::SBTarget &)); + LLDB_REGISTER_CONSTRUCTOR(SBSourceManager, (const lldb::SBSourceManager &)); + LLDB_REGISTER_METHOD( + const lldb::SBSourceManager &, + SBSourceManager, operator=,(const lldb::SBSourceManager &)); + LLDB_REGISTER_METHOD(size_t, SBSourceManager, + DisplaySourceLinesWithLineNumbers, + (const lldb::SBFileSpec &, uint32_t, uint32_t, + uint32_t, const char *, lldb::SBStream &)); + LLDB_REGISTER_METHOD(size_t, SBSourceManager, + DisplaySourceLinesWithLineNumbersAndColumn, + (const lldb::SBFileSpec &, uint32_t, uint32_t, + uint32_t, uint32_t, const char *, lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBStream.cpp b/src/llvm-project/lldb/source/API/SBStream.cpp index 876ef02..ae65233 100644 --- a/src/llvm-project/lldb/source/API/SBStream.cpp +++ b/src/llvm-project/lldb/source/API/SBStream.cpp
@@ -1,14 +1,14 @@ //===-- SBStream.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/Core/StreamFile.h" #include "lldb/Host/FileSystem.h" #include "lldb/Utility/Status.h" @@ -18,31 +18,45 @@ using namespace lldb; using namespace lldb_private; -SBStream::SBStream() : m_opaque_ap(new StreamString()), m_is_file(false) {} +SBStream::SBStream() : m_opaque_up(new StreamString()), m_is_file(false) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBStream); +} SBStream::SBStream(SBStream &&rhs) - : m_opaque_ap(std::move(rhs.m_opaque_ap)), m_is_file(rhs.m_is_file) {} + : m_opaque_up(std::move(rhs.m_opaque_up)), m_is_file(rhs.m_is_file) {} SBStream::~SBStream() {} -bool SBStream::IsValid() const { return (m_opaque_ap != NULL); } +bool SBStream::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBStream, IsValid); + return this->operator bool(); +} +SBStream::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBStream, operator bool); + + 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() { - if (m_is_file || m_opaque_ap == NULL) - return NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBStream, GetData); - return static_cast<StreamString *>(m_opaque_ap.get())->GetData(); + if (m_is_file || m_opaque_up == nullptr) + return nullptr; + + return static_cast<StreamString *>(m_opaque_up.get())->GetData(); } // 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() { - if (m_is_file || m_opaque_ap == NULL) + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBStream, GetSize); + + if (m_is_file || m_opaque_up == nullptr) return 0; - return static_cast<StreamString *>(m_opaque_ap.get())->GetSize(); + return static_cast<StreamString *>(m_opaque_up.get())->GetSize(); } void SBStream::Printf(const char *format, ...) { @@ -55,15 +69,18 @@ } void SBStream::RedirectToFile(const char *path, bool append) { + LLDB_RECORD_METHOD(void, SBStream, RedirectToFile, (const char *, bool), path, + append); + if (path == nullptr) return; std::string local_data; - if (m_opaque_ap) { + 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 = static_cast<StreamString *>(m_opaque_ap.get())->GetString(); + local_data = static_cast<StreamString *>(m_opaque_up.get())->GetString(); } StreamFile *stream_file = new StreamFile; uint32_t open_options = File::eOpenOptionWrite | File::eOpenOptionCanCreate; @@ -74,81 +91,108 @@ FileSystem::Instance().Open(stream_file->GetFile(), FileSpec(path), open_options); - m_opaque_ap.reset(stream_file); + m_opaque_up.reset(stream_file); - if (m_opaque_ap) { + if (m_opaque_up) { 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_ap->Write(&local_data[0], local_data.size()); + m_opaque_up->Write(&local_data[0], local_data.size()); } else m_is_file = false; } void SBStream::RedirectToFileHandle(FILE *fh, bool transfer_fh_ownership) { + LLDB_RECORD_METHOD(void, SBStream, RedirectToFileHandle, (FILE *, bool), fh, + transfer_fh_ownership); + if (fh == nullptr) return; std::string local_data; - if (m_opaque_ap) { + 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 = static_cast<StreamString *>(m_opaque_ap.get())->GetString(); + local_data = static_cast<StreamString *>(m_opaque_up.get())->GetString(); } - m_opaque_ap.reset(new StreamFile(fh, transfer_fh_ownership)); + m_opaque_up.reset(new StreamFile(fh, transfer_fh_ownership)); - if (m_opaque_ap) { + if (m_opaque_up) { 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_ap->Write(&local_data[0], local_data.size()); + m_opaque_up->Write(&local_data[0], local_data.size()); } else m_is_file = false; } void SBStream::RedirectToFileDescriptor(int fd, bool transfer_fh_ownership) { + LLDB_RECORD_METHOD(void, SBStream, RedirectToFileDescriptor, (int, bool), fd, + transfer_fh_ownership); + std::string local_data; - if (m_opaque_ap) { + 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 = static_cast<StreamString *>(m_opaque_ap.get())->GetString(); + local_data = static_cast<StreamString *>(m_opaque_up.get())->GetString(); } - m_opaque_ap.reset(new StreamFile(::fdopen(fd, "w"), transfer_fh_ownership)); - if (m_opaque_ap) { + m_opaque_up.reset(new StreamFile(::fdopen(fd, "w"), transfer_fh_ownership)); + if (m_opaque_up) { 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_ap->Write(&local_data[0], local_data.size()); + m_opaque_up->Write(&local_data[0], local_data.size()); } else m_is_file = false; } -lldb_private::Stream *SBStream::operator->() { return m_opaque_ap.get(); } +lldb_private::Stream *SBStream::operator->() { return m_opaque_up.get(); } -lldb_private::Stream *SBStream::get() { return m_opaque_ap.get(); } +lldb_private::Stream *SBStream::get() { return m_opaque_up.get(); } lldb_private::Stream &SBStream::ref() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new StreamString()); - return *m_opaque_ap; + if (m_opaque_up == nullptr) + m_opaque_up.reset(new StreamString()); + return *m_opaque_up; } void SBStream::Clear() { - if (m_opaque_ap) { + LLDB_RECORD_METHOD_NO_ARGS(void, SBStream, Clear); + + 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_ap.reset(); + m_opaque_up.reset(); else - static_cast<StreamString *>(m_opaque_ap.get())->Clear(); + static_cast<StreamString *>(m_opaque_up.get())->Clear(); } } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBStream>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBStream, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBStream, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBStream, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBStream, GetData, ()); + LLDB_REGISTER_METHOD(size_t, SBStream, GetSize, ()); + LLDB_REGISTER_METHOD(void, SBStream, RedirectToFile, (const char *, bool)); + LLDB_REGISTER_METHOD(void, SBStream, RedirectToFileHandle, (FILE *, bool)); + LLDB_REGISTER_METHOD(void, SBStream, RedirectToFileDescriptor, (int, bool)); + LLDB_REGISTER_METHOD(void, SBStream, Clear, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBStringList.cpp b/src/llvm-project/lldb/source/API/SBStringList.cpp index 6ed4d4b..2f8bd55 100644 --- a/src/llvm-project/lldb/source/API/SBStringList.cpp +++ b/src/llvm-project/lldb/source/API/SBStringList.cpp
@@ -1,109 +1,163 @@ //===-- SBStringList.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/Utility/StringList.h" using namespace lldb; using namespace lldb_private; -SBStringList::SBStringList() : m_opaque_ap() {} - -SBStringList::SBStringList(const lldb_private::StringList *lldb_strings_ptr) - : m_opaque_ap() { - if (lldb_strings_ptr) - m_opaque_ap.reset(new lldb_private::StringList(*lldb_strings_ptr)); +SBStringList::SBStringList() : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBStringList); } -SBStringList::SBStringList(const SBStringList &rhs) : m_opaque_ap() { - if (rhs.IsValid()) - m_opaque_ap.reset(new lldb_private::StringList(*rhs)); +SBStringList::SBStringList(const lldb_private::StringList *lldb_strings_ptr) + : m_opaque_up() { + if (lldb_strings_ptr) + m_opaque_up = llvm::make_unique<StringList>(*lldb_strings_ptr); +} + +SBStringList::SBStringList(const SBStringList &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBStringList, (const lldb::SBStringList &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } const SBStringList &SBStringList::operator=(const SBStringList &rhs) { - if (this != &rhs) { - if (rhs.IsValid()) - m_opaque_ap.reset(new lldb_private::StringList(*rhs)); - else - m_opaque_ap.reset(); - } - return *this; + LLDB_RECORD_METHOD(const lldb::SBStringList &, + SBStringList, operator=,(const lldb::SBStringList &), rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } SBStringList::~SBStringList() {} const lldb_private::StringList *SBStringList::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const lldb_private::StringList &SBStringList::operator*() const { - return *m_opaque_ap; + return *m_opaque_up; } -bool SBStringList::IsValid() const { return (m_opaque_ap != NULL); } +bool SBStringList::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBStringList, IsValid); + return this->operator bool(); +} +SBStringList::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBStringList, operator bool); + + return (m_opaque_up != nullptr); +} void SBStringList::AppendString(const char *str) { - if (str != NULL) { + LLDB_RECORD_METHOD(void, SBStringList, AppendString, (const char *), str); + + if (str != nullptr) { if (IsValid()) - m_opaque_ap->AppendString(str); + m_opaque_up->AppendString(str); else - m_opaque_ap.reset(new lldb_private::StringList(str)); + m_opaque_up.reset(new lldb_private::StringList(str)); } } void SBStringList::AppendList(const char **strv, int strc) { - if ((strv != NULL) && (strc > 0)) { + LLDB_RECORD_METHOD(void, SBStringList, AppendList, (const char **, int), strv, + strc); + + if ((strv != nullptr) && (strc > 0)) { if (IsValid()) - m_opaque_ap->AppendList(strv, strc); + m_opaque_up->AppendList(strv, strc); else - m_opaque_ap.reset(new lldb_private::StringList(strv, strc)); + m_opaque_up.reset(new lldb_private::StringList(strv, strc)); } } void SBStringList::AppendList(const SBStringList &strings) { + LLDB_RECORD_METHOD(void, SBStringList, AppendList, + (const lldb::SBStringList &), strings); + if (strings.IsValid()) { if (!IsValid()) - m_opaque_ap.reset(new lldb_private::StringList()); - m_opaque_ap->AppendList(*(strings.m_opaque_ap)); + m_opaque_up.reset(new lldb_private::StringList()); + m_opaque_up->AppendList(*(strings.m_opaque_up)); } } void SBStringList::AppendList(const StringList &strings) { if (!IsValid()) - m_opaque_ap.reset(new lldb_private::StringList()); - m_opaque_ap->AppendList(strings); + m_opaque_up.reset(new lldb_private::StringList()); + m_opaque_up->AppendList(strings); } uint32_t SBStringList::GetSize() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBStringList, GetSize); + if (IsValid()) { - return m_opaque_ap->GetSize(); + return m_opaque_up->GetSize(); } return 0; } const char *SBStringList::GetStringAtIndex(size_t idx) { + LLDB_RECORD_METHOD(const char *, SBStringList, GetStringAtIndex, (size_t), + idx); + if (IsValid()) { - return m_opaque_ap->GetStringAtIndex(idx); + return m_opaque_up->GetStringAtIndex(idx); } - return NULL; + return nullptr; } const char *SBStringList::GetStringAtIndex(size_t idx) const { + LLDB_RECORD_METHOD_CONST(const char *, SBStringList, GetStringAtIndex, + (size_t), idx); + if (IsValid()) { - return m_opaque_ap->GetStringAtIndex(idx); + return m_opaque_up->GetStringAtIndex(idx); } - return NULL; + return nullptr; } void SBStringList::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBStringList, Clear); + if (IsValid()) { - m_opaque_ap->Clear(); + m_opaque_up->Clear(); } } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBStringList>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBStringList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBStringList, (const lldb::SBStringList &)); + LLDB_REGISTER_METHOD(const lldb::SBStringList &, + SBStringList, operator=,(const lldb::SBStringList &)); + LLDB_REGISTER_METHOD_CONST(bool, SBStringList, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBStringList, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBStringList, AppendString, (const char *)); + LLDB_REGISTER_METHOD(void, SBStringList, AppendList, (const char **, int)); + LLDB_REGISTER_METHOD(void, SBStringList, AppendList, + (const lldb::SBStringList &)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBStringList, GetSize, ()); + LLDB_REGISTER_METHOD(const char *, SBStringList, GetStringAtIndex, + (size_t)); + LLDB_REGISTER_METHOD_CONST(const char *, SBStringList, GetStringAtIndex, + (size_t)); + LLDB_REGISTER_METHOD(void, SBStringList, Clear, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBStructuredData.cpp b/src/llvm-project/lldb/source/API/SBStructuredData.cpp index 2771934..6b973e8 100644 --- a/src/llvm-project/lldb/source/API/SBStructuredData.cpp +++ b/src/llvm-project/lldb/source/API/SBStructuredData.cpp
@@ -1,13 +1,13 @@ //===-- SBStructuredData.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBStringList.h" @@ -24,26 +24,43 @@ #pragma mark-- #pragma mark SBStructuredData -SBStructuredData::SBStructuredData() : m_impl_up(new StructuredDataImpl()) {} +SBStructuredData::SBStructuredData() : m_impl_up(new StructuredDataImpl()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBStructuredData); +} SBStructuredData::SBStructuredData(const lldb::SBStructuredData &rhs) - : m_impl_up(new StructuredDataImpl(*rhs.m_impl_up.get())) {} + : m_impl_up(new StructuredDataImpl(*rhs.m_impl_up.get())) { + LLDB_RECORD_CONSTRUCTOR(SBStructuredData, (const lldb::SBStructuredData &), + rhs); +} SBStructuredData::SBStructuredData(const lldb::EventSP &event_sp) - : m_impl_up(new StructuredDataImpl(event_sp)) {} + : m_impl_up(new StructuredDataImpl(event_sp)) { + LLDB_RECORD_CONSTRUCTOR(SBStructuredData, (const lldb::EventSP &), event_sp); +} SBStructuredData::SBStructuredData(lldb_private::StructuredDataImpl *impl) - : m_impl_up(impl) {} + : m_impl_up(impl) { + LLDB_RECORD_CONSTRUCTOR(SBStructuredData, + (lldb_private::StructuredDataImpl *), impl); +} SBStructuredData::~SBStructuredData() {} SBStructuredData &SBStructuredData:: operator=(const lldb::SBStructuredData &rhs) { + LLDB_RECORD_METHOD( + lldb::SBStructuredData &, + SBStructuredData, operator=,(const lldb::SBStructuredData &), rhs); + *m_impl_up = *rhs.m_impl_up; - return *this; + return LLDB_RECORD_RESULT(*this); } lldb::SBError SBStructuredData::SetFromJSON(lldb::SBStream &stream) { + LLDB_RECORD_METHOD(lldb::SBError, SBStructuredData, SetFromJSON, + (lldb::SBStream &), stream); + lldb::SBError error; std::string json_str(stream.GetData()); @@ -52,35 +69,61 @@ if (!json_obj || json_obj->GetType() != eStructuredDataTypeDictionary) error.SetErrorString("Invalid Syntax"); - return error; + return LLDB_RECORD_RESULT(error); } -bool SBStructuredData::IsValid() const { return m_impl_up->IsValid(); } +bool SBStructuredData::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBStructuredData, IsValid); + return this->operator bool(); +} +SBStructuredData::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBStructuredData, operator bool); -void SBStructuredData::Clear() { m_impl_up->Clear(); } + return m_impl_up->IsValid(); +} + +void SBStructuredData::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBStructuredData, Clear); + + m_impl_up->Clear(); +} SBError SBStructuredData::GetAsJSON(lldb::SBStream &stream) const { + LLDB_RECORD_METHOD_CONST(lldb::SBError, SBStructuredData, GetAsJSON, + (lldb::SBStream &), stream); + SBError error; error.SetError(m_impl_up->GetAsJSON(stream.ref())); - return error; + return LLDB_RECORD_RESULT(error); } lldb::SBError SBStructuredData::GetDescription(lldb::SBStream &stream) const { + LLDB_RECORD_METHOD_CONST(lldb::SBError, SBStructuredData, GetDescription, + (lldb::SBStream &), stream); + Status error = m_impl_up->GetDescription(stream.ref()); SBError sb_error; sb_error.SetError(error); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } StructuredDataType SBStructuredData::GetType() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::StructuredDataType, SBStructuredData, + GetType); + return (m_impl_up ? m_impl_up->GetType() : eStructuredDataTypeInvalid); } size_t SBStructuredData::GetSize() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(size_t, SBStructuredData, GetSize); + return (m_impl_up ? m_impl_up->GetSize() : 0); } bool SBStructuredData::GetKeys(lldb::SBStringList &keys) const { + LLDB_RECORD_METHOD_CONST(bool, SBStructuredData, GetKeys, + (lldb::SBStringList &), keys); + if (!m_impl_up) return false; @@ -108,35 +151,97 @@ } lldb::SBStructuredData SBStructuredData::GetValueForKey(const char *key) const { + LLDB_RECORD_METHOD_CONST(lldb::SBStructuredData, SBStructuredData, + GetValueForKey, (const char *), key); + if (!m_impl_up) - return SBStructuredData(); + return LLDB_RECORD_RESULT(SBStructuredData()); SBStructuredData result; result.m_impl_up->SetObjectSP(m_impl_up->GetValueForKey(key)); - return result; + return LLDB_RECORD_RESULT(result); } lldb::SBStructuredData SBStructuredData::GetItemAtIndex(size_t idx) const { + LLDB_RECORD_METHOD_CONST(lldb::SBStructuredData, SBStructuredData, + GetItemAtIndex, (size_t), idx); + if (!m_impl_up) - return SBStructuredData(); + return LLDB_RECORD_RESULT(SBStructuredData()); SBStructuredData result; result.m_impl_up->SetObjectSP(m_impl_up->GetItemAtIndex(idx)); - return result; + return LLDB_RECORD_RESULT(result); } uint64_t SBStructuredData::GetIntegerValue(uint64_t fail_value) const { + LLDB_RECORD_METHOD_CONST(uint64_t, SBStructuredData, GetIntegerValue, + (uint64_t), fail_value); + return (m_impl_up ? m_impl_up->GetIntegerValue(fail_value) : fail_value); } double SBStructuredData::GetFloatValue(double fail_value) const { + LLDB_RECORD_METHOD_CONST(double, SBStructuredData, GetFloatValue, (double), + fail_value); + return (m_impl_up ? m_impl_up->GetFloatValue(fail_value) : fail_value); } bool SBStructuredData::GetBooleanValue(bool fail_value) const { + LLDB_RECORD_METHOD_CONST(bool, SBStructuredData, GetBooleanValue, (bool), + fail_value); + return (m_impl_up ? m_impl_up->GetBooleanValue(fail_value) : fail_value); } size_t SBStructuredData::GetStringValue(char *dst, size_t dst_len) const { + LLDB_RECORD_METHOD_CONST(size_t, SBStructuredData, GetStringValue, + (char *, size_t), dst, dst_len); + return (m_impl_up ? m_impl_up->GetStringValue(dst, dst_len) : 0); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBStructuredData>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBStructuredData, ()); + LLDB_REGISTER_CONSTRUCTOR(SBStructuredData, + (const lldb::SBStructuredData &)); + LLDB_REGISTER_CONSTRUCTOR(SBStructuredData, (const lldb::EventSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBStructuredData, + (lldb_private::StructuredDataImpl *)); + LLDB_REGISTER_METHOD( + lldb::SBStructuredData &, + SBStructuredData, operator=,(const lldb::SBStructuredData &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBStructuredData, SetFromJSON, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(bool, SBStructuredData, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBStructuredData, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBStructuredData, Clear, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBError, SBStructuredData, GetAsJSON, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBError, SBStructuredData, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(lldb::StructuredDataType, SBStructuredData, + GetType, ()); + LLDB_REGISTER_METHOD_CONST(size_t, SBStructuredData, GetSize, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBStructuredData, GetKeys, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBStructuredData, SBStructuredData, + GetValueForKey, (const char *)); + LLDB_REGISTER_METHOD_CONST(lldb::SBStructuredData, SBStructuredData, + GetItemAtIndex, (size_t)); + LLDB_REGISTER_METHOD_CONST(uint64_t, SBStructuredData, GetIntegerValue, + (uint64_t)); + LLDB_REGISTER_METHOD_CONST(double, SBStructuredData, GetFloatValue, + (double)); + LLDB_REGISTER_METHOD_CONST(bool, SBStructuredData, GetBooleanValue, (bool)); + LLDB_REGISTER_METHOD_CONST(size_t, SBStructuredData, GetStringValue, + (char *, size_t)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBSymbol.cpp b/src/llvm-project/lldb/source/API/SBSymbol.cpp index 5be20a1..6cc90e0 100644 --- a/src/llvm-project/lldb/source/API/SBSymbol.cpp +++ b/src/llvm-project/lldb/source/API/SBSymbol.cpp
@@ -1,96 +1,111 @@ //===-- SBSymbol.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.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/Log.h" using namespace lldb; using namespace lldb_private; -SBSymbol::SBSymbol() : m_opaque_ptr(NULL) {} +SBSymbol::SBSymbol() : m_opaque_ptr(nullptr) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBSymbol); +} 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) {} - -const SBSymbol &SBSymbol::operator=(const SBSymbol &rhs) { - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; +SBSymbol::SBSymbol(const lldb::SBSymbol &rhs) : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBSymbol, (const lldb::SBSymbol &), rhs); } -SBSymbol::~SBSymbol() { m_opaque_ptr = NULL; } +const SBSymbol &SBSymbol::operator=(const SBSymbol &rhs) { + LLDB_RECORD_METHOD(const lldb::SBSymbol &, + SBSymbol, operator=,(const lldb::SBSymbol &), rhs); + + m_opaque_ptr = rhs.m_opaque_ptr; + return LLDB_RECORD_RESULT(*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 { return m_opaque_ptr != NULL; } +bool SBSymbol::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSymbol, IsValid); + return this->operator bool(); +} +SBSymbol::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSymbol, operator bool); + + return m_opaque_ptr != nullptr; +} const char *SBSymbol::GetName() const { - const char *name = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBSymbol, GetName); + + const char *name = nullptr; if (m_opaque_ptr) name = m_opaque_ptr->GetName().AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBSymbol(%p)::GetName () => \"%s\"", - static_cast<void *>(m_opaque_ptr), name ? name : ""); return name; } const char *SBSymbol::GetDisplayName() const { - const char *name = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBSymbol, GetDisplayName); + + const char *name = nullptr; if (m_opaque_ptr) name = m_opaque_ptr->GetMangled() .GetDisplayDemangledName(m_opaque_ptr->GetLanguage()) .AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBSymbol(%p)::GetDisplayName () => \"%s\"", - static_cast<void *>(m_opaque_ptr), name ? name : ""); return name; } const char *SBSymbol::GetMangledName() const { - const char *name = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBSymbol, GetMangledName); + + const char *name = nullptr; if (m_opaque_ptr) name = m_opaque_ptr->GetMangled().GetMangledName().AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBSymbol(%p)::GetMangledName () => \"%s\"", - static_cast<void *>(m_opaque_ptr), name ? name : ""); - return name; } bool SBSymbol::operator==(const SBSymbol &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBSymbol, operator==,(const lldb::SBSymbol &), + rhs); + return m_opaque_ptr == rhs.m_opaque_ptr; } bool SBSymbol::operator!=(const SBSymbol &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBSymbol, operator!=,(const lldb::SBSymbol &), + rhs); + return m_opaque_ptr != rhs.m_opaque_ptr; } bool SBSymbol::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBSymbol, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); if (m_opaque_ptr) { - m_opaque_ptr->GetDescription(&strm, lldb::eDescriptionLevelFull, NULL); + m_opaque_ptr->GetDescription(&strm, lldb::eDescriptionLevelFull, nullptr); } else strm.PutCString("No value"); @@ -98,11 +113,17 @@ } SBInstructionList SBSymbol::GetInstructions(SBTarget target) { - return GetInstructions(target, NULL); + LLDB_RECORD_METHOD(lldb::SBInstructionList, SBSymbol, GetInstructions, + (lldb::SBTarget), target); + + return LLDB_RECORD_RESULT(GetInstructions(target, nullptr)); } SBInstructionList SBSymbol::GetInstructions(SBTarget target, const char *flavor_string) { + LLDB_RECORD_METHOD(lldb::SBInstructionList, SBSymbol, GetInstructions, + (lldb::SBTarget, const char *), target, flavor_string); + SBInstructionList sb_instructions; if (m_opaque_ptr) { ExecutionContext exe_ctx; @@ -120,12 +141,12 @@ AddressRange symbol_range(symbol_addr, m_opaque_ptr->GetByteSize()); const bool prefer_file_cache = false; sb_instructions.SetDisassembler(Disassembler::DisassembleRange( - module_sp->GetArchitecture(), NULL, flavor_string, exe_ctx, + module_sp->GetArchitecture(), nullptr, flavor_string, exe_ctx, symbol_range, prefer_file_cache)); } } } - return sb_instructions; + return LLDB_RECORD_RESULT(sb_instructions); } lldb_private::Symbol *SBSymbol::get() { return m_opaque_ptr; } @@ -133,14 +154,18 @@ void SBSymbol::reset(lldb_private::Symbol *symbol) { m_opaque_ptr = symbol; } SBAddress SBSymbol::GetStartAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBAddress, SBSymbol, GetStartAddress); + SBAddress addr; if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) { addr.SetAddress(&m_opaque_ptr->GetAddressRef()); } - return addr; + return LLDB_RECORD_RESULT(addr); } SBAddress SBSymbol::GetEndAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBAddress, SBSymbol, GetEndAddress); + SBAddress addr; if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) { lldb::addr_t range_size = m_opaque_ptr->GetByteSize(); @@ -149,29 +174,71 @@ addr->Slide(m_opaque_ptr->GetByteSize()); } } - return addr; + return LLDB_RECORD_RESULT(addr); } uint32_t SBSymbol::GetPrologueByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBSymbol, GetPrologueByteSize); + if (m_opaque_ptr) return m_opaque_ptr->GetPrologueByteSize(); return 0; } SymbolType SBSymbol::GetType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SymbolType, SBSymbol, GetType); + if (m_opaque_ptr) return m_opaque_ptr->GetType(); return eSymbolTypeInvalid; } bool SBSymbol::IsExternal() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBSymbol, IsExternal); + if (m_opaque_ptr) return m_opaque_ptr->IsExternal(); return false; } bool SBSymbol::IsSynthetic() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBSymbol, IsSynthetic); + if (m_opaque_ptr) return m_opaque_ptr->IsSynthetic(); return false; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBSymbol>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBSymbol, ()); + LLDB_REGISTER_CONSTRUCTOR(SBSymbol, (const lldb::SBSymbol &)); + LLDB_REGISTER_METHOD(const lldb::SBSymbol &, + SBSymbol, operator=,(const lldb::SBSymbol &)); + LLDB_REGISTER_METHOD_CONST(bool, SBSymbol, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBSymbol, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBSymbol, GetName, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBSymbol, GetDisplayName, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBSymbol, GetMangledName, ()); + LLDB_REGISTER_METHOD_CONST(bool, + SBSymbol, operator==,(const lldb::SBSymbol &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBSymbol, operator!=,(const lldb::SBSymbol &)); + LLDB_REGISTER_METHOD(bool, SBSymbol, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(lldb::SBInstructionList, SBSymbol, GetInstructions, + (lldb::SBTarget)); + LLDB_REGISTER_METHOD(lldb::SBInstructionList, SBSymbol, GetInstructions, + (lldb::SBTarget, const char *)); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBSymbol, GetStartAddress, ()); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBSymbol, GetEndAddress, ()); + LLDB_REGISTER_METHOD(uint32_t, SBSymbol, GetPrologueByteSize, ()); + LLDB_REGISTER_METHOD(lldb::SymbolType, SBSymbol, GetType, ()); + LLDB_REGISTER_METHOD(bool, SBSymbol, IsExternal, ()); + LLDB_REGISTER_METHOD(bool, SBSymbol, IsSynthetic, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBSymbolContext.cpp b/src/llvm-project/lldb/source/API/SBSymbolContext.cpp index ab70c6f..365f0cc 100644 --- a/src/llvm-project/lldb/source/API/SBSymbolContext.cpp +++ b/src/llvm-project/lldb/source/API/SBSymbolContext.cpp
@@ -1,161 +1,166 @@ //===-- SBSymbolContext.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.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/Log.h" using namespace lldb; using namespace lldb_private; -SBSymbolContext::SBSymbolContext() : m_opaque_ap() {} - -SBSymbolContext::SBSymbolContext(const SymbolContext *sc_ptr) : m_opaque_ap() { - if (sc_ptr) - m_opaque_ap.reset(new SymbolContext(*sc_ptr)); +SBSymbolContext::SBSymbolContext() : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBSymbolContext); } -SBSymbolContext::SBSymbolContext(const SBSymbolContext &rhs) : m_opaque_ap() { - if (rhs.IsValid()) { - if (m_opaque_ap) - *m_opaque_ap = *rhs.m_opaque_ap; - else - ref() = *rhs.m_opaque_ap; - } +SBSymbolContext::SBSymbolContext(const SymbolContext *sc_ptr) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBSymbolContext, + (const lldb_private::SymbolContext *), sc_ptr); + + if (sc_ptr) + m_opaque_up = llvm::make_unique<SymbolContext>(*sc_ptr); +} + +SBSymbolContext::SBSymbolContext(const SBSymbolContext &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBSymbolContext, (const lldb::SBSymbolContext &), + rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBSymbolContext::~SBSymbolContext() {} const SBSymbolContext &SBSymbolContext::operator=(const SBSymbolContext &rhs) { - if (this != &rhs) { - if (rhs.IsValid()) - m_opaque_ap.reset(new lldb_private::SymbolContext(*rhs.m_opaque_ap)); - } - return *this; + LLDB_RECORD_METHOD(const lldb::SBSymbolContext &, + SBSymbolContext, operator=,(const lldb::SBSymbolContext &), + rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } void SBSymbolContext::SetSymbolContext(const SymbolContext *sc_ptr) { - if (sc_ptr) { - if (m_opaque_ap) - *m_opaque_ap = *sc_ptr; - else - m_opaque_ap.reset(new SymbolContext(*sc_ptr)); - } else { - if (m_opaque_ap) - m_opaque_ap->Clear(true); - } + if (sc_ptr) + m_opaque_up = llvm::make_unique<SymbolContext>(*sc_ptr); + else + m_opaque_up->Clear(true); } -bool SBSymbolContext::IsValid() const { return m_opaque_ap != NULL; } +bool SBSymbolContext::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSymbolContext, IsValid); + return this->operator bool(); +} +SBSymbolContext::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSymbolContext, operator bool); + + return m_opaque_up != nullptr; +} SBModule SBSymbolContext::GetModule() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBModule, SBSymbolContext, GetModule); SBModule sb_module; ModuleSP module_sp; - if (m_opaque_ap) { - module_sp = m_opaque_ap->module_sp; + if (m_opaque_up) { + module_sp = m_opaque_up->module_sp; sb_module.SetSP(module_sp); } - if (log) { - SBStream sstr; - sb_module.GetDescription(sstr); - log->Printf("SBSymbolContext(%p)::GetModule () => SBModule(%p): %s", - static_cast<void *>(m_opaque_ap.get()), - static_cast<void *>(module_sp.get()), sstr.GetData()); - } - - return sb_module; + return LLDB_RECORD_RESULT(sb_module); } SBCompileUnit SBSymbolContext::GetCompileUnit() { - return SBCompileUnit(m_opaque_ap ? m_opaque_ap->comp_unit : NULL); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBCompileUnit, SBSymbolContext, + GetCompileUnit); + + return LLDB_RECORD_RESULT( + SBCompileUnit(m_opaque_up ? m_opaque_up->comp_unit : nullptr)); } SBFunction SBSymbolContext::GetFunction() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFunction, SBSymbolContext, GetFunction); - Function *function = NULL; + Function *function = nullptr; - if (m_opaque_ap) - function = m_opaque_ap->function; + if (m_opaque_up) + function = m_opaque_up->function; SBFunction sb_function(function); - if (log) - log->Printf("SBSymbolContext(%p)::GetFunction () => SBFunction(%p)", - static_cast<void *>(m_opaque_ap.get()), - static_cast<void *>(function)); - - return sb_function; + return LLDB_RECORD_RESULT(sb_function); } SBBlock SBSymbolContext::GetBlock() { - return SBBlock(m_opaque_ap ? m_opaque_ap->block : NULL); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBSymbolContext, GetBlock); + + return LLDB_RECORD_RESULT( + SBBlock(m_opaque_up ? m_opaque_up->block : nullptr)); } SBLineEntry SBSymbolContext::GetLineEntry() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBLineEntry, SBSymbolContext, GetLineEntry); SBLineEntry sb_line_entry; - if (m_opaque_ap) - sb_line_entry.SetLineEntry(m_opaque_ap->line_entry); + if (m_opaque_up) + sb_line_entry.SetLineEntry(m_opaque_up->line_entry); - if (log) { - log->Printf("SBSymbolContext(%p)::GetLineEntry () => SBLineEntry(%p)", - static_cast<void *>(m_opaque_ap.get()), - static_cast<void *>(sb_line_entry.get())); - } - - return sb_line_entry; + return LLDB_RECORD_RESULT(sb_line_entry); } SBSymbol SBSymbolContext::GetSymbol() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSymbol, SBSymbolContext, GetSymbol); - Symbol *symbol = NULL; + Symbol *symbol = nullptr; - if (m_opaque_ap) - symbol = m_opaque_ap->symbol; + if (m_opaque_up) + symbol = m_opaque_up->symbol; SBSymbol sb_symbol(symbol); - if (log) - log->Printf("SBSymbolContext(%p)::GetSymbol () => SBSymbol(%p)", - static_cast<void *>(m_opaque_ap.get()), - static_cast<void *>(symbol)); - - return sb_symbol; + return LLDB_RECORD_RESULT(sb_symbol); } void SBSymbolContext::SetModule(lldb::SBModule module) { + LLDB_RECORD_METHOD(void, SBSymbolContext, SetModule, (lldb::SBModule), + module); + ref().module_sp = module.GetSP(); } void SBSymbolContext::SetCompileUnit(lldb::SBCompileUnit compile_unit) { + LLDB_RECORD_METHOD(void, SBSymbolContext, SetCompileUnit, + (lldb::SBCompileUnit), compile_unit); + ref().comp_unit = compile_unit.get(); } void SBSymbolContext::SetFunction(lldb::SBFunction function) { + LLDB_RECORD_METHOD(void, SBSymbolContext, SetFunction, (lldb::SBFunction), + function); + ref().function = function.get(); } void SBSymbolContext::SetBlock(lldb::SBBlock block) { + LLDB_RECORD_METHOD(void, SBSymbolContext, SetBlock, (lldb::SBBlock), block); + ref().block = block.GetPtr(); } void SBSymbolContext::SetLineEntry(lldb::SBLineEntry line_entry) { + LLDB_RECORD_METHOD(void, SBSymbolContext, SetLineEntry, (lldb::SBLineEntry), + line_entry); + if (line_entry.IsValid()) ref().line_entry = line_entry.ref(); else @@ -163,39 +168,45 @@ } void SBSymbolContext::SetSymbol(lldb::SBSymbol symbol) { + LLDB_RECORD_METHOD(void, SBSymbolContext, SetSymbol, (lldb::SBSymbol), + symbol); + ref().symbol = symbol.get(); } lldb_private::SymbolContext *SBSymbolContext::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const lldb_private::SymbolContext &SBSymbolContext::operator*() const { - assert(m_opaque_ap.get()); - return *m_opaque_ap; + assert(m_opaque_up.get()); + return *m_opaque_up; } lldb_private::SymbolContext &SBSymbolContext::operator*() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new SymbolContext); - return *m_opaque_ap; + if (m_opaque_up == nullptr) + m_opaque_up.reset(new SymbolContext); + return *m_opaque_up; } lldb_private::SymbolContext &SBSymbolContext::ref() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new SymbolContext); - return *m_opaque_ap; + if (m_opaque_up == nullptr) + m_opaque_up.reset(new SymbolContext); + return *m_opaque_up; } lldb_private::SymbolContext *SBSymbolContext::get() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } bool SBSymbolContext::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBSymbolContext, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); - if (m_opaque_ap) { - m_opaque_ap->GetDescription(&strm, lldb::eDescriptionLevelFull, NULL); + if (m_opaque_up) { + m_opaque_up->GetDescription(&strm, lldb::eDescriptionLevelFull, nullptr); } else strm.PutCString("No value"); @@ -205,11 +216,56 @@ SBSymbolContext SBSymbolContext::GetParentOfInlinedScope(const SBAddress &curr_frame_pc, SBAddress &parent_frame_addr) const { + LLDB_RECORD_METHOD_CONST(lldb::SBSymbolContext, SBSymbolContext, + GetParentOfInlinedScope, + (const lldb::SBAddress &, lldb::SBAddress &), + curr_frame_pc, parent_frame_addr); + SBSymbolContext sb_sc; - if (m_opaque_ap.get() && curr_frame_pc.IsValid()) { - if (m_opaque_ap->GetParentOfInlinedScope(curr_frame_pc.ref(), sb_sc.ref(), + 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 LLDB_RECORD_RESULT(sb_sc); } - return SBSymbolContext(); + return LLDB_RECORD_RESULT(SBSymbolContext()); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBSymbolContext>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBSymbolContext, ()); + LLDB_REGISTER_CONSTRUCTOR(SBSymbolContext, + (const lldb_private::SymbolContext *)); + LLDB_REGISTER_CONSTRUCTOR(SBSymbolContext, (const lldb::SBSymbolContext &)); + LLDB_REGISTER_METHOD( + const lldb::SBSymbolContext &, + SBSymbolContext, operator=,(const lldb::SBSymbolContext &)); + LLDB_REGISTER_METHOD_CONST(bool, SBSymbolContext, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBSymbolContext, operator bool, ()); + LLDB_REGISTER_METHOD(lldb::SBModule, SBSymbolContext, GetModule, ()); + LLDB_REGISTER_METHOD(lldb::SBCompileUnit, SBSymbolContext, GetCompileUnit, + ()); + LLDB_REGISTER_METHOD(lldb::SBFunction, SBSymbolContext, GetFunction, ()); + LLDB_REGISTER_METHOD(lldb::SBBlock, SBSymbolContext, GetBlock, ()); + LLDB_REGISTER_METHOD(lldb::SBLineEntry, SBSymbolContext, GetLineEntry, ()); + LLDB_REGISTER_METHOD(lldb::SBSymbol, SBSymbolContext, GetSymbol, ()); + LLDB_REGISTER_METHOD(void, SBSymbolContext, SetModule, (lldb::SBModule)); + LLDB_REGISTER_METHOD(void, SBSymbolContext, SetCompileUnit, + (lldb::SBCompileUnit)); + LLDB_REGISTER_METHOD(void, SBSymbolContext, SetFunction, + (lldb::SBFunction)); + LLDB_REGISTER_METHOD(void, SBSymbolContext, SetBlock, (lldb::SBBlock)); + LLDB_REGISTER_METHOD(void, SBSymbolContext, SetLineEntry, + (lldb::SBLineEntry)); + LLDB_REGISTER_METHOD(void, SBSymbolContext, SetSymbol, (lldb::SBSymbol)); + LLDB_REGISTER_METHOD(bool, SBSymbolContext, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBSymbolContext, SBSymbolContext, + GetParentOfInlinedScope, + (const lldb::SBAddress &, lldb::SBAddress &)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBSymbolContextList.cpp b/src/llvm-project/lldb/source/API/SBSymbolContextList.cpp index b07ab2a..915d04a 100644 --- a/src/llvm-project/lldb/source/API/SBSymbolContextList.cpp +++ b/src/llvm-project/lldb/source/API/SBSymbolContextList.cpp
@@ -1,13 +1,14 @@ //===-- SBSymbolContextList.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBStream.h" #include "lldb/Symbol/SymbolContext.h" @@ -15,67 +16,129 @@ using namespace lldb_private; SBSymbolContextList::SBSymbolContextList() - : m_opaque_ap(new SymbolContextList()) {} + : m_opaque_up(new SymbolContextList()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBSymbolContextList); +} SBSymbolContextList::SBSymbolContextList(const SBSymbolContextList &rhs) - : m_opaque_ap(new SymbolContextList(*rhs.m_opaque_ap)) {} + : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBSymbolContextList, + (const lldb::SBSymbolContextList &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} SBSymbolContextList::~SBSymbolContextList() {} const SBSymbolContextList &SBSymbolContextList:: operator=(const SBSymbolContextList &rhs) { - if (this != &rhs) { - *m_opaque_ap = *rhs.m_opaque_ap; - } - return *this; + LLDB_RECORD_METHOD( + const lldb::SBSymbolContextList &, + SBSymbolContextList, operator=,(const lldb::SBSymbolContextList &), rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return LLDB_RECORD_RESULT(*this); } uint32_t SBSymbolContextList::GetSize() const { - if (m_opaque_ap) - return m_opaque_ap->GetSize(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBSymbolContextList, GetSize); + + if (m_opaque_up) + return m_opaque_up->GetSize(); return 0; } SBSymbolContext SBSymbolContextList::GetContextAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBSymbolContext, SBSymbolContextList, + GetContextAtIndex, (uint32_t), idx); + SBSymbolContext sb_sc; - if (m_opaque_ap) { + if (m_opaque_up) { SymbolContext sc; - if (m_opaque_ap->GetContextAtIndex(idx, sc)) { + if (m_opaque_up->GetContextAtIndex(idx, sc)) { sb_sc.SetSymbolContext(&sc); } } - return sb_sc; + return LLDB_RECORD_RESULT(sb_sc); } void SBSymbolContextList::Clear() { - if (m_opaque_ap) - m_opaque_ap->Clear(); + LLDB_RECORD_METHOD_NO_ARGS(void, SBSymbolContextList, Clear); + + if (m_opaque_up) + m_opaque_up->Clear(); } void SBSymbolContextList::Append(SBSymbolContext &sc) { - if (sc.IsValid() && m_opaque_ap.get()) - m_opaque_ap->Append(*sc); + LLDB_RECORD_METHOD(void, SBSymbolContextList, Append, + (lldb::SBSymbolContext &), sc); + + if (sc.IsValid() && m_opaque_up.get()) + m_opaque_up->Append(*sc); } void SBSymbolContextList::Append(SBSymbolContextList &sc_list) { - if (sc_list.IsValid() && m_opaque_ap.get()) - m_opaque_ap->Append(*sc_list); + LLDB_RECORD_METHOD(void, SBSymbolContextList, Append, + (lldb::SBSymbolContextList &), sc_list); + + if (sc_list.IsValid() && m_opaque_up.get()) + m_opaque_up->Append(*sc_list); } -bool SBSymbolContextList::IsValid() const { return m_opaque_ap != NULL; } +bool SBSymbolContextList::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSymbolContextList, IsValid); + return this->operator bool(); +} +SBSymbolContextList::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBSymbolContextList, operator bool); + + return m_opaque_up != nullptr; +} lldb_private::SymbolContextList *SBSymbolContextList::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } lldb_private::SymbolContextList &SBSymbolContextList::operator*() const { - assert(m_opaque_ap.get()); - return *m_opaque_ap; + assert(m_opaque_up.get()); + return *m_opaque_up; } bool SBSymbolContextList::GetDescription(lldb::SBStream &description) { + LLDB_RECORD_METHOD(bool, SBSymbolContextList, GetDescription, + (lldb::SBStream &), description); + Stream &strm = description.ref(); - if (m_opaque_ap) - m_opaque_ap->GetDescription(&strm, lldb::eDescriptionLevelFull, NULL); + if (m_opaque_up) + m_opaque_up->GetDescription(&strm, lldb::eDescriptionLevelFull, nullptr); return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBSymbolContextList>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBSymbolContextList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBSymbolContextList, + (const lldb::SBSymbolContextList &)); + LLDB_REGISTER_METHOD( + const lldb::SBSymbolContextList &, + SBSymbolContextList, operator=,(const lldb::SBSymbolContextList &)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBSymbolContextList, GetSize, ()); + LLDB_REGISTER_METHOD(lldb::SBSymbolContext, SBSymbolContextList, + GetContextAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBSymbolContextList, Clear, ()); + LLDB_REGISTER_METHOD(void, SBSymbolContextList, Append, + (lldb::SBSymbolContext &)); + LLDB_REGISTER_METHOD(void, SBSymbolContextList, Append, + (lldb::SBSymbolContextList &)); + LLDB_REGISTER_METHOD_CONST(bool, SBSymbolContextList, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBSymbolContextList, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBSymbolContextList, GetDescription, + (lldb::SBStream &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTarget.cpp b/src/llvm-project/lldb/source/API/SBTarget.cpp index 98587e7..5e87eb6 100644 --- a/src/llvm-project/lldb/source/API/SBTarget.cpp +++ b/src/llvm-project/lldb/source/API/SBTarget.cpp
@@ -1,13 +1,13 @@ //===-- SBTarget.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/lldb-public.h" @@ -53,7 +53,6 @@ #include "lldb/Target/ABI.h" #include "lldb/Target/Language.h" #include "lldb/Target/LanguageRuntime.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" @@ -61,7 +60,7 @@ #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/FileSpec.h" -#include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/RegularExpression.h" #include "Commands/CommandObjectBreakpoint.h" @@ -97,35 +96,50 @@ } // namespace -//---------------------------------------------------------------------- // SBTarget constructor -//---------------------------------------------------------------------- -SBTarget::SBTarget() : m_opaque_sp() {} - -SBTarget::SBTarget(const SBTarget &rhs) : m_opaque_sp(rhs.m_opaque_sp) {} - -SBTarget::SBTarget(const TargetSP &target_sp) : m_opaque_sp(target_sp) {} - -const SBTarget &SBTarget::operator=(const SBTarget &rhs) { - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +SBTarget::SBTarget() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTarget); } -//---------------------------------------------------------------------- +SBTarget::SBTarget(const SBTarget &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTarget, (const lldb::SBTarget &), rhs); +} + +SBTarget::SBTarget(const TargetSP &target_sp) : m_opaque_sp(target_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTarget, (const lldb::TargetSP &), target_sp); +} + +const SBTarget &SBTarget::operator=(const SBTarget &rhs) { + LLDB_RECORD_METHOD(const lldb::SBTarget &, + SBTarget, operator=,(const lldb::SBTarget &), rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return LLDB_RECORD_RESULT(*this); +} + // Destructor -//---------------------------------------------------------------------- SBTarget::~SBTarget() {} bool SBTarget::EventIsTargetEvent(const SBEvent &event) { - return Target::TargetEventData::GetEventDataFromEvent(event.get()) != NULL; + LLDB_RECORD_STATIC_METHOD(bool, SBTarget, EventIsTargetEvent, + (const lldb::SBEvent &), event); + + return Target::TargetEventData::GetEventDataFromEvent(event.get()) != nullptr; } SBTarget SBTarget::GetTargetFromEvent(const SBEvent &event) { - return Target::TargetEventData::GetTargetFromEvent(event.get()); + LLDB_RECORD_STATIC_METHOD(lldb::SBTarget, SBTarget, GetTargetFromEvent, + (const lldb::SBEvent &), event); + + return LLDB_RECORD_RESULT( + Target::TargetEventData::GetTargetFromEvent(event.get())); } uint32_t SBTarget::GetNumModulesFromEvent(const SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(uint32_t, SBTarget, GetNumModulesFromEvent, + (const lldb::SBEvent &), event); + const ModuleList module_list = Target::TargetEventData::GetModuleListFromEvent(event.get()); return module_list.GetSize(); @@ -133,20 +147,35 @@ SBModule SBTarget::GetModuleAtIndexFromEvent(const uint32_t idx, const SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(lldb::SBModule, SBTarget, GetModuleAtIndexFromEvent, + (const uint32_t, const lldb::SBEvent &), idx, + event); + const ModuleList module_list = Target::TargetEventData::GetModuleListFromEvent(event.get()); - return SBModule(module_list.GetModuleAtIndex(idx)); + return LLDB_RECORD_RESULT(SBModule(module_list.GetModuleAtIndex(idx))); } const char *SBTarget::GetBroadcasterClassName() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBTarget, + GetBroadcasterClassName); + return Target::GetStaticBroadcasterClass().AsCString(); } bool SBTarget::IsValid() const { - return m_opaque_sp.get() != NULL && m_opaque_sp->IsValid(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTarget, IsValid); + return this->operator bool(); +} +SBTarget::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTarget, operator bool); + + return m_opaque_sp.get() != nullptr && m_opaque_sp->IsValid(); } SBProcess SBTarget::GetProcess() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBProcess, SBTarget, GetProcess); + SBProcess sb_process; ProcessSP process_sp; TargetSP target_sp(GetSP()); @@ -155,39 +184,39 @@ sb_process.SetSP(process_sp); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBTarget(%p)::GetProcess () => SBProcess(%p)", - static_cast<void *>(target_sp.get()), - static_cast<void *>(process_sp.get())); - - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } SBPlatform SBTarget::GetPlatform() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBPlatform, SBTarget, GetPlatform); + TargetSP target_sp(GetSP()); if (!target_sp) - return SBPlatform(); + return LLDB_RECORD_RESULT(SBPlatform()); SBPlatform platform; platform.m_opaque_sp = target_sp->GetPlatform(); - return platform; + return LLDB_RECORD_RESULT(platform); } SBDebugger SBTarget::GetDebugger() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBDebugger, SBTarget, GetDebugger); + SBDebugger debugger; TargetSP target_sp(GetSP()); if (target_sp) debugger.reset(target_sp->GetDebugger().shared_from_this()); - return debugger; + return LLDB_RECORD_RESULT(debugger); } SBStructuredData SBTarget::GetStatistics() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBStructuredData, SBTarget, GetStatistics); + SBStructuredData data; TargetSP target_sp(GetSP()); if (!target_sp) - return data; + return LLDB_RECORD_RESULT(data); auto stats_up = llvm::make_unique<StructuredData::Dictionary>(); int i = 0; @@ -199,10 +228,12 @@ } data.m_impl_up->SetObjectSP(std::move(stats_up)); - return data; + return LLDB_RECORD_RESULT(data); } void SBTarget::SetCollectingStats(bool v) { + LLDB_RECORD_METHOD(void, SBTarget, SetCollectingStats, (bool), v); + TargetSP target_sp(GetSP()); if (!target_sp) return; @@ -210,19 +241,26 @@ } bool SBTarget::GetCollectingStats() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTarget, GetCollectingStats); + TargetSP target_sp(GetSP()); if (!target_sp) return false; return target_sp->GetCollectingStats(); } - SBProcess SBTarget::LoadCore(const char *core_file) { + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, LoadCore, (const char *), + core_file); + lldb::SBError error; // Ignored - return LoadCore(core_file, error); + return LLDB_RECORD_RESULT(LoadCore(core_file, error)); } SBProcess SBTarget::LoadCore(const char *core_file, lldb::SBError &error) { + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, LoadCore, + (const char *, lldb::SBError &), core_file, error); + SBProcess sb_process; TargetSP target_sp(GetSP()); if (target_sp) { @@ -240,30 +278,37 @@ } else { error.SetErrorString("SBTarget is invalid"); } - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } SBProcess SBTarget::LaunchSimple(char const **argv, char const **envp, const char *working_directory) { - char *stdin_path = NULL; - char *stdout_path = NULL; - char *stderr_path = NULL; + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, LaunchSimple, + (const char **, const char **, const char *), argv, envp, + working_directory); + + char *stdin_path = nullptr; + char *stdout_path = nullptr; + char *stderr_path = nullptr; uint32_t launch_flags = 0; bool stop_at_entry = false; SBError error; SBListener listener = GetDebugger().GetListener(); - return Launch(listener, argv, envp, stdin_path, stdout_path, stderr_path, - working_directory, launch_flags, stop_at_entry, error); + return LLDB_RECORD_RESULT(Launch(listener, argv, envp, stdin_path, + stdout_path, stderr_path, working_directory, + launch_flags, stop_at_entry, error)); } SBError SBTarget::Install() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBTarget, Install); + 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(NULL); + sb_error.ref() = target_sp->Install(nullptr); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBProcess SBTarget::Launch(SBListener &listener, char const **argv, @@ -272,23 +317,17 @@ const char *working_directory, uint32_t launch_flags, // See LaunchFlags bool stop_at_entry, lldb::SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, Launch, + (lldb::SBListener &, const char **, const char **, + const char *, const char *, const char *, const char *, + uint32_t, bool, lldb::SBError &), + 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 (log) - log->Printf("SBTarget(%p)::Launch (argv=%p, envp=%p, stdin=%s, stdout=%s, " - "stderr=%s, working-dir=%s, launch_flags=0x%x, " - "stop_at_entry=%i, &error (%p))...", - static_cast<void *>(target_sp.get()), static_cast<void *>(argv), - static_cast<void *>(envp), stdin_path ? stdin_path : "NULL", - stdout_path ? stdout_path : "NULL", - stderr_path ? stderr_path : "NULL", - working_directory ? working_directory : "NULL", launch_flags, - stop_at_entry, static_cast<void *>(error.get())); - if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -308,7 +347,7 @@ error.SetErrorString("process attach is in progress"); else error.SetErrorString("a process is already being debugged"); - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } } @@ -319,7 +358,7 @@ if (listener.IsValid()) { error.SetErrorString("process is connected and already has a listener, " "pass empty listener"); - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } } @@ -341,33 +380,25 @@ if (listener.IsValid()) launch_info.SetListener(listener.GetSP()); - error.SetError(target_sp->Launch(launch_info, NULL)); + error.SetError(target_sp->Launch(launch_info, nullptr)); sb_process.SetSP(target_sp->GetProcessSP()); } else { error.SetErrorString("SBTarget is invalid"); } - log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); - if (log) - log->Printf("SBTarget(%p)::Launch (...) => SBProcess(%p), SBError(%s)", - static_cast<void *>(target_sp.get()), - static_cast<void *>(sb_process.GetSP().get()), - error.GetCString()); - - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } SBProcess SBTarget::Launch(SBLaunchInfo &sb_launch_info, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, Launch, + (lldb::SBLaunchInfo &, lldb::SBError &), sb_launch_info, + error); + SBProcess sb_process; TargetSP target_sp(GetSP()); - if (log) - log->Printf("SBTarget(%p)::Launch (launch_info, error)...", - static_cast<void *>(target_sp.get())); - if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); StateType state = eStateInvalid; @@ -381,7 +412,7 @@ error.SetErrorString("process attach is in progress"); else error.SetErrorString("a process is already being debugged"); - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } } } @@ -398,32 +429,24 @@ if (arch_spec.IsValid()) launch_info.GetArchitecture() = arch_spec; - error.SetError(target_sp->Launch(launch_info, NULL)); + 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"); } - log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); - if (log) - log->Printf("SBTarget(%p)::Launch (...) => SBProcess(%p)", - static_cast<void *>(target_sp.get()), - static_cast<void *>(sb_process.GetSP().get())); - - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } lldb::SBProcess SBTarget::Attach(SBAttachInfo &sb_attach_info, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, Attach, + (lldb::SBAttachInfo &, lldb::SBError &), sb_attach_info, + error); SBProcess sb_process; TargetSP target_sp(GetSP()); - if (log) - log->Printf("SBTarget(%p)::Attach (sb_attach_info, error)...", - static_cast<void *>(target_sp.get())); - if (target_sp) { ProcessAttachInfo &attach_info = sb_attach_info.ref(); if (attach_info.ProcessIDIsValid() && !attach_info.UserIDIsValid()) { @@ -437,12 +460,7 @@ } else { error.ref().SetErrorStringWithFormat( "no process found with process ID %" PRIu64, attach_pid); - if (log) { - log->Printf("SBTarget(%p)::Attach (...) => error %s", - static_cast<void *>(target_sp.get()), - error.GetCString()); - } - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } } } @@ -453,28 +471,21 @@ error.SetErrorString("SBTarget is invalid"); } - if (log) - log->Printf("SBTarget(%p)::Attach (...) => SBProcess(%p)", - static_cast<void *>(target_sp.get()), - static_cast<void *>(sb_process.GetSP().get())); - - return sb_process; + return LLDB_RECORD_RESULT(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 - ) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +) { + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, AttachToProcessWithID, + (lldb::SBListener &, lldb::pid_t, lldb::SBError &), + listener, pid, error); SBProcess sb_process; TargetSP target_sp(GetSP()); - if (log) - log->Printf("SBTarget(%p)::%s (listener, pid=%" PRId64 ", error)...", - static_cast<void *>(target_sp.get()), __FUNCTION__, pid); - if (target_sp) { ProcessAttachInfo attach_info; attach_info.SetProcessID(pid); @@ -491,11 +502,7 @@ } else error.SetErrorString("SBTarget is invalid"); - if (log) - log->Printf("SBTarget(%p)::%s (...) => SBProcess(%p)", - static_cast<void *>(target_sp.get()), __FUNCTION__, - static_cast<void *>(sb_process.GetSP().get())); - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } lldb::SBProcess SBTarget::AttachToProcessWithName( @@ -503,17 +510,14 @@ 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 - ) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +) { + LLDB_RECORD_METHOD(lldb::SBProcess, SBTarget, AttachToProcessWithName, + (lldb::SBListener &, const char *, bool, lldb::SBError &), + listener, name, wait_for, error); SBProcess sb_process; TargetSP target_sp(GetSP()); - if (log) - log->Printf("SBTarget(%p)::%s (listener, name=%s, wait_for=%s, error)...", - static_cast<void *>(target_sp.get()), __FUNCTION__, name, - wait_for ? "true" : "false"); - if (name && target_sp) { ProcessAttachInfo attach_info; attach_info.GetExecutableFile().SetFile(name, FileSpec::Style::native); @@ -527,39 +531,33 @@ } else error.SetErrorString("SBTarget is invalid"); - if (log) - log->Printf("SBTarget(%p)::%s (...) => SBProcess(%p)", - static_cast<void *>(target_sp.get()), __FUNCTION__, - static_cast<void *>(sb_process.GetSP().get())); - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } lldb::SBProcess SBTarget::ConnectRemote(SBListener &listener, const char *url, const char *plugin_name, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD( + lldb::SBProcess, SBTarget, ConnectRemote, + (lldb::SBListener &, const char *, const char *, lldb::SBError &), + listener, url, plugin_name, error); SBProcess sb_process; ProcessSP process_sp; TargetSP target_sp(GetSP()); - if (log) - log->Printf("SBTarget(%p)::ConnectRemote (listener, url=%s, " - "plugin_name=%s, error)...", - static_cast<void *>(target_sp.get()), url, plugin_name); - 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, NULL); + target_sp->CreateProcess(listener.m_opaque_sp, plugin_name, nullptr); else process_sp = target_sp->CreateProcess( - target_sp->GetDebugger().GetListener(), plugin_name, NULL); + target_sp->GetDebugger().GetListener(), plugin_name, nullptr); if (process_sp) { sb_process.SetSP(process_sp); - error.SetError(process_sp->ConnectRemote(NULL, url)); + error.SetError(process_sp->ConnectRemote(nullptr, url)); } else { error.SetErrorString("unable to create lldb_private::Process"); } @@ -567,14 +565,11 @@ error.SetErrorString("SBTarget is invalid"); } - if (log) - log->Printf("SBTarget(%p)::ConnectRemote (...) => SBProcess(%p)", - static_cast<void *>(target_sp.get()), - static_cast<void *>(process_sp.get())); - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } SBFileSpec SBTarget::GetExecutable() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFileSpec, SBTarget, GetExecutable); SBFileSpec exe_file_spec; TargetSP target_sp(GetSP()); @@ -584,21 +579,20 @@ exe_file_spec.SetFileSpec(exe_module->GetFileSpec()); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - log->Printf("SBTarget(%p)::GetExecutable () => SBFileSpec(%p)", - static_cast<void *>(target_sp.get()), - static_cast<const void *>(exe_file_spec.get())); - } - - return exe_file_spec; + return LLDB_RECORD_RESULT(exe_file_spec); } bool SBTarget::operator==(const SBTarget &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBTarget, operator==,(const lldb::SBTarget &), + rhs); + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); } bool SBTarget::operator!=(const SBTarget &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBTarget, operator!=,(const lldb::SBTarget &), + rhs); + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); } @@ -609,55 +603,68 @@ } lldb::SBAddress SBTarget::ResolveLoadAddress(lldb::addr_t vm_addr) { + LLDB_RECORD_METHOD(lldb::SBAddress, SBTarget, ResolveLoadAddress, + (lldb::addr_t), 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; + return LLDB_RECORD_RESULT(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; + return LLDB_RECORD_RESULT(sb_addr); } lldb::SBAddress SBTarget::ResolveFileAddress(lldb::addr_t file_addr) { + LLDB_RECORD_METHOD(lldb::SBAddress, SBTarget, ResolveFileAddress, + (lldb::addr_t), 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; + return LLDB_RECORD_RESULT(sb_addr); } addr.SetRawAddress(file_addr); - return sb_addr; + return LLDB_RECORD_RESULT(sb_addr); } lldb::SBAddress SBTarget::ResolvePastLoadAddress(uint32_t stop_id, lldb::addr_t vm_addr) { + LLDB_RECORD_METHOD(lldb::SBAddress, SBTarget, ResolvePastLoadAddress, + (uint32_t, lldb::addr_t), 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; + return LLDB_RECORD_RESULT(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; + return LLDB_RECORD_RESULT(sb_addr); } SBSymbolContext SBTarget::ResolveSymbolContextForAddress(const SBAddress &addr, uint32_t resolve_scope) { + LLDB_RECORD_METHOD(lldb::SBSymbolContext, SBTarget, + ResolveSymbolContextForAddress, + (const lldb::SBAddress &, uint32_t), addr, resolve_scope); + SBSymbolContext sc; SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope); if (addr.IsValid()) { @@ -666,11 +673,15 @@ target_sp->GetImages().ResolveSymbolContextForAddress(addr.ref(), scope, sc.ref()); } - return sc; + return LLDB_RECORD_RESULT(sc); } size_t SBTarget::ReadMemory(const SBAddress addr, void *buf, size_t size, lldb::SBError &error) { + LLDB_RECORD_DUMMY(size_t, SBTarget, ReadMemory, + (const lldb::SBAddress, void *, size_t, lldb::SBError &), + addr, buf, size, error); + SBError sb_error; size_t bytes_read = 0; TargetSP target_sp(GetSP()); @@ -687,35 +698,54 @@ SBBreakpoint SBTarget::BreakpointCreateByLocation(const char *file, uint32_t line) { - return SBBreakpoint( - BreakpointCreateByLocation(SBFileSpec(file, false), line)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByLocation, + (const char *, uint32_t), file, line); + + return LLDB_RECORD_RESULT( + SBBreakpoint(BreakpointCreateByLocation(SBFileSpec(file, false), line))); } SBBreakpoint SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec, uint32_t line) { - return BreakpointCreateByLocation(sb_file_spec, line, 0); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t), sb_file_spec, line); + + return LLDB_RECORD_RESULT(BreakpointCreateByLocation(sb_file_spec, line, 0)); } SBBreakpoint SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec, uint32_t line, lldb::addr_t offset) { + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t, lldb::addr_t), + sb_file_spec, line, offset); + SBFileSpecList empty_list; - return BreakpointCreateByLocation(sb_file_spec, line, offset, empty_list); + return LLDB_RECORD_RESULT( + 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) { - return BreakpointCreateByLocation(sb_file_spec, line, 0, offset, - sb_module_list); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t, lldb::addr_t, + lldb::SBFileSpecList &), + sb_file_spec, line, offset, sb_module_list); + + return LLDB_RECORD_RESULT(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) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t, uint32_t, + lldb::addr_t, lldb::SBFileSpecList &), + sb_file_spec, line, column, offset, sb_module_list); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -736,23 +766,13 @@ skip_prologue, internal, hardware, move_to_nearest_code); } - if (log) { - SBStream sstr; - sb_bp.GetDescription(sstr); - char path[PATH_MAX]; - sb_file_spec->GetPath(path, sizeof(path)); - log->Printf("SBTarget(%p)::BreakpointCreateByLocation ( %s:%u ) => " - "SBBreakpoint(%p): %s", - static_cast<void *>(target_sp.get()), path, line, - static_cast<void *>(sb_bp.GetSP().get()), sstr.GetData()); - } - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } SBBreakpoint SBTarget::BreakpointCreateByName(const char *symbol_name, const char *module_name) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, const char *), symbol_name, module_name); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -767,47 +787,56 @@ FileSpecList module_spec_list; module_spec_list.Append(FileSpec(module_name)); sb_bp = target_sp->CreateBreakpoint( - &module_spec_list, NULL, symbol_name, eFunctionNameTypeAuto, + &module_spec_list, nullptr, symbol_name, eFunctionNameTypeAuto, eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); } else { sb_bp = target_sp->CreateBreakpoint( - NULL, NULL, symbol_name, eFunctionNameTypeAuto, eLanguageTypeUnknown, - offset, skip_prologue, internal, hardware); + nullptr, nullptr, symbol_name, eFunctionNameTypeAuto, + eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); } } - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", " - "module=\"%s\") => SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), symbol_name, module_name, - static_cast<void *>(sb_bp.GetSP().get())); - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } lldb::SBBreakpoint SBTarget::BreakpointCreateByName(const char *symbol_name, const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + 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); + return LLDB_RECORD_RESULT( + 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) { - return BreakpointCreateByName(symbol_name, name_type_mask, - eLanguageTypeUnknown, module_list, - comp_unit_list); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, uint32_t, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + symbol_name, name_type_mask, module_list, comp_unit_list); + + return LLDB_RECORD_RESULT( + 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) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, uint32_t, lldb::LanguageType, + const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + symbol_name, name_type_mask, symbol_language, module_list, + comp_unit_list); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -822,37 +851,49 @@ skip_prologue, internal, hardware); } - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", " - "name_type: %d) => SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), symbol_name, - name_type_mask, static_cast<void *>(sb_bp.GetSP().get())); - - return sb_bp; + return LLDB_RECORD_RESULT(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) { - return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, - eLanguageTypeUnknown, module_list, - comp_unit_list); + LLDB_RECORD_METHOD( + lldb::SBBreakpoint, SBTarget, BreakpointCreateByNames, + (const char **, uint32_t, uint32_t, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + symbol_names, num_names, name_type_mask, module_list, comp_unit_list); + + return LLDB_RECORD_RESULT(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) { - return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, - eLanguageTypeUnknown, 0, module_list, - comp_unit_list); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByNames, + (const char **, uint32_t, uint32_t, lldb::LanguageType, + const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + symbol_names, num_names, name_type_mask, symbol_language, + module_list, comp_unit_list); + + return LLDB_RECORD_RESULT(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) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByNames, + (const char **, uint32_t, uint32_t, lldb::LanguageType, + lldb::addr_t, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + symbol_names, num_names, name_type_mask, symbol_language, + offset, module_list, comp_unit_list); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -867,50 +908,47 @@ symbol_language, offset, skip_prologue, internal, hardware); } - if (log) { - log->Printf("SBTarget(%p)::BreakpointCreateByName (symbols={", - static_cast<void *>(target_sp.get())); - for (uint32_t i = 0; i < num_names; i++) { - char sep; - if (i < num_names - 1) - sep = ','; - else - sep = '}'; - if (symbol_names[i] != NULL) - log->Printf("\"%s\"%c ", symbol_names[i], sep); - else - log->Printf("\"<NULL>\"%c ", sep); - } - log->Printf("name_type: %d) => SBBreakpoint(%p)", name_type_mask, - static_cast<void *>(sb_bp.GetSP().get())); - } - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } SBBreakpoint SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex, const char *module_name) { + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByRegex, + (const char *, const char *), 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); + return LLDB_RECORD_RESULT( + 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) { - return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown, - module_list, comp_unit_list); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByRegex, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + symbol_name_regex, module_list, comp_unit_list); + + return LLDB_RECORD_RESULT(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) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD( + lldb::SBBreakpoint, SBTarget, BreakpointCreateByRegex, + (const char *, lldb::LanguageType, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + symbol_name_regex, symbol_language, module_list, comp_unit_list); + SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -926,17 +964,12 @@ skip_prologue, internal, hardware); } - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateByRegex (symbol_regex=\"%s\") " - "=> SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), symbol_name_regex, - static_cast<void *>(sb_bp.GetSP().get())); - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } SBBreakpoint SBTarget::BreakpointCreateByAddress(addr_t address) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByAddress, + (lldb::addr_t), address); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -946,27 +979,17 @@ sb_bp = target_sp->CreateBreakpoint(address, false, hardware); } - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateByAddress (address=%" PRIu64 - ") => SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), - static_cast<uint64_t>(address), - static_cast<void *>(sb_bp.GetSP().get())); - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } SBBreakpoint SBTarget::BreakpointCreateBySBAddress(SBAddress &sb_address) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateBySBAddress, + (lldb::SBAddress &), sb_address); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); if (!sb_address.IsValid()) { - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateBySBAddress called with " - "invalid address", - static_cast<void *>(target_sp.get())); - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } if (target_sp) { @@ -975,22 +998,18 @@ sb_bp = target_sp->CreateBreakpoint(sb_address.ref(), false, hardware); } - if (log) { - SBStream s; - sb_address.GetDescription(s); - log->Printf("SBTarget(%p)::BreakpointCreateBySBAddress (address=%s) => " - "SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), s.GetData(), - static_cast<void *>(sb_bp.GetSP().get())); - } - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex(const char *source_regex, const lldb::SBFileSpec &source_file, const char *module_name) { + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateBySourceRegex, + (const char *, const lldb::SBFileSpec &, const char *), + source_regex, source_file, module_name); + SBFileSpecList module_spec_list; if (module_name && module_name[0]) { @@ -1002,22 +1021,32 @@ source_file_list.Append(source_file); } - return BreakpointCreateBySourceRegex(source_regex, module_spec_list, - source_file_list); + return LLDB_RECORD_RESULT(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) { - return BreakpointCreateBySourceRegex(source_regex, module_list, - source_file_list, SBStringList()); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateBySourceRegex, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &), + source_regex, module_list, source_file_list); + + return LLDB_RECORD_RESULT(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) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateBySourceRegex, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &, const lldb::SBStringList &), + source_regex, module_list, source_file_list, func_names); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -1036,19 +1065,15 @@ false, hardware, move_to_nearest_code); } - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateByRegex (source_regex=\"%s\") " - "=> SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), source_regex, - static_cast<void *>(sb_bp.GetSP().get())); - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } lldb::SBBreakpoint SBTarget::BreakpointCreateForException(lldb::LanguageType language, bool catch_bp, bool throw_bp) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateForException, + (lldb::LanguageType, bool, bool), language, catch_bp, + throw_bp); SBBreakpoint sb_bp; TargetSP target_sp(GetSP()); @@ -1059,32 +1084,25 @@ hardware); } - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateForException (Language: %s, catch: " - "%s throw: %s) => SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), - Language::GetNameForLanguageType(language), - catch_bp ? "on" : "off", throw_bp ? "on" : "off", - static_cast<void *>(sb_bp.GetSP().get())); - - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } -lldb::SBBreakpoint -SBTarget::BreakpointCreateFromScript(const char *class_name, - SBStructuredData &extra_args, - const SBFileSpecList &module_list, - const SBFileSpecList &file_list, - bool request_hardware) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +lldb::SBBreakpoint SBTarget::BreakpointCreateFromScript( + const char *class_name, SBStructuredData &extra_args, + const SBFileSpecList &module_list, const SBFileSpecList &file_list, + bool request_hardware) { + LLDB_RECORD_METHOD( + lldb::SBBreakpoint, SBTarget, BreakpointCreateFromScript, + (const char *, lldb::SBStructuredData &, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &, bool), + 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, @@ -1095,18 +1113,13 @@ obj_sp, &error); } - if (log) - log->Printf("SBTarget(%p)::BreakpointCreateFromScript (class name: %s) " - " => SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), - class_name, - static_cast<void *>(sb_bp.GetSP().get())); - return sb_bp; + return LLDB_RECORD_RESULT(sb_bp); } - uint32_t SBTarget::GetNumBreakpoints() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBTarget, GetNumBreakpoints); + TargetSP target_sp(GetSP()); if (target_sp) { // The breakpoint list is thread safe, no need to lock @@ -1116,17 +1129,21 @@ } SBBreakpoint SBTarget::GetBreakpointAtIndex(uint32_t idx) const { + LLDB_RECORD_METHOD_CONST(lldb::SBBreakpoint, SBTarget, GetBreakpointAtIndex, + (uint32_t), 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; + return LLDB_RECORD_RESULT(sb_breakpoint); } bool SBTarget::BreakpointDelete(break_id_t bp_id) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBTarget, BreakpointDelete, (lldb::break_id_t), + bp_id); bool result = false; TargetSP target_sp(GetSP()); @@ -1135,16 +1152,12 @@ result = target_sp->RemoveBreakpointByID(bp_id); } - if (log) - log->Printf("SBTarget(%p)::BreakpointDelete (bp_id=%d) => %i", - static_cast<void *>(target_sp.get()), - static_cast<uint32_t>(bp_id), result); - return result; } SBBreakpoint SBTarget::FindBreakpointByID(break_id_t bp_id) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBBreakpoint, SBTarget, FindBreakpointByID, + (lldb::break_id_t), bp_id); SBBreakpoint sb_breakpoint; TargetSP target_sp(GetSP()); @@ -1153,17 +1166,14 @@ sb_breakpoint = target_sp->GetBreakpointByID(bp_id); } - if (log) - log->Printf( - "SBTarget(%p)::FindBreakpointByID (bp_id=%d) => SBBreakpoint(%p)", - static_cast<void *>(target_sp.get()), static_cast<uint32_t>(bp_id), - static_cast<void *>(sb_breakpoint.GetSP().get())); - - return sb_breakpoint; + return LLDB_RECORD_RESULT(sb_breakpoint); } bool SBTarget::FindBreakpointsByName(const char *name, SBBreakpointList &bkpts) { + LLDB_RECORD_METHOD(bool, SBTarget, FindBreakpointsByName, + (const char *, lldb::SBBreakpointList &), name, bkpts); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1179,8 +1189,10 @@ return true; } -void SBTarget::GetBreakpointNames(SBStringList &names) -{ +void SBTarget::GetBreakpointNames(SBStringList &names) { + LLDB_RECORD_METHOD(void, SBTarget, GetBreakpointNames, (lldb::SBStringList &), + names); + names.Clear(); TargetSP target_sp(GetSP()); @@ -1194,8 +1206,10 @@ } } -void SBTarget::DeleteBreakpointName(const char *name) -{ +void SBTarget::DeleteBreakpointName(const char *name) { + LLDB_RECORD_METHOD(void, SBTarget, DeleteBreakpointName, (const char *), + name); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1204,6 +1218,8 @@ } bool SBTarget::EnableAllBreakpoints() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTarget, EnableAllBreakpoints); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1214,6 +1230,8 @@ } bool SBTarget::DisableAllBreakpoints() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTarget, DisableAllBreakpoints); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1224,6 +1242,8 @@ } bool SBTarget::DeleteAllBreakpoints() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTarget, DeleteAllBreakpoints); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1235,19 +1255,29 @@ lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file, SBBreakpointList &new_bps) { + LLDB_RECORD_METHOD(lldb::SBError, SBTarget, BreakpointsCreateFromFile, + (lldb::SBFileSpec &, lldb::SBBreakpointList &), + source_file, new_bps); + SBStringList empty_name_list; - return BreakpointsCreateFromFile(source_file, empty_name_list, new_bps); + return LLDB_RECORD_RESULT( + BreakpointsCreateFromFile(source_file, empty_name_list, new_bps)); } lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file, SBStringList &matching_names, SBBreakpointList &new_bps) { + LLDB_RECORD_METHOD( + lldb::SBError, SBTarget, BreakpointsCreateFromFile, + (lldb::SBFileSpec &, lldb::SBStringList &, lldb::SBBreakpointList &), + source_file, matching_names, new_bps); + SBError sberr; TargetSP target_sp(GetSP()); if (!target_sp) { sberr.SetErrorString( "BreakpointCreateFromFile called with invalid target."); - return sberr; + return LLDB_RECORD_RESULT(sberr); } std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1261,35 +1291,42 @@ sberr.ref() = target_sp->CreateBreakpointsFromFile(source_file.ref(), name_vector, bp_ids); if (sberr.Fail()) - return sberr; + return LLDB_RECORD_RESULT(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; + return LLDB_RECORD_RESULT(sberr); } lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file) { + LLDB_RECORD_METHOD(lldb::SBError, SBTarget, BreakpointsWriteToFile, + (lldb::SBFileSpec &), dest_file); + SBError sberr; TargetSP target_sp(GetSP()); if (!target_sp) { sberr.SetErrorString("BreakpointWriteToFile called with invalid target."); - return sberr; + return LLDB_RECORD_RESULT(sberr); } SBBreakpointList bkpt_list(*this); - return BreakpointsWriteToFile(dest_file, bkpt_list); + return LLDB_RECORD_RESULT(BreakpointsWriteToFile(dest_file, bkpt_list)); } lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file, SBBreakpointList &bkpt_list, bool append) { + LLDB_RECORD_METHOD(lldb::SBError, SBTarget, BreakpointsWriteToFile, + (lldb::SBFileSpec &, lldb::SBBreakpointList &, bool), + dest_file, bkpt_list, append); + SBError sberr; TargetSP target_sp(GetSP()); if (!target_sp) { sberr.SetErrorString("BreakpointWriteToFile called with invalid target."); - return sberr; + return LLDB_RECORD_RESULT(sberr); } std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1297,10 +1334,12 @@ bkpt_list.CopyToBreakpointIDList(bp_id_list); sberr.ref() = target_sp->SerializeBreakpointsToFile(dest_file.ref(), bp_id_list, append); - return sberr; + return LLDB_RECORD_RESULT(sberr); } uint32_t SBTarget::GetNumWatchpoints() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBTarget, GetNumWatchpoints); + TargetSP target_sp(GetSP()); if (target_sp) { // The watchpoint list is thread safe, no need to lock @@ -1310,17 +1349,22 @@ } SBWatchpoint SBTarget::GetWatchpointAtIndex(uint32_t idx) const { + LLDB_RECORD_METHOD_CONST(lldb::SBWatchpoint, SBTarget, GetWatchpointAtIndex, + (uint32_t), 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; + return LLDB_RECORD_RESULT(sb_watchpoint); } bool SBTarget::DeleteWatchpoint(watch_id_t wp_id) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBTarget, DeleteWatchpoint, (lldb::watch_id_t), + wp_id); + bool result = false; TargetSP target_sp(GetSP()); @@ -1331,16 +1375,13 @@ result = target_sp->RemoveWatchpointByID(wp_id); } - if (log) - log->Printf("SBTarget(%p)::WatchpointDelete (wp_id=%d) => %i", - static_cast<void *>(target_sp.get()), - static_cast<uint32_t>(wp_id), result); - return result; } SBWatchpoint SBTarget::FindWatchpointByID(lldb::watch_id_t wp_id) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBWatchpoint, SBTarget, FindWatchpointByID, + (lldb::watch_id_t), wp_id); + SBWatchpoint sb_watchpoint; lldb::WatchpointSP watchpoint_sp; @@ -1353,19 +1394,15 @@ sb_watchpoint.SetSP(watchpoint_sp); } - if (log) - log->Printf( - "SBTarget(%p)::FindWatchpointByID (bp_id=%d) => SBWatchpoint(%p)", - static_cast<void *>(target_sp.get()), static_cast<uint32_t>(wp_id), - static_cast<void *>(watchpoint_sp.get())); - - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); } lldb::SBWatchpoint SBTarget::WatchAddress(lldb::addr_t addr, size_t size, bool read, bool write, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBWatchpoint, SBTarget, WatchAddress, + (lldb::addr_t, size_t, bool, bool, lldb::SBError &), addr, + size, read, write, error); SBWatchpoint sb_watchpoint; lldb::WatchpointSP watchpoint_sp; @@ -1381,30 +1418,25 @@ if (watch_type == 0) { error.SetErrorString( "Can't create a watchpoint that is neither read nor write."); - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); } // 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 = NULL; + CompilerType *type = nullptr; watchpoint_sp = target_sp->CreateWatchpoint(addr, size, type, watch_type, cw_error); error.SetError(cw_error); sb_watchpoint.SetSP(watchpoint_sp); } - if (log) - log->Printf("SBTarget(%p)::WatchAddress (addr=0x%" PRIx64 - ", 0x%u) => SBWatchpoint(%p)", - static_cast<void *>(target_sp.get()), addr, - static_cast<uint32_t>(size), - static_cast<void *>(watchpoint_sp.get())); - - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); } bool SBTarget::EnableAllWatchpoints() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTarget, EnableAllWatchpoints); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1417,6 +1449,8 @@ } bool SBTarget::DisableAllWatchpoints() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTarget, DisableAllWatchpoints); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1430,6 +1464,10 @@ SBValue SBTarget::CreateValueFromAddress(const char *name, SBAddress addr, SBType type) { + LLDB_RECORD_METHOD(lldb::SBValue, SBTarget, CreateValueFromAddress, + (const char *, lldb::SBAddress, lldb::SBType), name, addr, + type); + SBValue sb_value; lldb::ValueObjectSP new_value_sp; if (IsValid() && name && *name && addr.IsValid() && type.IsValid()) { @@ -1441,21 +1479,15 @@ exe_ctx, ast_type); } sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (new_value_sp) - log->Printf("SBTarget(%p)::CreateValueFromAddress => \"%s\"", - static_cast<void *>(m_opaque_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf("SBTarget(%p)::CreateValueFromAddress => NULL", - static_cast<void *>(m_opaque_sp.get())); - } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBTarget::CreateValueFromData(const char *name, lldb::SBData data, lldb::SBType type) { + LLDB_RECORD_METHOD(lldb::SBValue, SBTarget, CreateValueFromData, + (const char *, lldb::SBData, lldb::SBType), name, data, + type); + SBValue sb_value; lldb::ValueObjectSP new_value_sp; if (IsValid() && name && *name && data.IsValid() && type.IsValid()) { @@ -1467,21 +1499,14 @@ exe_ctx, ast_type); } sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (new_value_sp) - log->Printf("SBTarget(%p)::CreateValueFromData => \"%s\"", - static_cast<void *>(m_opaque_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf("SBTarget(%p)::CreateValueFromData => NULL", - static_cast<void *>(m_opaque_sp.get())); - } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBTarget::CreateValueFromExpression(const char *name, const char *expr) { + LLDB_RECORD_METHOD(lldb::SBValue, SBTarget, CreateValueFromExpression, + (const char *, const char *), name, expr); + SBValue sb_value; lldb::ValueObjectSP new_value_sp; if (IsValid() && name && *name && expr && *expr) { @@ -1491,20 +1516,12 @@ ValueObject::CreateValueObjectFromExpression(name, expr, exe_ctx); } sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (new_value_sp) - log->Printf("SBTarget(%p)::CreateValueFromExpression => \"%s\"", - static_cast<void *>(m_opaque_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf("SBTarget(%p)::CreateValueFromExpression => NULL", - static_cast<void *>(m_opaque_sp.get())); - } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } bool SBTarget::DeleteAllWatchpoints() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTarget, DeleteAllWatchpoints); + TargetSP target_sp(GetSP()); if (target_sp) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); @@ -1518,6 +1535,10 @@ void SBTarget::AppendImageSearchPath(const char *from, const char *to, lldb::SBError &error) { + LLDB_RECORD_METHOD(void, SBTarget, AppendImageSearchPath, + (const char *, const char *, lldb::SBError &), from, to, + error); + TargetSP target_sp(GetSP()); if (!target_sp) return error.SetErrorString("invalid target"); @@ -1528,21 +1549,24 @@ if (!csTo) return error.SetErrorString("<to> path can't be empty"); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBTarget(%p)::%s: '%s' -> '%s'", - static_cast<void *>(target_sp.get()), __FUNCTION__, - from, to); target_sp->GetImageSearchPathList().Append(csFrom, csTo, true); } lldb::SBModule SBTarget::AddModule(const char *path, const char *triple, const char *uuid_cstr) { - return AddModule(path, triple, uuid_cstr, NULL); + LLDB_RECORD_METHOD(lldb::SBModule, SBTarget, AddModule, + (const char *, const char *, const char *), path, triple, + uuid_cstr); + + return LLDB_RECORD_RESULT(AddModule(path, triple, uuid_cstr, nullptr)); } lldb::SBModule SBTarget::AddModule(const char *path, const char *triple, const char *uuid_cstr, const char *symfile) { + LLDB_RECORD_METHOD(lldb::SBModule, SBTarget, AddModule, + (const char *, const char *, const char *, const char *), + path, triple, uuid_cstr, symfile); + lldb::SBModule sb_module; TargetSP target_sp(GetSP()); if (target_sp) { @@ -1562,20 +1586,26 @@ if (symfile) module_spec.GetSymbolFileSpec().SetFile(symfile, FileSpec::Style::native); - sb_module.SetSP(target_sp->GetSharedModule(module_spec)); + sb_module.SetSP(target_sp->GetOrCreateModule(module_spec, true /* notify */)); } - return sb_module; + return LLDB_RECORD_RESULT(sb_module); } lldb::SBModule SBTarget::AddModule(const SBModuleSpec &module_spec) { + LLDB_RECORD_METHOD(lldb::SBModule, SBTarget, AddModule, + (const lldb::SBModuleSpec &), module_spec); + lldb::SBModule sb_module; TargetSP target_sp(GetSP()); if (target_sp) - sb_module.SetSP(target_sp->GetSharedModule(*module_spec.m_opaque_ap)); - return sb_module; + sb_module.SetSP(target_sp->GetOrCreateModule(*module_spec.m_opaque_up, + true /* notify */)); + return LLDB_RECORD_RESULT(sb_module); } bool SBTarget::AddModule(lldb::SBModule &module) { + LLDB_RECORD_METHOD(bool, SBTarget, AddModule, (lldb::SBModule &), module); + TargetSP target_sp(GetSP()); if (target_sp) { target_sp->GetImages().AppendIfNeeded(module.GetSP()); @@ -1585,7 +1615,7 @@ } uint32_t SBTarget::GetNumModules() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBTarget, GetNumModules); uint32_t num = 0; TargetSP target_sp(GetSP()); @@ -1594,24 +1624,19 @@ num = target_sp->GetImages().GetSize(); } - if (log) - log->Printf("SBTarget(%p)::GetNumModules () => %d", - static_cast<void *>(target_sp.get()), num); - return num; } void SBTarget::Clear() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) - log->Printf("SBTarget(%p)::Clear ()", - static_cast<void *>(m_opaque_sp.get())); + LLDB_RECORD_METHOD_NO_ARGS(void, SBTarget, Clear); m_opaque_sp.reset(); } SBModule SBTarget::FindModule(const SBFileSpec &sb_file_spec) { + LLDB_RECORD_METHOD(lldb::SBModule, SBTarget, FindModule, + (const lldb::SBFileSpec &), sb_file_spec); + SBModule sb_module; TargetSP target_sp(GetSP()); if (target_sp && sb_file_spec.IsValid()) { @@ -1619,11 +1644,13 @@ // The module list is thread safe, no need to lock sb_module.SetSP(target_sp->GetImages().FindFirstModule(module_spec)); } - return sb_module; + return LLDB_RECORD_RESULT(sb_module); } -SBSymbolContextList -SBTarget::FindCompileUnits(const SBFileSpec &sb_file_spec) { +SBSymbolContextList SBTarget::FindCompileUnits(const SBFileSpec &sb_file_spec) { + LLDB_RECORD_METHOD(lldb::SBSymbolContextList, SBTarget, FindCompileUnits, + (const lldb::SBFileSpec &), sb_file_spec); + SBSymbolContextList sb_sc_list; const TargetSP target_sp(GetSP()); if (target_sp && sb_file_spec.IsValid()) { @@ -1631,10 +1658,12 @@ target_sp->GetImages().FindCompileUnits(*sb_file_spec, append, *sb_sc_list); } - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); } lldb::ByteOrder SBTarget::GetByteOrder() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::ByteOrder, SBTarget, GetByteOrder); + TargetSP target_sp(GetSP()); if (target_sp) return target_sp->GetArchitecture().GetByteOrder(); @@ -1642,6 +1671,8 @@ } const char *SBTarget::GetTriple() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTarget, GetTriple); + TargetSP target_sp(GetSP()); if (target_sp) { std::string triple(target_sp->GetArchitecture().GetTriple().str()); @@ -1651,10 +1682,12 @@ ConstString const_triple(triple.c_str()); return const_triple.GetCString(); } - return NULL; + return nullptr; } uint32_t SBTarget::GetDataByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTarget, GetDataByteSize); + TargetSP target_sp(GetSP()); if (target_sp) { return target_sp->GetArchitecture().GetDataByteSize(); @@ -1663,6 +1696,8 @@ } uint32_t SBTarget::GetCodeByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTarget, GetCodeByteSize); + TargetSP target_sp(GetSP()); if (target_sp) { return target_sp->GetArchitecture().GetCodeByteSize(); @@ -1671,6 +1706,8 @@ } uint32_t SBTarget::GetAddressByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTarget, GetAddressByteSize); + TargetSP target_sp(GetSP()); if (target_sp) return target_sp->GetArchitecture().GetAddressByteSize(); @@ -1678,7 +1715,8 @@ } SBModule SBTarget::GetModuleAtIndex(uint32_t idx) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBModule, SBTarget, GetModuleAtIndex, (uint32_t), + idx); SBModule sb_module; ModuleSP module_sp; @@ -1689,15 +1727,12 @@ sb_module.SetSP(module_sp); } - if (log) - log->Printf("SBTarget(%p)::GetModuleAtIndex (idx=%d) => SBModule(%p)", - static_cast<void *>(target_sp.get()), idx, - static_cast<void *>(module_sp.get())); - - return sb_module; + return LLDB_RECORD_RESULT(sb_module); } bool SBTarget::RemoveModule(lldb::SBModule module) { + LLDB_RECORD_METHOD(bool, SBTarget, RemoveModule, (lldb::SBModule), module); + TargetSP target_sp(GetSP()); if (target_sp) return target_sp->GetImages().Remove(module.GetSP()); @@ -1705,21 +1740,23 @@ } SBBroadcaster SBTarget::GetBroadcaster() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBroadcaster, SBTarget, + GetBroadcaster); + TargetSP target_sp(GetSP()); SBBroadcaster broadcaster(target_sp.get(), false); - if (log) - log->Printf("SBTarget(%p)::GetBroadcaster () => SBBroadcaster(%p)", - static_cast<void *>(target_sp.get()), - static_cast<void *>(broadcaster.get())); - return broadcaster; + return LLDB_RECORD_RESULT(broadcaster); } bool SBTarget::GetDescription(SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTarget, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + Stream &strm = description.ref(); TargetSP target_sp(GetSP()); @@ -1733,13 +1770,16 @@ lldb::SBSymbolContextList SBTarget::FindFunctions(const char *name, uint32_t name_type_mask) { + LLDB_RECORD_METHOD(lldb::SBSymbolContextList, SBTarget, FindFunctions, + (const char *, uint32_t), name, name_type_mask); + lldb::SBSymbolContextList sb_sc_list; if (!name | !name[0]) - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); TargetSP target_sp(GetSP()); if (!target_sp) - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); const bool symbols_ok = true; const bool inlines_ok = true; @@ -1747,12 +1787,16 @@ FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask); target_sp->GetImages().FindFunctions(ConstString(name), mask, symbols_ok, inlines_ok, append, *sb_sc_list); - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); } lldb::SBSymbolContextList SBTarget::FindGlobalFunctions(const char *name, uint32_t max_matches, MatchType matchtype) { + LLDB_RECORD_METHOD(lldb::SBSymbolContextList, SBTarget, FindGlobalFunctions, + (const char *, uint32_t, lldb::MatchType), name, + max_matches, matchtype); + lldb::SBSymbolContextList sb_sc_list; if (name && name[0]) { llvm::StringRef name_ref(name); @@ -1777,10 +1821,13 @@ } } } - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); } lldb::SBType SBTarget::FindFirstType(const char *typename_cstr) { + LLDB_RECORD_METHOD(lldb::SBType, SBTarget, FindFirstType, (const char *), + typename_cstr); + TargetSP target_sp(GetSP()); if (typename_cstr && typename_cstr[0] && target_sp) { ConstString const_typename(typename_cstr); @@ -1795,30 +1842,17 @@ TypeSP type_sp( module_sp->FindFirstType(sc, const_typename, exact_match)); if (type_sp) - return SBType(type_sp); + return LLDB_RECORD_RESULT(SBType(type_sp)); } } - // Didn't find the type in the symbols; try the Objective-C runtime if one - // is installed - - ProcessSP process_sp(target_sp->GetProcessSP()); - - if (process_sp) { - ObjCLanguageRuntime *objc_language_runtime = - process_sp->GetObjCLanguageRuntime(); - - if (objc_language_runtime) { - DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor(); - - if (objc_decl_vendor) { - std::vector<clang::NamedDecl *> decls; - - if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) { - if (CompilerType type = ClangASTContext::GetTypeForDecl(decls[0])) { - return SBType(type); - } - } + // 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 LLDB_RECORD_RESULT(SBType(types.front())); } } } @@ -1826,24 +1860,30 @@ // No matches, search for basic typename matches ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); if (clang_ast) - return SBType(ClangASTContext::GetBasicType(clang_ast->getASTContext(), - const_typename)); + return LLDB_RECORD_RESULT(SBType(ClangASTContext::GetBasicType( + clang_ast->getASTContext(), const_typename))); } - return SBType(); + return LLDB_RECORD_RESULT(SBType()); } SBType SBTarget::GetBasicType(lldb::BasicType type) { + LLDB_RECORD_METHOD(lldb::SBType, SBTarget, GetBasicType, (lldb::BasicType), + type); + TargetSP target_sp(GetSP()); if (target_sp) { ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); if (clang_ast) - return SBType( - ClangASTContext::GetBasicType(clang_ast->getASTContext(), type)); + return LLDB_RECORD_RESULT(SBType( + ClangASTContext::GetBasicType(clang_ast->getASTContext(), type))); } - return SBType(); + return LLDB_RECORD_RESULT(SBType()); } lldb::SBTypeList SBTarget::FindTypes(const char *typename_cstr) { + LLDB_RECORD_METHOD(lldb::SBTypeList, SBTarget, FindTypes, (const char *), + typename_cstr); + SBTypeList sb_type_list; TargetSP target_sp(GetSP()); if (typename_cstr && typename_cstr[0] && target_sp) { @@ -1864,27 +1904,14 @@ } } - // Try the Objective-C runtime if one is installed - - ProcessSP process_sp(target_sp->GetProcessSP()); - - if (process_sp) { - ObjCLanguageRuntime *objc_language_runtime = - process_sp->GetObjCLanguageRuntime(); - - if (objc_language_runtime) { - DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor(); - - if (objc_decl_vendor) { - std::vector<clang::NamedDecl *> decls; - - if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) { - for (clang::NamedDecl *decl : decls) { - if (CompilerType type = ClangASTContext::GetTypeForDecl(decl)) { - sb_type_list.Append(SBType(type)); - } - } - } + // 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)); } } } @@ -1897,11 +1924,14 @@ clang_ast->getASTContext(), const_typename))); } } - return sb_type_list; + return LLDB_RECORD_RESULT(sb_type_list); } SBValueList SBTarget::FindGlobalVariables(const char *name, uint32_t max_matches) { + LLDB_RECORD_METHOD(lldb::SBValueList, SBTarget, FindGlobalVariables, + (const char *, uint32_t), name, max_matches); + SBValueList sb_value_list; TargetSP target_sp(GetSP()); @@ -1912,7 +1942,7 @@ if (match_count > 0) { ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); - if (exe_scope == NULL) + if (exe_scope == nullptr) exe_scope = target_sp.get(); for (uint32_t i = 0; i < match_count; ++i) { lldb::ValueObjectSP valobj_sp(ValueObjectVariable::Create( @@ -1923,12 +1953,16 @@ } } - return sb_value_list; + return LLDB_RECORD_RESULT(sb_value_list); } SBValueList SBTarget::FindGlobalVariables(const char *name, uint32_t max_matches, MatchType matchtype) { + LLDB_RECORD_METHOD(lldb::SBValueList, SBTarget, FindGlobalVariables, + (const char *, uint32_t, lldb::MatchType), name, + max_matches, matchtype); + SBValueList sb_value_list; TargetSP target_sp(GetSP()); @@ -1956,7 +1990,7 @@ if (match_count > 0) { ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); - if (exe_scope == NULL) + if (exe_scope == nullptr) exe_scope = target_sp.get(); for (uint32_t i = 0; i < match_count; ++i) { lldb::ValueObjectSP valobj_sp(ValueObjectVariable::Create( @@ -1967,29 +2001,41 @@ } } - return sb_value_list; + return LLDB_RECORD_RESULT(sb_value_list); } lldb::SBValue SBTarget::FindFirstGlobalVariable(const char *name) { + LLDB_RECORD_METHOD(lldb::SBValue, SBTarget, FindFirstGlobalVariable, + (const char *), 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(); + return LLDB_RECORD_RESULT(sb_value_list.GetValueAtIndex(0)); + return LLDB_RECORD_RESULT(SBValue()); } SBSourceManager SBTarget::GetSourceManager() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSourceManager, SBTarget, GetSourceManager); + SBSourceManager source_manager(*this); - return source_manager; + return LLDB_RECORD_RESULT(source_manager); } lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr, uint32_t count) { - return ReadInstructions(base_addr, count, NULL); + LLDB_RECORD_METHOD(lldb::SBInstructionList, SBTarget, ReadInstructions, + (lldb::SBAddress, uint32_t), base_addr, count); + + return LLDB_RECORD_RESULT(ReadInstructions(base_addr, count, nullptr)); } lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr, uint32_t count, const char *flavor_string) { + LLDB_RECORD_METHOD(lldb::SBInstructionList, SBTarget, ReadInstructions, + (lldb::SBAddress, uint32_t, const char *), base_addr, + count, flavor_string); + SBInstructionList sb_instructions; TargetSP target_sp(GetSP()); @@ -2007,24 +2053,33 @@ data.GetByteSize(), error, &load_addr); const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS; sb_instructions.SetDisassembler(Disassembler::DisassembleBytes( - target_sp->GetArchitecture(), NULL, flavor_string, *addr_ptr, + target_sp->GetArchitecture(), nullptr, flavor_string, *addr_ptr, data.GetBytes(), bytes_read, count, data_from_file)); } } - return sb_instructions; + return LLDB_RECORD_RESULT(sb_instructions); } lldb::SBInstructionList SBTarget::GetInstructions(lldb::SBAddress base_addr, const void *buf, size_t size) { - return GetInstructionsWithFlavor(base_addr, NULL, buf, size); + LLDB_RECORD_DUMMY(lldb::SBInstructionList, SBTarget, GetInstructions, + (lldb::SBAddress, const void *, size_t), 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_RECORD_DUMMY(lldb::SBInstructionList, SBTarget, + GetInstructionsWithFlavor, + (lldb::SBAddress, const char *, const void *, size_t), + base_addr, flavor_string, buf, size); + SBInstructionList sb_instructions; TargetSP target_sp(GetSP()); @@ -2037,7 +2092,7 @@ const bool data_from_file = true; sb_instructions.SetDisassembler(Disassembler::DisassembleBytes( - target_sp->GetArchitecture(), NULL, flavor_string, addr, buf, size, + target_sp->GetArchitecture(), nullptr, flavor_string, addr, buf, size, UINT32_MAX, data_from_file)); } @@ -2047,7 +2102,10 @@ lldb::SBInstructionList SBTarget::GetInstructions(lldb::addr_t base_addr, const void *buf, size_t size) { - return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), NULL, buf, + LLDB_RECORD_DUMMY(lldb::SBInstructionList, SBTarget, GetInstructions, + (lldb::addr_t, const void *, size_t), base_addr, buf, size); + + return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), nullptr, buf, size); } @@ -2055,12 +2113,21 @@ SBTarget::GetInstructionsWithFlavor(lldb::addr_t base_addr, const char *flavor_string, const void *buf, size_t size) { + LLDB_RECORD_DUMMY(lldb::SBInstructionList, SBTarget, + GetInstructionsWithFlavor, + (lldb::addr_t, const char *, const void *, size_t), + 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_RECORD_METHOD(lldb::SBError, SBTarget, SetSectionLoadAddress, + (lldb::SBSection, lldb::addr_t), section, + section_base_addr); + SBError sb_error; TargetSP target_sp(GetSP()); if (target_sp) { @@ -2091,10 +2158,13 @@ } else { sb_error.SetErrorString("invalid target"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBTarget::ClearSectionLoadAddress(lldb::SBSection section) { + LLDB_RECORD_METHOD(lldb::SBError, SBTarget, ClearSectionLoadAddress, + (lldb::SBSection), section); + SBError sb_error; TargetSP target_sp(GetSP()); @@ -2123,11 +2193,14 @@ } else { sb_error.SetErrorStringWithFormat("invalid target"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module, int64_t slide_offset) { + LLDB_RECORD_METHOD(lldb::SBError, SBTarget, SetModuleLoadAddress, + (lldb::SBModule, int64_t), module, slide_offset); + SBError sb_error; TargetSP target_sp(GetSP()); @@ -2155,10 +2228,13 @@ } else { sb_error.SetErrorStringWithFormat("invalid target"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBTarget::ClearModuleLoadAddress(lldb::SBModule module) { + LLDB_RECORD_METHOD(lldb::SBError, SBTarget, ClearModuleLoadAddress, + (lldb::SBModule), module); + SBError sb_error; char path[PATH_MAX]; @@ -2204,11 +2280,14 @@ } else { sb_error.SetErrorStringWithFormat("invalid target"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } lldb::SBSymbolContextList SBTarget::FindSymbols(const char *name, lldb::SymbolType symbol_type) { + LLDB_RECORD_METHOD(lldb::SBSymbolContextList, SBTarget, FindSymbols, + (const char *, lldb::SymbolType), name, symbol_type); + SBSymbolContextList sb_sc_list; if (name && name[0]) { TargetSP target_sp(GetSP()); @@ -2218,46 +2297,44 @@ ConstString(name), symbol_type, *sb_sc_list, append); } } - return sb_sc_list; + return LLDB_RECORD_RESULT(sb_sc_list); } lldb::SBValue SBTarget::EvaluateExpression(const char *expr) { + LLDB_RECORD_METHOD(lldb::SBValue, SBTarget, EvaluateExpression, + (const char *), expr); + TargetSP target_sp(GetSP()); if (!target_sp) - return SBValue(); + return LLDB_RECORD_RESULT(SBValue()); SBExpressionOptions options; lldb::DynamicValueType fetch_dynamic_value = target_sp->GetPreferDynamicValue(); options.SetFetchDynamicValue(fetch_dynamic_value); options.SetUnwindOnError(true); - return EvaluateExpression(expr, options); + return LLDB_RECORD_RESULT(EvaluateExpression(expr, options)); } lldb::SBValue SBTarget::EvaluateExpression(const char *expr, const SBExpressionOptions &options) { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -#if !defined(LLDB_DISABLE_PYTHON) + LLDB_RECORD_METHOD(lldb::SBValue, SBTarget, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &), expr, + options); + Log *expr_log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); -#endif SBValue expr_result; - ExpressionResults exe_results = eExpressionSetupError; ValueObjectSP expr_value_sp; TargetSP target_sp(GetSP()); - StackFrame *frame = NULL; + StackFrame *frame = nullptr; if (target_sp) { - if (expr == NULL || expr[0] == '\0') { - if (log) - log->Printf( - "SBTarget::EvaluateExpression called with an empty expression"); - return expr_result; + if (expr == nullptr || expr[0] == '\0') { + return LLDB_RECORD_RESULT(expr_result); } std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); ExecutionContext exe_ctx(m_opaque_sp.get()); - if (log) - log->Printf("SBTarget()::EvaluateExpression (expr=\"%s\")...", expr); frame = exe_ctx.GetFramePtr(); Target *target = exe_ctx.GetTargetPtr(); @@ -2273,33 +2350,21 @@ expr, options.GetFetchDynamicValue(), frame_description.GetString().str().c_str()); #endif - exe_results = - target->EvaluateExpression(expr, frame, expr_value_sp, options.ref()); + target->EvaluateExpression(expr, frame, expr_value_sp, options.ref()); expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); - } else { - if (log) - log->Printf("SBTarget::EvaluateExpression () => error: could not " - "reconstruct frame object for this SBTarget."); } } -#ifndef LLDB_DISABLE_PYTHON if (expr_log) expr_log->Printf("** [SBTarget::EvaluateExpression] Expression result is " "%s, summary %s **", expr_result.GetValue(), expr_result.GetSummary()); - - if (log) - log->Printf("SBTarget(%p)::EvaluateExpression (expr=\"%s\") => SBValue(%p) " - "(execution result=%d)", - static_cast<void *>(frame), expr, - static_cast<void *>(expr_value_sp.get()), exe_results); -#endif - - return expr_result; + return LLDB_RECORD_RESULT(expr_result); } lldb::addr_t SBTarget::GetStackRedZoneSize() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBTarget, GetStackRedZoneSize); + TargetSP target_sp(GetSP()); if (target_sp) { ABISP abi_sp; @@ -2315,15 +2380,267 @@ } lldb::SBLaunchInfo SBTarget::GetLaunchInfo() const { - lldb::SBLaunchInfo launch_info(NULL); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBLaunchInfo, SBTarget, GetLaunchInfo); + + lldb::SBLaunchInfo launch_info(nullptr); TargetSP target_sp(GetSP()); if (target_sp) launch_info.set_ref(m_opaque_sp->GetProcessLaunchInfo()); - return launch_info; + return LLDB_RECORD_RESULT(launch_info); } void SBTarget::SetLaunchInfo(const lldb::SBLaunchInfo &launch_info) { + LLDB_RECORD_METHOD(void, SBTarget, SetLaunchInfo, + (const lldb::SBLaunchInfo &), launch_info); + TargetSP target_sp(GetSP()); if (target_sp) m_opaque_sp->SetProcessLaunchInfo(launch_info.ref()); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTarget>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTarget, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTarget, (const lldb::SBTarget &)); + LLDB_REGISTER_CONSTRUCTOR(SBTarget, (const lldb::TargetSP &)); + LLDB_REGISTER_METHOD(const lldb::SBTarget &, + SBTarget, operator=,(const lldb::SBTarget &)); + LLDB_REGISTER_STATIC_METHOD(bool, SBTarget, EventIsTargetEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBTarget, SBTarget, GetTargetFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(uint32_t, SBTarget, GetNumModulesFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBModule, SBTarget, + GetModuleAtIndexFromEvent, + (const uint32_t, const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(const char *, SBTarget, GetBroadcasterClassName, + ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTarget, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTarget, operator bool, ()); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, GetProcess, ()); + LLDB_REGISTER_METHOD(lldb::SBPlatform, SBTarget, GetPlatform, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBDebugger, SBTarget, GetDebugger, ()); + LLDB_REGISTER_METHOD(lldb::SBStructuredData, SBTarget, GetStatistics, ()); + LLDB_REGISTER_METHOD(void, SBTarget, SetCollectingStats, (bool)); + LLDB_REGISTER_METHOD(bool, SBTarget, GetCollectingStats, ()); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, LoadCore, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, LoadCore, + (const char *, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, LaunchSimple, + (const char **, const char **, const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, Install, ()); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, Launch, + (lldb::SBListener &, const char **, const char **, + const char *, const char *, const char *, + const char *, uint32_t, bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, Launch, + (lldb::SBLaunchInfo &, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, Attach, + (lldb::SBAttachInfo &, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBTarget, AttachToProcessWithID, + (lldb::SBListener &, lldb::pid_t, lldb::SBError &)); + LLDB_REGISTER_METHOD( + lldb::SBProcess, SBTarget, AttachToProcessWithName, + (lldb::SBListener &, const char *, bool, lldb::SBError &)); + LLDB_REGISTER_METHOD( + lldb::SBProcess, SBTarget, ConnectRemote, + (lldb::SBListener &, const char *, const char *, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBFileSpec, SBTarget, GetExecutable, ()); + LLDB_REGISTER_METHOD_CONST(bool, + SBTarget, operator==,(const lldb::SBTarget &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBTarget, operator!=,(const lldb::SBTarget &)); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBTarget, ResolveLoadAddress, + (lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBTarget, ResolveFileAddress, + (lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBTarget, ResolvePastLoadAddress, + (uint32_t, lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContext, SBTarget, + ResolveSymbolContextForAddress, + (const lldb::SBAddress &, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateByLocation, (const char *, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t, lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t, lldb::addr_t, + lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateByLocation, + (const lldb::SBFileSpec &, uint32_t, uint32_t, + lldb::addr_t, lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, const char *)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, uint32_t, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByName, + (const char *, uint32_t, lldb::LanguageType, + const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByNames, + (const char **, uint32_t, uint32_t, + const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByNames, + (const char **, uint32_t, uint32_t, lldb::LanguageType, + const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByNames, + (const char **, uint32_t, uint32_t, lldb::LanguageType, + lldb::addr_t, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByRegex, + (const char *, const char *)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByRegex, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, BreakpointCreateByRegex, + (const char *, lldb::LanguageType, + const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateByAddress, (lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateBySBAddress, (lldb::SBAddress &)); + LLDB_REGISTER_METHOD( + lldb::SBBreakpoint, SBTarget, BreakpointCreateBySourceRegex, + (const char *, const lldb::SBFileSpec &, const char *)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateBySourceRegex, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &)); + LLDB_REGISTER_METHOD( + lldb::SBBreakpoint, SBTarget, BreakpointCreateBySourceRegex, + (const char *, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &, const lldb::SBStringList &)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, + BreakpointCreateForException, + (lldb::LanguageType, bool, bool)); + LLDB_REGISTER_METHOD( + lldb::SBBreakpoint, SBTarget, BreakpointCreateFromScript, + (const char *, lldb::SBStructuredData &, const lldb::SBFileSpecList &, + const lldb::SBFileSpecList &, bool)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBTarget, GetNumBreakpoints, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBBreakpoint, SBTarget, + GetBreakpointAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTarget, BreakpointDelete, (lldb::break_id_t)); + LLDB_REGISTER_METHOD(lldb::SBBreakpoint, SBTarget, FindBreakpointByID, + (lldb::break_id_t)); + LLDB_REGISTER_METHOD(bool, SBTarget, FindBreakpointsByName, + (const char *, lldb::SBBreakpointList &)); + LLDB_REGISTER_METHOD(void, SBTarget, GetBreakpointNames, + (lldb::SBStringList &)); + LLDB_REGISTER_METHOD(void, SBTarget, DeleteBreakpointName, (const char *)); + LLDB_REGISTER_METHOD(bool, SBTarget, EnableAllBreakpoints, ()); + LLDB_REGISTER_METHOD(bool, SBTarget, DisableAllBreakpoints, ()); + LLDB_REGISTER_METHOD(bool, SBTarget, DeleteAllBreakpoints, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, BreakpointsCreateFromFile, + (lldb::SBFileSpec &, lldb::SBBreakpointList &)); + LLDB_REGISTER_METHOD( + lldb::SBError, SBTarget, BreakpointsCreateFromFile, + (lldb::SBFileSpec &, lldb::SBStringList &, lldb::SBBreakpointList &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, BreakpointsWriteToFile, + (lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, BreakpointsWriteToFile, + (lldb::SBFileSpec &, lldb::SBBreakpointList &, bool)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBTarget, GetNumWatchpoints, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBWatchpoint, SBTarget, + GetWatchpointAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTarget, DeleteWatchpoint, (lldb::watch_id_t)); + LLDB_REGISTER_METHOD(lldb::SBWatchpoint, SBTarget, FindWatchpointByID, + (lldb::watch_id_t)); + LLDB_REGISTER_METHOD(lldb::SBWatchpoint, SBTarget, WatchAddress, + (lldb::addr_t, size_t, bool, bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(bool, SBTarget, EnableAllWatchpoints, ()); + LLDB_REGISTER_METHOD(bool, SBTarget, DisableAllWatchpoints, ()); + LLDB_REGISTER_METHOD(lldb::SBValue, SBTarget, CreateValueFromAddress, + (const char *, lldb::SBAddress, lldb::SBType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBTarget, CreateValueFromData, + (const char *, lldb::SBData, lldb::SBType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBTarget, CreateValueFromExpression, + (const char *, const char *)); + LLDB_REGISTER_METHOD(bool, SBTarget, DeleteAllWatchpoints, ()); + LLDB_REGISTER_METHOD(void, SBTarget, AppendImageSearchPath, + (const char *, const char *, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBModule, SBTarget, AddModule, + (const char *, const char *, const char *)); + LLDB_REGISTER_METHOD( + lldb::SBModule, SBTarget, AddModule, + (const char *, const char *, const char *, const char *)); + LLDB_REGISTER_METHOD(lldb::SBModule, SBTarget, AddModule, + (const lldb::SBModuleSpec &)); + LLDB_REGISTER_METHOD(bool, SBTarget, AddModule, (lldb::SBModule &)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBTarget, GetNumModules, ()); + LLDB_REGISTER_METHOD(void, SBTarget, Clear, ()); + LLDB_REGISTER_METHOD(lldb::SBModule, SBTarget, FindModule, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContextList, SBTarget, FindCompileUnits, + (const lldb::SBFileSpec &)); + LLDB_REGISTER_METHOD(lldb::ByteOrder, SBTarget, GetByteOrder, ()); + LLDB_REGISTER_METHOD(const char *, SBTarget, GetTriple, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTarget, GetDataByteSize, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTarget, GetCodeByteSize, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTarget, GetAddressByteSize, ()); + LLDB_REGISTER_METHOD(lldb::SBModule, SBTarget, GetModuleAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTarget, RemoveModule, (lldb::SBModule)); + LLDB_REGISTER_METHOD_CONST(lldb::SBBroadcaster, SBTarget, GetBroadcaster, + ()); + LLDB_REGISTER_METHOD(bool, SBTarget, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContextList, SBTarget, FindFunctions, + (const char *, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContextList, SBTarget, + FindGlobalFunctions, + (const char *, uint32_t, lldb::MatchType)); + LLDB_REGISTER_METHOD(lldb::SBType, SBTarget, FindFirstType, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBType, SBTarget, GetBasicType, + (lldb::BasicType)); + LLDB_REGISTER_METHOD(lldb::SBTypeList, SBTarget, FindTypes, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBTarget, FindGlobalVariables, + (const char *, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBValueList, SBTarget, FindGlobalVariables, + (const char *, uint32_t, lldb::MatchType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBTarget, FindFirstGlobalVariable, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBSourceManager, SBTarget, GetSourceManager, ()); + LLDB_REGISTER_METHOD(lldb::SBInstructionList, SBTarget, ReadInstructions, + (lldb::SBAddress, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBInstructionList, SBTarget, ReadInstructions, + (lldb::SBAddress, uint32_t, const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, SetSectionLoadAddress, + (lldb::SBSection, lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, ClearSectionLoadAddress, + (lldb::SBSection)); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, SetModuleLoadAddress, + (lldb::SBModule, int64_t)); + LLDB_REGISTER_METHOD(lldb::SBError, SBTarget, ClearModuleLoadAddress, + (lldb::SBModule)); + LLDB_REGISTER_METHOD(lldb::SBSymbolContextList, SBTarget, FindSymbols, + (const char *, lldb::SymbolType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBTarget, EvaluateExpression, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBTarget, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &)); + LLDB_REGISTER_METHOD(lldb::addr_t, SBTarget, GetStackRedZoneSize, ()); + LLDB_REGISTER_METHOD_CONST(lldb::SBLaunchInfo, SBTarget, GetLaunchInfo, ()); + LLDB_REGISTER_METHOD(void, SBTarget, SetLaunchInfo, + (const lldb::SBLaunchInfo &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBThread.cpp b/src/llvm-project/lldb/source/API/SBThread.cpp index 2c859d5..85e9a6b 100644 --- a/src/llvm-project/lldb/source/API/SBThread.cpp +++ b/src/llvm-project/lldb/source/API/SBThread.cpp
@@ -1,17 +1,25 @@ //===-- SBThread.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.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/SBFrame.h" +#include "lldb/API/SBProcess.h" #include "lldb/API/SBStream.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/StreamFile.h" @@ -34,57 +42,58 @@ #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/SBThreadCollection.h" -#include "lldb/API/SBThreadPlan.h" -#include "lldb/API/SBValue.h" #include "lldb/lldb-enumerations.h" +#include <memory> + using namespace lldb; using namespace lldb_private; const char *SBThread::GetBroadcasterClassName() { + LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBThread, + GetBroadcasterClassName); + return Thread::GetStaticBroadcasterClass().AsCString(); } -//---------------------------------------------------------------------- // Constructors -//---------------------------------------------------------------------- -SBThread::SBThread() : m_opaque_sp(new ExecutionContextRef()) {} - -SBThread::SBThread(const ThreadSP &lldb_object_sp) - : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) {} - -SBThread::SBThread(const SBThread &rhs) - : m_opaque_sp(new ExecutionContextRef(*rhs.m_opaque_sp)) {} - -//---------------------------------------------------------------------- -// Assignment operator -//---------------------------------------------------------------------- - -const lldb::SBThread &SBThread::operator=(const SBThread &rhs) { - if (this != &rhs) - *m_opaque_sp = *rhs.m_opaque_sp; - return *this; +SBThread::SBThread() : m_opaque_sp(new ExecutionContextRef()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBThread); } -//---------------------------------------------------------------------- +SBThread::SBThread(const ThreadSP &lldb_object_sp) + : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) { + LLDB_RECORD_CONSTRUCTOR(SBThread, (const lldb::ThreadSP &), lldb_object_sp); +} + +SBThread::SBThread(const SBThread &rhs) : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR(SBThread, (const lldb::SBThread &), rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); +} + +// Assignment operator + +const lldb::SBThread &SBThread::operator=(const SBThread &rhs) { + LLDB_RECORD_METHOD(const lldb::SBThread &, + SBThread, operator=,(const lldb::SBThread &), rhs); + + if (this != &rhs) + m_opaque_sp = clone(rhs.m_opaque_sp); + return LLDB_RECORD_RESULT(*this); +} + // Destructor -//---------------------------------------------------------------------- SBThread::~SBThread() {} lldb::SBQueue SBThread::GetQueue() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBQueue, SBThread, GetQueue); + SBQueue sb_queue; QueueSP queue_sp; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (exe_ctx.HasThreadScope()) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { @@ -92,22 +101,19 @@ if (queue_sp) { sb_queue.SetQueue(queue_sp); } - } else { - if (log) - log->Printf("SBThread(%p)::GetQueue() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetQueue () => SBQueue(%p)", - static_cast<void *>(exe_ctx.GetThreadPtr()), - static_cast<void *>(queue_sp.get())); - - return sb_queue; + return LLDB_RECORD_RESULT(sb_queue); } bool SBThread::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBThread, IsValid); + return this->operator bool(); +} +SBThread::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBThread, operator bool); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -116,16 +122,20 @@ if (target && process) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process->GetRunLock())) - return m_opaque_sp->GetThreadSP().get() != NULL; + return m_opaque_sp->GetThreadSP().get() != nullptr; } // Without a valid target & process, this thread can't be valid. return false; } -void SBThread::Clear() { m_opaque_sp->Clear(); } +void SBThread::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBThread, Clear); + + m_opaque_sp->Clear(); +} StopReason SBThread::GetStopReason() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::StopReason, SBThread, GetStopReason); StopReason reason = eStopReasonInvalid; std::unique_lock<std::recursive_mutex> lock; @@ -135,23 +145,15 @@ Process::StopLocker stop_locker; if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { return exe_ctx.GetThreadPtr()->GetStopReason(); - } else { - if (log) - log->Printf( - "SBThread(%p)::GetStopReason() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetStopReason () => %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), - Thread::StopReasonAsCString(reason)); - return reason; } size_t SBThread::GetStopReasonDataCount() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBThread, GetStopReasonDataCount); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -193,18 +195,15 @@ return 1; } } - } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBThread(%p)::GetStopReasonDataCount() => error: process " - "is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } return 0; } uint64_t SBThread::GetStopReasonDataAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(uint64_t, SBThread, GetStopReasonDataAtIndex, (uint32_t), + idx); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -258,18 +257,15 @@ return stop_info_sp->GetValue(); } } - } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBThread(%p)::GetStopReasonDataAtIndex() => error: " - "process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } return 0; } bool SBThread::GetStopReasonExtendedInfoAsJSON(lldb::SBStream &stream) { + LLDB_RECORD_METHOD(bool, SBThread, GetStopReasonExtendedInfoAsJSON, + (lldb::SBStream &), stream); + Stream &strm = stream.ref(); std::unique_lock<std::recursive_mutex> lock; @@ -290,28 +286,33 @@ SBThreadCollection SBThread::GetStopReasonExtendedBacktraces(InstrumentationRuntimeType type) { + LLDB_RECORD_METHOD(lldb::SBThreadCollection, SBThread, + GetStopReasonExtendedBacktraces, + (lldb::InstrumentationRuntimeType), type); + ThreadCollectionSP threads; - threads.reset(new ThreadCollection()); + threads = std::make_shared<ThreadCollection>(); std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); if (!exe_ctx.HasThreadScope()) - return threads; + return LLDB_RECORD_RESULT(threads); ProcessSP process_sp = exe_ctx.GetProcessSP(); StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); if (!info) - return threads; + return LLDB_RECORD_RESULT(threads); - return process_sp->GetInstrumentationRuntime(type) - ->GetBacktracesFromExtendedStopInfo(info); + return LLDB_RECORD_RESULT(process_sp->GetInstrumentationRuntime(type) + ->GetBacktracesFromExtendedStopInfo(info)); } size_t SBThread::GetStopDescription(char *dst, size_t dst_len) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(size_t, SBThread, GetStopDescription, (char *, size_t), + dst, dst_len); std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -324,10 +325,6 @@ if (stop_info_sp) { const char *stop_desc = stop_info_sp->GetDescription(); if (stop_desc) { - if (log) - log->Printf( - "SBThread(%p)::GetStopDescription (dst, dst_len) => \"%s\"", - static_cast<void *>(exe_ctx.GetThreadPtr()), stop_desc); if (dst) return ::snprintf(dst, dst_len, "%s", stop_desc); else { @@ -362,7 +359,7 @@ stop_desc = exe_ctx.GetProcessPtr()->GetUnixSignals()->GetSignalAsCString( stop_info_sp->GetValue()); - if (stop_desc == NULL || stop_desc[0] == '\0') { + if (stop_desc == nullptr || stop_desc[0] == '\0') { static char signal_desc[] = "signal"; stop_desc = signal_desc; stop_desc_len = @@ -392,11 +389,6 @@ } if (stop_desc && stop_desc[0]) { - if (log) - log->Printf( - "SBThread(%p)::GetStopDescription (dst, dst_len) => '%s'", - static_cast<void *>(exe_ctx.GetThreadPtr()), stop_desc); - if (dst) return ::snprintf(dst, dst_len, "%s", stop_desc) + 1; // Include the NULL byte @@ -408,12 +400,6 @@ } } } - } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf( - "SBThread(%p)::GetStopDescription() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } if (dst) @@ -422,7 +408,8 @@ } SBValue SBThread::GetStopReturnValue() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValue, SBThread, GetStopReturnValue); + ValueObjectSP return_valobj_sp; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -434,21 +421,10 @@ if (stop_info_sp) { return_valobj_sp = StopInfo::GetReturnValueObject(stop_info_sp); } - } else { - if (log) - log->Printf( - "SBThread(%p)::GetStopReturnValue() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetStopReturnValue () => %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), - return_valobj_sp.get() ? return_valobj_sp->GetValueAsCString() - : "<no return value>"); - - return SBValue(return_valobj_sp); + return LLDB_RECORD_RESULT(SBValue(return_valobj_sp)); } void SBThread::SetThread(const ThreadSP &lldb_object_sp) { @@ -456,6 +432,8 @@ } lldb::tid_t SBThread::GetThreadID() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::tid_t, SBThread, GetThreadID); + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); if (thread_sp) return thread_sp->GetID(); @@ -463,6 +441,8 @@ } uint32_t SBThread::GetIndexID() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBThread, GetIndexID); + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); if (thread_sp) return thread_sp->GetIndexID(); @@ -470,8 +450,9 @@ } const char *SBThread::GetName() const { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *name = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBThread, GetName); + + const char *name = nullptr; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -479,72 +460,50 @@ Process::StopLocker stop_locker; if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { name = exe_ctx.GetThreadPtr()->GetName(); - } else { - if (log) - log->Printf("SBThread(%p)::GetName() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetName () => %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), - name ? name : "NULL"); - return name; } const char *SBThread::GetQueueName() const { - const char *name = NULL; + LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBThread, GetQueueName); + + const char *name = nullptr; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (exe_ctx.HasThreadScope()) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { name = exe_ctx.GetThreadPtr()->GetQueueName(); - } else { - if (log) - log->Printf("SBThread(%p)::GetQueueName() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetQueueName () => %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), - name ? name : "NULL"); - return name; } lldb::queue_id_t SBThread::GetQueueID() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::queue_id_t, SBThread, GetQueueID); + queue_id_t id = LLDB_INVALID_QUEUE_ID; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (exe_ctx.HasThreadScope()) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { id = exe_ctx.GetThreadPtr()->GetQueueID(); - } else { - if (log) - log->Printf("SBThread(%p)::GetQueueID() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetQueueID () => 0x%" PRIx64, - static_cast<void *>(exe_ctx.GetThreadPtr()), id); - return id; } bool SBThread::GetInfoItemByPathAsString(const char *path, SBStream &strm) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBThread, GetInfoItemByPathAsString, + (const char *, lldb::SBStream &), path, strm); + bool success = false; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -583,18 +542,9 @@ } } } - } else { - if (log) - log->Printf("SBThread(%p)::GetInfoItemByPathAsString() => error: " - "process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetInfoItemByPathAsString (\"%s\") => \"%s\"", - static_cast<void *>(exe_ctx.GetThreadPtr()), path, strm.GetData()); - return success; } @@ -616,7 +566,7 @@ // User level plans should be Master Plans so they can be interrupted, other // plans executed, and then a "continue" will resume the plan. - if (new_plan != NULL) { + if (new_plan != nullptr) { new_plan->SetIsMasterPlan(true); new_plan->SetOkayToDiscard(false); } @@ -627,27 +577,26 @@ if (process->GetTarget().GetDebugger().GetAsyncExecution()) sb_error.ref() = process->Resume(); else - sb_error.ref() = process->ResumeSynchronous(NULL); + sb_error.ref() = process->ResumeSynchronous(nullptr); return sb_error; } void SBThread::StepOver(lldb::RunMode stop_other_threads) { + LLDB_RECORD_METHOD(void, SBThread, StepOver, (lldb::RunMode), + stop_other_threads); + SBError error; // Ignored StepOver(stop_other_threads, error); } void SBThread::StepOver(lldb::RunMode stop_other_threads, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBThread, StepOver, (lldb::RunMode, lldb::SBError &), + stop_other_threads, error); std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBThread(%p)::StepOver (stop_other_threads='%s')", - static_cast<void *>(exe_ctx.GetThreadPtr()), - Thread::RunModeAsCString(stop_other_threads)); - if (!exe_ctx.HasThreadScope()) { error.SetErrorString("this SBThread object is invalid"); return; @@ -675,29 +624,31 @@ } void SBThread::StepInto(lldb::RunMode stop_other_threads) { - StepInto(NULL, stop_other_threads); + LLDB_RECORD_METHOD(void, SBThread, StepInto, (lldb::RunMode), + stop_other_threads); + + StepInto(nullptr, stop_other_threads); } void SBThread::StepInto(const char *target_name, lldb::RunMode stop_other_threads) { + LLDB_RECORD_METHOD(void, SBThread, StepInto, (const char *, lldb::RunMode), + 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) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBThread, StepInto, + (const char *, uint32_t, lldb::SBError &, lldb::RunMode), + target_name, end_line, error, stop_other_threads); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf( - "SBThread(%p)::StepInto (target_name='%s', stop_other_threads='%s')", - static_cast<void *>(exe_ctx.GetThreadPtr()), - target_name ? target_name : "<NULL>", - Thread::RunModeAsCString(stop_other_threads)); - if (!exe_ctx.HasThreadScope()) { error.SetErrorString("this SBThread object is invalid"); return; @@ -740,20 +691,18 @@ } void SBThread::StepOut() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBThread, StepOut); + SBError error; // Ignored StepOut(error); } void SBThread::StepOut(SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBThread, StepOut, (lldb::SBError &), error); std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBThread(%p)::StepOut ()", - static_cast<void *>(exe_ctx.GetThreadPtr())); - if (!exe_ctx.HasThreadScope()) { error.SetErrorString("this SBThread object is invalid"); return; @@ -767,7 +716,7 @@ const LazyBool avoid_no_debug = eLazyBoolCalculate; Status new_plan_status; ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepOut( - abort_other_plans, NULL, false, stop_other_threads, eVoteYes, + abort_other_plans, nullptr, false, stop_other_threads, eVoteYes, eVoteNoOpinion, 0, new_plan_status, avoid_no_debug)); if (new_plan_status.Success()) @@ -777,33 +726,27 @@ } void SBThread::StepOutOfFrame(SBFrame &sb_frame) { + LLDB_RECORD_METHOD(void, SBThread, StepOutOfFrame, (lldb::SBFrame &), + sb_frame); + SBError error; // Ignored StepOutOfFrame(sb_frame, error); } void SBThread::StepOutOfFrame(SBFrame &sb_frame, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBThread, StepOutOfFrame, + (lldb::SBFrame &, lldb::SBError &), sb_frame, error); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); if (!sb_frame.IsValid()) { - if (log) - log->Printf( - "SBThread(%p)::StepOutOfFrame passed an invalid frame, returning.", - static_cast<void *>(exe_ctx.GetThreadPtr())); error.SetErrorString("passed invalid SBFrame object"); return; } StackFrameSP frame_sp(sb_frame.GetFrameSP()); - if (log) { - SBStream frame_desc_strm; - sb_frame.GetDescription(frame_desc_strm); - log->Printf("SBThread(%p)::StepOutOfFrame (frame = SBFrame(%p): %s)", - static_cast<void *>(exe_ctx.GetThreadPtr()), - static_cast<void *>(frame_sp.get()), frame_desc_strm.GetData()); - } if (!exe_ctx.HasThreadScope()) { error.SetErrorString("this SBThread object is invalid"); @@ -814,17 +757,13 @@ bool stop_other_threads = false; Thread *thread = exe_ctx.GetThreadPtr(); if (sb_frame.GetThread().GetThreadID() != thread->GetID()) { - log->Printf("SBThread(%p)::StepOutOfFrame passed a frame from another " - "thread (0x%" PRIx64 " vrs. 0x%" PRIx64 ", returning.", - static_cast<void *>(exe_ctx.GetThreadPtr()), - 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, NULL, false, stop_other_threads, eVoteYes, + abort_other_plans, nullptr, false, stop_other_threads, eVoteYes, eVoteNoOpinion, frame_sp->GetFrameIndex(), new_plan_status)); if (new_plan_status.Success()) @@ -834,20 +773,19 @@ } void SBThread::StepInstruction(bool step_over) { + LLDB_RECORD_METHOD(void, SBThread, StepInstruction, (bool), step_over); + SBError error; // Ignored StepInstruction(step_over, error); } void SBThread::StepInstruction(bool step_over, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBThread, StepInstruction, (bool, lldb::SBError &), + step_over, error); std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBThread(%p)::StepInstruction (step_over=%i)", - static_cast<void *>(exe_ctx.GetThreadPtr()), step_over); - if (!exe_ctx.HasThreadScope()) { error.SetErrorString("this SBThread object is invalid"); return; @@ -865,20 +803,19 @@ } void SBThread::RunToAddress(lldb::addr_t addr) { + LLDB_RECORD_METHOD(void, SBThread, RunToAddress, (lldb::addr_t), addr); + SBError error; // Ignored RunToAddress(addr, error); } void SBThread::RunToAddress(lldb::addr_t addr, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(void, SBThread, RunToAddress, + (lldb::addr_t, lldb::SBError &), addr, error); std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBThread(%p)::RunToAddress (addr=0x%" PRIx64 ")", - static_cast<void *>(exe_ctx.GetThreadPtr()), addr); - if (!exe_ctx.HasThreadScope()) { error.SetErrorString("this SBThread object is invalid"); return; @@ -903,8 +840,11 @@ SBError SBThread::StepOverUntil(lldb::SBFrame &sb_frame, lldb::SBFileSpec &sb_file_spec, uint32_t line) { + LLDB_RECORD_METHOD(lldb::SBError, SBThread, StepOverUntil, + (lldb::SBFrame &, lldb::SBFileSpec &, uint32_t), sb_frame, + sb_file_spec, line); + SBError sb_error; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); char path[PATH_MAX]; std::unique_lock<std::recursive_mutex> lock; @@ -912,24 +852,13 @@ StackFrameSP frame_sp(sb_frame.GetFrameSP()); - if (log) { - SBStream frame_desc_strm; - sb_frame.GetDescription(frame_desc_strm); - sb_file_spec->GetPath(path, sizeof(path)); - log->Printf("SBThread(%p)::StepOverUntil (frame = SBFrame(%p): %s, " - "file+line = %s:%u)", - static_cast<void *>(exe_ctx.GetThreadPtr()), - static_cast<void *>(frame_sp.get()), frame_desc_strm.GetData(), - path, line); - } - 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; + return LLDB_RECORD_RESULT(sb_error); } if (!frame_sp) { @@ -941,7 +870,7 @@ SymbolContext frame_sc; if (!frame_sp) { sb_error.SetErrorString("no valid frames in thread to step"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } // If we have a frame, get its line @@ -949,10 +878,10 @@ eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextLineEntry | eSymbolContextSymbol); - if (frame_sc.comp_unit == NULL) { + if (frame_sc.comp_unit == nullptr) { sb_error.SetErrorStringWithFormat( "frame %u doesn't have debug information", frame_sp->GetFrameIndex()); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } FileSpec step_file_spec; @@ -964,7 +893,7 @@ step_file_spec = frame_sc.line_entry.file; else { sb_error.SetErrorString("invalid file argument or no file for frame"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } } @@ -1024,29 +953,31 @@ } else { sb_error.SetErrorString("this SBThread object is invalid"); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBThread::StepUsingScriptedThreadPlan(const char *script_class_name) { - return StepUsingScriptedThreadPlan(script_class_name, true); + LLDB_RECORD_METHOD(lldb::SBError, SBThread, StepUsingScriptedThreadPlan, + (const char *), script_class_name); + + return LLDB_RECORD_RESULT( + StepUsingScriptedThreadPlan(script_class_name, true)); } SBError SBThread::StepUsingScriptedThreadPlan(const char *script_class_name, bool resume_immediately) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBError, SBThread, StepUsingScriptedThreadPlan, + (const char *, bool), script_class_name, + resume_immediately); + SBError error; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) { - log->Printf("SBThread(%p)::StepUsingScriptedThreadPlan: class name: %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), script_class_name); - } - if (!exe_ctx.HasThreadScope()) { error.SetErrorString("this SBThread object is invalid"); - return error; + return LLDB_RECORD_RESULT(error); } Thread *thread = exe_ctx.GetThreadPtr(); @@ -1056,78 +987,68 @@ if (new_plan_status.Fail()) { error.SetErrorString(new_plan_status.AsCString()); - return error; + return LLDB_RECORD_RESULT(error); } if (!resume_immediately) - return error; + return LLDB_RECORD_RESULT(error); if (new_plan_status.Success()) error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); else error.SetErrorString(new_plan_status.AsCString()); - return error; + return LLDB_RECORD_RESULT(error); } SBError SBThread::JumpToLine(lldb::SBFileSpec &file_spec, uint32_t line) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBError, SBThread, JumpToLine, + (lldb::SBFileSpec &, uint32_t), file_spec, line); + SBError sb_error; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBThread(%p)::JumpToLine (file+line = %s:%u)", - static_cast<void *>(exe_ctx.GetThreadPtr()), - file_spec->GetPath().c_str(), line); - if (!exe_ctx.HasThreadScope()) { sb_error.SetErrorString("this SBThread object is invalid"); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } Thread *thread = exe_ctx.GetThreadPtr(); Status err = thread->JumpToLine(file_spec.get(), line, true); sb_error.SetError(err); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBThread::ReturnFromFrame(SBFrame &frame, SBValue &return_value) { - SBError sb_error; + LLDB_RECORD_METHOD(lldb::SBError, SBThread, ReturnFromFrame, + (lldb::SBFrame &, lldb::SBValue &), frame, return_value); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBError sb_error; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBThread(%p)::ReturnFromFrame (frame=%d)", - static_cast<void *>(exe_ctx.GetThreadPtr()), - frame.GetFrameID()); - if (exe_ctx.HasThreadScope()) { Thread *thread = exe_ctx.GetThreadPtr(); sb_error.SetError( thread->ReturnFromFrame(frame.GetFrameSP(), return_value.GetSP())); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } SBError SBThread::UnwindInnermostExpression() { - SBError sb_error; + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBThread, + UnwindInnermostExpression); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBError sb_error; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf("SBThread(%p)::UnwindExpressionEvaluation", - static_cast<void *>(exe_ctx.GetThreadPtr())); - if (exe_ctx.HasThreadScope()) { Thread *thread = exe_ctx.GetThreadPtr(); sb_error.SetError(thread->UnwindInnermostExpression()); @@ -1135,16 +1056,19 @@ thread->SetSelectedFrameByIndex(0, false); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } bool SBThread::Suspend() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThread, Suspend); + SBError error; // Ignored return Suspend(error); } bool SBThread::Suspend(SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBThread, Suspend, (lldb::SBError &), error); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1156,25 +1080,22 @@ result = true; } else { error.SetErrorString("process is running"); - if (log) - log->Printf("SBThread(%p)::Suspend() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } else error.SetErrorString("this SBThread object is invalid"); - if (log) - log->Printf("SBThread(%p)::Suspend() => %i", - static_cast<void *>(exe_ctx.GetThreadPtr()), result); return result; } bool SBThread::Resume() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThread, Resume); + SBError error; // Ignored return Resume(error); } bool SBThread::Resume(SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBThread, Resume, (lldb::SBError &), error); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1187,19 +1108,15 @@ result = true; } else { error.SetErrorString("process is running"); - if (log) - log->Printf("SBThread(%p)::Resume() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } else error.SetErrorString("this SBThread object is invalid"); - if (log) - log->Printf("SBThread(%p)::Resume() => %i", - static_cast<void *>(exe_ctx.GetThreadPtr()), result); return result; } bool SBThread::IsSuspended() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThread, IsSuspended); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1209,6 +1126,8 @@ } bool SBThread::IsStopped() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThread, IsStopped); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1218,6 +1137,8 @@ } SBProcess SBThread::GetProcess() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBProcess, SBThread, GetProcess); + SBProcess sb_process; std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); @@ -1228,21 +1149,11 @@ sb_process.SetSP(exe_ctx.GetProcessSP()); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - SBStream frame_desc_strm; - sb_process.GetDescription(frame_desc_strm); - log->Printf("SBThread(%p)::GetProcess () => SBProcess(%p): %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), - static_cast<void *>(sb_process.GetSP().get()), - frame_desc_strm.GetData()); - } - - return sb_process; + return LLDB_RECORD_RESULT(sb_process); } uint32_t SBThread::GetNumFrames() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBThread, GetNumFrames); uint32_t num_frames = 0; std::unique_lock<std::recursive_mutex> lock; @@ -1252,22 +1163,14 @@ Process::StopLocker stop_locker; if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { num_frames = exe_ctx.GetThreadPtr()->GetStackFrameCount(); - } else { - if (log) - log->Printf("SBThread(%p)::GetNumFrames() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) - log->Printf("SBThread(%p)::GetNumFrames () => %u", - static_cast<void *>(exe_ctx.GetThreadPtr()), num_frames); - return num_frames; } SBFrame SBThread::GetFrameAtIndex(uint32_t idx) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBFrame, SBThread, GetFrameAtIndex, (uint32_t), idx); SBFrame sb_frame; StackFrameSP frame_sp; @@ -1279,27 +1182,14 @@ if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { frame_sp = exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(idx); sb_frame.SetFrameSP(frame_sp); - } else { - if (log) - log->Printf( - "SBThread(%p)::GetFrameAtIndex() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) { - SBStream frame_desc_strm; - sb_frame.GetDescription(frame_desc_strm); - log->Printf("SBThread(%p)::GetFrameAtIndex (idx=%d) => SBFrame(%p): %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), idx, - static_cast<void *>(frame_sp.get()), frame_desc_strm.GetData()); - } - - return sb_frame; + return LLDB_RECORD_RESULT(sb_frame); } lldb::SBFrame SBThread::GetSelectedFrame() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFrame, SBThread, GetSelectedFrame); SBFrame sb_frame; StackFrameSP frame_sp; @@ -1311,27 +1201,15 @@ if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { frame_sp = exe_ctx.GetThreadPtr()->GetSelectedFrame(); sb_frame.SetFrameSP(frame_sp); - } else { - if (log) - log->Printf( - "SBThread(%p)::GetSelectedFrame() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) { - SBStream frame_desc_strm; - sb_frame.GetDescription(frame_desc_strm); - log->Printf("SBThread(%p)::GetSelectedFrame () => SBFrame(%p): %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), - static_cast<void *>(frame_sp.get()), frame_desc_strm.GetData()); - } - - return sb_frame; + return LLDB_RECORD_RESULT(sb_frame); } lldb::SBFrame SBThread::SetSelectedFrame(uint32_t idx) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBFrame, SBThread, SetSelectedFrame, (uint32_t), + idx); SBFrame sb_frame; StackFrameSP frame_sp; @@ -1347,47 +1225,55 @@ thread->SetSelectedFrame(frame_sp.get()); sb_frame.SetFrameSP(frame_sp); } - } else { - if (log) - log->Printf( - "SBThread(%p)::SetSelectedFrame() => error: process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log) { - SBStream frame_desc_strm; - sb_frame.GetDescription(frame_desc_strm); - log->Printf("SBThread(%p)::SetSelectedFrame (idx=%u) => SBFrame(%p): %s", - static_cast<void *>(exe_ctx.GetThreadPtr()), idx, - static_cast<void *>(frame_sp.get()), frame_desc_strm.GetData()); - } - return sb_frame; + return LLDB_RECORD_RESULT(sb_frame); } bool SBThread::EventIsThreadEvent(const SBEvent &event) { - return Thread::ThreadEventData::GetEventDataFromEvent(event.get()) != NULL; + LLDB_RECORD_STATIC_METHOD(bool, SBThread, EventIsThreadEvent, + (const lldb::SBEvent &), event); + + return Thread::ThreadEventData::GetEventDataFromEvent(event.get()) != nullptr; } SBFrame SBThread::GetStackFrameFromEvent(const SBEvent &event) { - return Thread::ThreadEventData::GetStackFrameFromEvent(event.get()); + LLDB_RECORD_STATIC_METHOD(lldb::SBFrame, SBThread, GetStackFrameFromEvent, + (const lldb::SBEvent &), event); + + return LLDB_RECORD_RESULT( + Thread::ThreadEventData::GetStackFrameFromEvent(event.get())); } SBThread SBThread::GetThreadFromEvent(const SBEvent &event) { - return Thread::ThreadEventData::GetThreadFromEvent(event.get()); + LLDB_RECORD_STATIC_METHOD(lldb::SBThread, SBThread, GetThreadFromEvent, + (const lldb::SBEvent &), event); + + return LLDB_RECORD_RESULT( + Thread::ThreadEventData::GetThreadFromEvent(event.get())); } bool SBThread::operator==(const SBThread &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBThread, operator==,(const lldb::SBThread &), + rhs); + return m_opaque_sp->GetThreadSP().get() == rhs.m_opaque_sp->GetThreadSP().get(); } bool SBThread::operator!=(const SBThread &rhs) const { + LLDB_RECORD_METHOD_CONST(bool, SBThread, operator!=,(const lldb::SBThread &), + rhs); + return m_opaque_sp->GetThreadSP().get() != rhs.m_opaque_sp->GetThreadSP().get(); } bool SBThread::GetStatus(SBStream &status) const { + LLDB_RECORD_METHOD_CONST(bool, SBThread, GetStatus, (lldb::SBStream &), + status); + Stream &strm = status.ref(); std::unique_lock<std::recursive_mutex> lock; @@ -1402,10 +1288,16 @@ } bool SBThread::GetDescription(SBStream &description) const { - return GetDescription(description, false); + LLDB_RECORD_METHOD_CONST(bool, SBThread, GetDescription, (lldb::SBStream &), + description); + + return GetDescription(description, false); } bool SBThread::GetDescription(SBStream &description, bool stop_format) const { + LLDB_RECORD_METHOD_CONST(bool, SBThread, GetDescription, + (lldb::SBStream &, bool), description, stop_format); + Stream &strm = description.ref(); std::unique_lock<std::recursive_mutex> lock; @@ -1424,14 +1316,16 @@ } SBThread SBThread::GetExtendedBacktraceThread(const char *type) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBThread, SBThread, GetExtendedBacktraceThread, + (const char *), type); + std::unique_lock<std::recursive_mutex> lock; ExecutionContext exe_ctx(m_opaque_sp.get(), lock); SBThread sb_origin_thread; - if (exe_ctx.HasThreadScope()) { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + 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); @@ -1446,38 +1340,20 @@ // pointer retains the object. process->GetExtendedThreadList().AddThread(new_thread_sp); sb_origin_thread.SetThread(new_thread_sp); - if (log) { - const char *queue_name = new_thread_sp->GetQueueName(); - if (queue_name == NULL) - queue_name = ""; - log->Printf("SBThread(%p)::GetExtendedBacktraceThread() => new " - "extended Thread " - "created (%p) with queue_id 0x%" PRIx64 - " queue name '%s'", - static_cast<void *>(exe_ctx.GetThreadPtr()), - static_cast<void *>(new_thread_sp.get()), - new_thread_sp->GetQueueID(), queue_name); - } } } } } - } else { - if (log) - log->Printf("SBThread(%p)::GetExtendedBacktraceThread() => error: " - "process is running", - static_cast<void *>(exe_ctx.GetThreadPtr())); } } - if (log && !sb_origin_thread.IsValid()) - log->Printf("SBThread(%p)::GetExtendedBacktraceThread() is not returning a " - "Valid thread", - static_cast<void *>(exe_ctx.GetThreadPtr())); - return sb_origin_thread; + return LLDB_RECORD_RESULT(sb_origin_thread); } uint32_t SBThread::GetExtendedBacktraceOriginatingIndexID() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBThread, + GetExtendedBacktraceOriginatingIndexID); + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); if (thread_sp) return thread_sp->GetExtendedBacktraceOriginatingIndexID(); @@ -1485,20 +1361,30 @@ } SBValue SBThread::GetCurrentException() { - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (!thread_sp) return SBValue(); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValue, SBThread, GetCurrentException); - return SBValue(thread_sp->GetCurrentException()); + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (!thread_sp) + return LLDB_RECORD_RESULT(SBValue()); + + return LLDB_RECORD_RESULT(SBValue(thread_sp->GetCurrentException())); } SBThread SBThread::GetCurrentExceptionBacktrace() { - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (!thread_sp) return SBThread(); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBThread, SBThread, + GetCurrentExceptionBacktrace); - return SBThread(thread_sp->GetCurrentExceptionBacktrace()); + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (!thread_sp) + return LLDB_RECORD_RESULT(SBThread()); + + return LLDB_RECORD_RESULT( + SBThread(thread_sp->GetCurrentExceptionBacktrace())); } bool SBThread::SafeToCallFunctions() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThread, SafeToCallFunctions); + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); if (thread_sp) return thread_sp->SafeToCallFunctions(); @@ -1506,17 +1392,115 @@ } lldb_private::Thread *SBThread::operator->() { - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp.get(); - else - return NULL; + return get(); } lldb_private::Thread *SBThread::get() { - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp.get(); - else - return NULL; + return m_opaque_sp->GetThreadSP().get(); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBThread>(Registry &R) { + LLDB_REGISTER_STATIC_METHOD(const char *, SBThread, GetBroadcasterClassName, + ()); + LLDB_REGISTER_CONSTRUCTOR(SBThread, ()); + LLDB_REGISTER_CONSTRUCTOR(SBThread, (const lldb::ThreadSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBThread, (const lldb::SBThread &)); + LLDB_REGISTER_METHOD(const lldb::SBThread &, + SBThread, operator=,(const lldb::SBThread &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBQueue, SBThread, GetQueue, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBThread, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBThread, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBThread, Clear, ()); + LLDB_REGISTER_METHOD(lldb::StopReason, SBThread, GetStopReason, ()); + LLDB_REGISTER_METHOD(size_t, SBThread, GetStopReasonDataCount, ()); + LLDB_REGISTER_METHOD(uint64_t, SBThread, GetStopReasonDataAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBThread, GetStopReasonExtendedInfoAsJSON, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(lldb::SBThreadCollection, SBThread, + GetStopReasonExtendedBacktraces, + (lldb::InstrumentationRuntimeType)); + LLDB_REGISTER_METHOD(size_t, SBThread, GetStopDescription, + (char *, size_t)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBThread, GetStopReturnValue, ()); + LLDB_REGISTER_METHOD_CONST(lldb::tid_t, SBThread, GetThreadID, ()); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBThread, GetIndexID, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBThread, GetName, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBThread, GetQueueName, ()); + LLDB_REGISTER_METHOD_CONST(lldb::queue_id_t, SBThread, GetQueueID, ()); + LLDB_REGISTER_METHOD(bool, SBThread, GetInfoItemByPathAsString, + (const char *, lldb::SBStream &)); + LLDB_REGISTER_METHOD(void, SBThread, StepOver, (lldb::RunMode)); + LLDB_REGISTER_METHOD(void, SBThread, StepOver, + (lldb::RunMode, lldb::SBError &)); + LLDB_REGISTER_METHOD(void, SBThread, StepInto, (lldb::RunMode)); + LLDB_REGISTER_METHOD(void, SBThread, StepInto, + (const char *, lldb::RunMode)); + LLDB_REGISTER_METHOD( + void, SBThread, StepInto, + (const char *, uint32_t, lldb::SBError &, lldb::RunMode)); + LLDB_REGISTER_METHOD(void, SBThread, StepOut, ()); + LLDB_REGISTER_METHOD(void, SBThread, StepOut, (lldb::SBError &)); + LLDB_REGISTER_METHOD(void, SBThread, StepOutOfFrame, (lldb::SBFrame &)); + LLDB_REGISTER_METHOD(void, SBThread, StepOutOfFrame, + (lldb::SBFrame &, lldb::SBError &)); + LLDB_REGISTER_METHOD(void, SBThread, StepInstruction, (bool)); + LLDB_REGISTER_METHOD(void, SBThread, StepInstruction, + (bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(void, SBThread, RunToAddress, (lldb::addr_t)); + LLDB_REGISTER_METHOD(void, SBThread, RunToAddress, + (lldb::addr_t, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBThread, StepOverUntil, + (lldb::SBFrame &, lldb::SBFileSpec &, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBError, SBThread, StepUsingScriptedThreadPlan, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBError, SBThread, StepUsingScriptedThreadPlan, + (const char *, bool)); + LLDB_REGISTER_METHOD(lldb::SBError, SBThread, JumpToLine, + (lldb::SBFileSpec &, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBError, SBThread, ReturnFromFrame, + (lldb::SBFrame &, lldb::SBValue &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBThread, UnwindInnermostExpression, + ()); + LLDB_REGISTER_METHOD(bool, SBThread, Suspend, ()); + LLDB_REGISTER_METHOD(bool, SBThread, Suspend, (lldb::SBError &)); + LLDB_REGISTER_METHOD(bool, SBThread, Resume, ()); + LLDB_REGISTER_METHOD(bool, SBThread, Resume, (lldb::SBError &)); + LLDB_REGISTER_METHOD(bool, SBThread, IsSuspended, ()); + LLDB_REGISTER_METHOD(bool, SBThread, IsStopped, ()); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBThread, GetProcess, ()); + LLDB_REGISTER_METHOD(uint32_t, SBThread, GetNumFrames, ()); + LLDB_REGISTER_METHOD(lldb::SBFrame, SBThread, GetFrameAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBFrame, SBThread, GetSelectedFrame, ()); + LLDB_REGISTER_METHOD(lldb::SBFrame, SBThread, SetSelectedFrame, (uint32_t)); + LLDB_REGISTER_STATIC_METHOD(bool, SBThread, EventIsThreadEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBFrame, SBThread, GetStackFrameFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBThread, SBThread, GetThreadFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBThread, operator==,(const lldb::SBThread &)); + LLDB_REGISTER_METHOD_CONST(bool, + SBThread, operator!=,(const lldb::SBThread &)); + LLDB_REGISTER_METHOD_CONST(bool, SBThread, GetStatus, (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(bool, SBThread, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD_CONST(bool, SBThread, GetDescription, + (lldb::SBStream &, bool)); + LLDB_REGISTER_METHOD(lldb::SBThread, SBThread, GetExtendedBacktraceThread, + (const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBThread, + GetExtendedBacktraceOriginatingIndexID, ()); + LLDB_REGISTER_METHOD(lldb::SBValue, SBThread, GetCurrentException, ()); + LLDB_REGISTER_METHOD(lldb::SBThread, SBThread, GetCurrentExceptionBacktrace, + ()); + LLDB_REGISTER_METHOD(bool, SBThread, SafeToCallFunctions, ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBThreadCollection.cpp b/src/llvm-project/lldb/source/API/SBThreadCollection.cpp index c424d47..3c1cf98 100644 --- a/src/llvm-project/lldb/source/API/SBThreadCollection.cpp +++ b/src/llvm-project/lldb/source/API/SBThreadCollection.cpp
@@ -1,29 +1,38 @@ //===-- SBThreadCollection.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBThread.h" #include "lldb/Target/ThreadList.h" using namespace lldb; using namespace lldb_private; -SBThreadCollection::SBThreadCollection() : m_opaque_sp() {} +SBThreadCollection::SBThreadCollection() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBThreadCollection); +} SBThreadCollection::SBThreadCollection(const SBThreadCollection &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBThreadCollection, + (const lldb::SBThreadCollection &), rhs); +} const SBThreadCollection &SBThreadCollection:: operator=(const SBThreadCollection &rhs) { + LLDB_RECORD_METHOD( + const lldb::SBThreadCollection &, + SBThreadCollection, operator=,(const lldb::SBThreadCollection &), rhs); + if (this != &rhs) m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBThreadCollection::SBThreadCollection(const ThreadCollectionSP &threads) @@ -51,17 +60,51 @@ return m_opaque_sp; } -bool SBThreadCollection::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBThreadCollection::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBThreadCollection, IsValid); + return this->operator bool(); +} +SBThreadCollection::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBThreadCollection, operator bool); + + return m_opaque_sp.get() != nullptr; +} size_t SBThreadCollection::GetSize() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBThreadCollection, GetSize); + if (m_opaque_sp) return m_opaque_sp->GetSize(); return 0; } SBThread SBThreadCollection::GetThreadAtIndex(size_t idx) { + LLDB_RECORD_METHOD(lldb::SBThread, SBThreadCollection, GetThreadAtIndex, + (size_t), idx); + SBThread thread; if (m_opaque_sp && idx < m_opaque_sp->GetSize()) thread = m_opaque_sp->GetThreadAtIndex(idx); - return thread; + return LLDB_RECORD_RESULT(thread); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBThreadCollection>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBThreadCollection, ()); + LLDB_REGISTER_CONSTRUCTOR(SBThreadCollection, + (const lldb::SBThreadCollection &)); + LLDB_REGISTER_METHOD( + const lldb::SBThreadCollection &, + SBThreadCollection, operator=,(const lldb::SBThreadCollection &)); + LLDB_REGISTER_METHOD_CONST(bool, SBThreadCollection, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBThreadCollection, operator bool, ()); + LLDB_REGISTER_METHOD(size_t, SBThreadCollection, GetSize, ()); + LLDB_REGISTER_METHOD(lldb::SBThread, SBThreadCollection, GetThreadAtIndex, + (size_t)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBThreadPlan.cpp b/src/llvm-project/lldb/source/API/SBThreadPlan.cpp index fc54f5b..8f6802f 100644 --- a/src/llvm-project/lldb/source/API/SBThreadPlan.cpp +++ b/src/llvm-project/lldb/source/API/SBThreadPlan.cpp
@@ -1,12 +1,12 @@ //===-- SBThreadPlan.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBThread.h" #include "lldb/API/SBFileSpec.h" @@ -42,60 +42,98 @@ #include "lldb/API/SBThreadPlan.h" #include "lldb/API/SBValue.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Constructors -//---------------------------------------------------------------------- -SBThreadPlan::SBThreadPlan() {} +SBThreadPlan::SBThreadPlan() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBThreadPlan); } SBThreadPlan::SBThreadPlan(const ThreadPlanSP &lldb_object_sp) - : m_opaque_sp(lldb_object_sp) {} + : m_opaque_sp(lldb_object_sp) { + LLDB_RECORD_CONSTRUCTOR(SBThreadPlan, (const lldb::ThreadPlanSP &), + lldb_object_sp); +} SBThreadPlan::SBThreadPlan(const SBThreadPlan &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBThreadPlan, (const lldb::SBThreadPlan &), rhs); +} SBThreadPlan::SBThreadPlan(lldb::SBThread &sb_thread, const char *class_name) { + LLDB_RECORD_CONSTRUCTOR(SBThreadPlan, (lldb::SBThread &, const char *), + sb_thread, class_name); + Thread *thread = sb_thread.get(); if (thread) - m_opaque_sp.reset(new ThreadPlanPython(*thread, class_name)); + m_opaque_sp = std::make_shared<ThreadPlanPython>(*thread, class_name); } -//---------------------------------------------------------------------- // Assignment operator -//---------------------------------------------------------------------- const lldb::SBThreadPlan &SBThreadPlan::operator=(const SBThreadPlan &rhs) { + LLDB_RECORD_METHOD(const lldb::SBThreadPlan &, + SBThreadPlan, operator=,(const lldb::SBThreadPlan &), rhs); + if (this != &rhs) m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SBThreadPlan::~SBThreadPlan() {} lldb_private::ThreadPlan *SBThreadPlan::get() { return m_opaque_sp.get(); } -bool SBThreadPlan::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBThreadPlan::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBThreadPlan, IsValid); + return this->operator bool(); +} +SBThreadPlan::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBThreadPlan, operator bool); -void SBThreadPlan::Clear() { m_opaque_sp.reset(); } + return m_opaque_sp.get() != nullptr; +} -lldb::StopReason SBThreadPlan::GetStopReason() { return eStopReasonNone; } +void SBThreadPlan::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBThreadPlan, Clear); -size_t SBThreadPlan::GetStopReasonDataCount() { return 0; } + m_opaque_sp.reset(); +} -uint64_t SBThreadPlan::GetStopReasonDataAtIndex(uint32_t idx) { return 0; } +lldb::StopReason SBThreadPlan::GetStopReason() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::StopReason, SBThreadPlan, GetStopReason); + + return eStopReasonNone; +} + +size_t SBThreadPlan::GetStopReasonDataCount() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBThreadPlan, GetStopReasonDataCount); + + return 0; +} + +uint64_t SBThreadPlan::GetStopReasonDataAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(uint64_t, SBThreadPlan, GetStopReasonDataAtIndex, + (uint32_t), idx); + + return 0; +} SBThread SBThreadPlan::GetThread() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBThread, SBThreadPlan, GetThread); + if (m_opaque_sp) { - return SBThread(m_opaque_sp->GetThread().shared_from_this()); + return LLDB_RECORD_RESULT( + SBThread(m_opaque_sp->GetThread().shared_from_this())); } else - return SBThread(); + return LLDB_RECORD_RESULT(SBThread()); } bool SBThreadPlan::GetDescription(lldb::SBStream &description) const { + LLDB_RECORD_METHOD_CONST(bool, SBThreadPlan, GetDescription, + (lldb::SBStream &), description); + if (m_opaque_sp) { m_opaque_sp->GetDescription(description.get(), eDescriptionLevelFull); } else { @@ -109,11 +147,15 @@ } void SBThreadPlan::SetPlanComplete(bool success) { + LLDB_RECORD_METHOD(void, SBThreadPlan, SetPlanComplete, (bool), success); + if (m_opaque_sp) m_opaque_sp->SetPlanComplete(success); } bool SBThreadPlan::IsPlanComplete() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThreadPlan, IsPlanComplete); + if (m_opaque_sp) return m_opaque_sp->IsPlanComplete(); else @@ -121,6 +163,8 @@ } bool SBThreadPlan::IsPlanStale() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThreadPlan, IsPlanStale); + if (m_opaque_sp) return m_opaque_sp->IsPlanStale(); else @@ -128,6 +172,8 @@ } bool SBThreadPlan::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBThreadPlan, IsValid); + if (m_opaque_sp) return m_opaque_sp->ValidatePlan(nullptr); else @@ -143,16 +189,26 @@ SBThreadPlan SBThreadPlan::QueueThreadPlanForStepOverRange(SBAddress &sb_start_address, lldb::addr_t size) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOverRange, + (lldb::SBAddress &, lldb::addr_t), sb_start_address, size); + SBError error; - return QueueThreadPlanForStepOverRange(sb_start_address, size, error); + return LLDB_RECORD_RESULT( + QueueThreadPlanForStepOverRange(sb_start_address, size, error)); } SBThreadPlan SBThreadPlan::QueueThreadPlanForStepOverRange( SBAddress &sb_start_address, lldb::addr_t size, SBError &error) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOverRange, + (lldb::SBAddress &, lldb::addr_t, lldb::SBError &), + sb_start_address, size, error); + if (m_opaque_sp) { Address *start_address = sb_start_address.get(); if (!start_address) { - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); } AddressRange range(*start_address, size); @@ -167,26 +223,36 @@ if (plan_status.Fail()) error.SetErrorString(plan_status.AsCString()); - return plan; + return LLDB_RECORD_RESULT(plan); } else { - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); } } SBThreadPlan SBThreadPlan::QueueThreadPlanForStepInRange(SBAddress &sb_start_address, lldb::addr_t size) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepInRange, + (lldb::SBAddress &, lldb::addr_t), sb_start_address, size); + SBError error; - return QueueThreadPlanForStepInRange(sb_start_address, size, error); + return LLDB_RECORD_RESULT( + QueueThreadPlanForStepInRange(sb_start_address, size, error)); } SBThreadPlan SBThreadPlan::QueueThreadPlanForStepInRange(SBAddress &sb_start_address, lldb::addr_t size, SBError &error) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepInRange, + (lldb::SBAddress &, lldb::addr_t, lldb::SBError &), + sb_start_address, size, error); + if (m_opaque_sp) { Address *start_address = sb_start_address.get(); if (!start_address) { - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); } AddressRange range(*start_address, size); @@ -196,27 +262,37 @@ Status plan_status; SBThreadPlan plan = SBThreadPlan(m_opaque_sp->GetThread().QueueThreadPlanForStepInRange( - false, range, sc, NULL, eAllThreads, plan_status)); + false, range, sc, nullptr, eAllThreads, plan_status)); if (plan_status.Fail()) error.SetErrorString(plan_status.AsCString()); - return plan; + return LLDB_RECORD_RESULT(plan); } else { - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); } } SBThreadPlan SBThreadPlan::QueueThreadPlanForStepOut(uint32_t frame_idx_to_step_to, bool first_insn) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOut, (uint32_t, bool), + frame_idx_to_step_to, first_insn); + SBError error; - return QueueThreadPlanForStepOut(frame_idx_to_step_to, first_insn, error); + return LLDB_RECORD_RESULT( + 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_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOut, + (uint32_t, bool, lldb::SBError &), frame_idx_to_step_to, + first_insn, error); + if (m_opaque_sp) { SymbolContext sc; sc = m_opaque_sp->GetThread().GetStackFrameAtIndex(0)->GetSymbolContext( @@ -231,24 +307,32 @@ if (plan_status.Fail()) error.SetErrorString(plan_status.AsCString()); - return plan; + return LLDB_RECORD_RESULT(plan); } else { - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); } } SBThreadPlan SBThreadPlan::QueueThreadPlanForRunToAddress(SBAddress sb_address) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForRunToAddress, (lldb::SBAddress), + sb_address); + SBError error; - return QueueThreadPlanForRunToAddress(sb_address, error); + return LLDB_RECORD_RESULT(QueueThreadPlanForRunToAddress(sb_address, error)); } SBThreadPlan SBThreadPlan::QueueThreadPlanForRunToAddress(SBAddress sb_address, SBError &error) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForRunToAddress, + (lldb::SBAddress, lldb::SBError &), sb_address, error); + if (m_opaque_sp) { Address *address = sb_address.get(); if (!address) - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); Status plan_status; SBThreadPlan plan = @@ -258,21 +342,30 @@ if (plan_status.Fail()) error.SetErrorString(plan_status.AsCString()); - return plan; + return LLDB_RECORD_RESULT(plan); } else { - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); } } SBThreadPlan SBThreadPlan::QueueThreadPlanForStepScripted(const char *script_class_name) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepScripted, (const char *), + script_class_name); + SBError error; - return QueueThreadPlanForStepScripted(script_class_name, error); + return LLDB_RECORD_RESULT( + QueueThreadPlanForStepScripted(script_class_name, error)); } SBThreadPlan SBThreadPlan::QueueThreadPlanForStepScripted(const char *script_class_name, SBError &error) { + LLDB_RECORD_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepScripted, + (const char *, lldb::SBError &), script_class_name, error); + if (m_opaque_sp) { Status plan_status; SBThreadPlan plan = @@ -282,8 +375,65 @@ if (plan_status.Fail()) error.SetErrorString(plan_status.AsCString()); - return plan; + return LLDB_RECORD_RESULT(plan); } else { - return SBThreadPlan(); + return LLDB_RECORD_RESULT(SBThreadPlan()); } } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBThreadPlan>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBThreadPlan, ()); + LLDB_REGISTER_CONSTRUCTOR(SBThreadPlan, (const lldb::ThreadPlanSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBThreadPlan, (const lldb::SBThreadPlan &)); + LLDB_REGISTER_CONSTRUCTOR(SBThreadPlan, (lldb::SBThread &, const char *)); + LLDB_REGISTER_METHOD(const lldb::SBThreadPlan &, + SBThreadPlan, operator=,(const lldb::SBThreadPlan &)); + LLDB_REGISTER_METHOD_CONST(bool, SBThreadPlan, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBThreadPlan, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBThreadPlan, Clear, ()); + LLDB_REGISTER_METHOD(lldb::StopReason, SBThreadPlan, GetStopReason, ()); + LLDB_REGISTER_METHOD(size_t, SBThreadPlan, GetStopReasonDataCount, ()); + LLDB_REGISTER_METHOD(uint64_t, SBThreadPlan, GetStopReasonDataAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD_CONST(lldb::SBThread, SBThreadPlan, GetThread, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBThreadPlan, GetDescription, + (lldb::SBStream &)); + LLDB_REGISTER_METHOD(void, SBThreadPlan, SetPlanComplete, (bool)); + LLDB_REGISTER_METHOD(bool, SBThreadPlan, IsPlanComplete, ()); + LLDB_REGISTER_METHOD(bool, SBThreadPlan, IsPlanStale, ()); + LLDB_REGISTER_METHOD(bool, SBThreadPlan, IsValid, ()); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOverRange, + (lldb::SBAddress &, lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOverRange, + (lldb::SBAddress &, lldb::addr_t, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepInRange, + (lldb::SBAddress &, lldb::addr_t)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepInRange, + (lldb::SBAddress &, lldb::addr_t, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOut, (uint32_t, bool)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepOut, + (uint32_t, bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForRunToAddress, (lldb::SBAddress)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForRunToAddress, + (lldb::SBAddress, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepScripted, (const char *)); + LLDB_REGISTER_METHOD(lldb::SBThreadPlan, SBThreadPlan, + QueueThreadPlanForStepScripted, + (const char *, lldb::SBError &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTrace.cpp b/src/llvm-project/lldb/source/API/SBTrace.cpp index 9a5fa4e..9b871e6 100644 --- a/src/llvm-project/lldb/source/API/SBTrace.cpp +++ b/src/llvm-project/lldb/source/API/SBTrace.cpp
@@ -1,18 +1,19 @@ //===-- SBTrace.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/Target/Process.h" -#include "lldb/Utility/Log.h" #include "lldb/API/SBTrace.h" #include "lldb/API/SBTraceOptions.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -25,8 +26,11 @@ size_t SBTrace::GetTraceData(SBError &error, void *buf, size_t size, size_t offset, lldb::tid_t thread_id) { + LLDB_RECORD_DUMMY(size_t, SBTrace, GetTraceData, + (lldb::SBError &, void *, size_t, size_t, lldb::tid_t), + error, buf, size, offset, thread_id); + ProcessSP process_sp(GetSP()); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); llvm::MutableArrayRef<uint8_t> buffer(static_cast<uint8_t *>(buf), size); error.Clear(); @@ -35,30 +39,33 @@ } else { error.SetError( process_sp->GetData(GetTraceUID(), thread_id, buffer, offset)); - LLDB_LOG(log, "SBTrace::bytes_read - {0}", buffer.size()); } return buffer.size(); } size_t SBTrace::GetMetaData(SBError &error, void *buf, size_t size, size_t offset, lldb::tid_t thread_id) { + LLDB_RECORD_DUMMY(size_t, SBTrace, GetMetaData, + (lldb::SBError &, void *, size_t, size_t, lldb::tid_t), + error, buf, size, offset, thread_id); + ProcessSP process_sp(GetSP()); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); llvm::MutableArrayRef<uint8_t> buffer(static_cast<uint8_t *>(buf), size); error.Clear(); if (!process_sp) { error.SetErrorString("invalid process"); } else { - error.SetError( process_sp->GetMetaData(GetTraceUID(), thread_id, buffer, offset)); - LLDB_LOG(log, "SBTrace::bytes_read - {0}", buffer.size()); } return buffer.size(); } void SBTrace::StopTrace(SBError &error, lldb::tid_t thread_id) { + LLDB_RECORD_METHOD(void, SBTrace, StopTrace, (lldb::SBError &, lldb::tid_t), + error, thread_id); + ProcessSP process_sp(GetSP()); error.Clear(); @@ -70,6 +77,9 @@ } void SBTrace::GetTraceConfig(SBTraceOptions &options, SBError &error) { + LLDB_RECORD_METHOD(void, SBTrace, GetTraceConfig, + (lldb::SBTraceOptions &, lldb::SBError &), options, error); + ProcessSP process_sp(GetSP()); error.Clear(); @@ -82,6 +92,8 @@ } lldb::user_id_t SBTrace::GetTraceUID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::user_id_t, SBTrace, GetTraceUID); + if (m_trace_impl_sp) return m_trace_impl_sp->uid; return LLDB_INVALID_UID; @@ -93,7 +105,9 @@ } SBTrace::SBTrace() { - m_trace_impl_sp.reset(new TraceImpl); + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTrace); + + m_trace_impl_sp = std::make_shared<TraceImpl>(); if (m_trace_impl_sp) m_trace_impl_sp->uid = LLDB_INVALID_UID; } @@ -101,9 +115,33 @@ void SBTrace::SetSP(const ProcessSP &process_sp) { m_opaque_wp = process_sp; } bool SBTrace::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTrace, IsValid); + return this->operator bool(); +} +SBTrace::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTrace, operator bool); + if (!m_trace_impl_sp) return false; if (!GetSP()) return false; return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTrace>(Registry &R) { + LLDB_REGISTER_METHOD(void, SBTrace, StopTrace, + (lldb::SBError &, lldb::tid_t)); + LLDB_REGISTER_METHOD(void, SBTrace, GetTraceConfig, + (lldb::SBTraceOptions &, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::user_id_t, SBTrace, GetTraceUID, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTrace, ()); + LLDB_REGISTER_METHOD(bool, SBTrace, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTrace, operator bool, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTraceOptions.cpp b/src/llvm-project/lldb/source/API/SBTraceOptions.cpp index 20a8f25..a24cdd5 100644 --- a/src/llvm-project/lldb/source/API/SBTraceOptions.cpp +++ b/src/llvm-project/lldb/source/API/SBTraceOptions.cpp
@@ -1,39 +1,51 @@ //===-- SBTraceOptions.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/SBTraceOptions.h" +#include "SBReproducerPrivate.h" #include "lldb/API/SBError.h" #include "lldb/API/SBStructuredData.h" #include "lldb/Core/StructuredDataImpl.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/TraceOptions.h" +#include <memory> + using namespace lldb; using namespace lldb_private; SBTraceOptions::SBTraceOptions() { - m_traceoptions_sp.reset(new TraceOptions()); + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTraceOptions); + + m_traceoptions_sp = std::make_shared<TraceOptions>(); } lldb::TraceType SBTraceOptions::getType() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::TraceType, SBTraceOptions, getType); + if (m_traceoptions_sp) return m_traceoptions_sp->getType(); return lldb::TraceType::eTraceTypeNone; } uint64_t SBTraceOptions::getTraceBufferSize() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint64_t, SBTraceOptions, + getTraceBufferSize); + if (m_traceoptions_sp) return m_traceoptions_sp->getTraceBufferSize(); return 0; } lldb::SBStructuredData SBTraceOptions::getTraceParams(lldb::SBError &error) { + LLDB_RECORD_METHOD(lldb::SBStructuredData, SBTraceOptions, getTraceParams, + (lldb::SBError &), error); + error.Clear(); const lldb_private::StructuredData::DictionarySP dict_obj = m_traceoptions_sp->getTraceParams(); @@ -42,16 +54,22 @@ structData.m_impl_up->SetObjectSP(dict_obj->shared_from_this()); else error.SetErrorString("Empty trace params"); - return structData; + return LLDB_RECORD_RESULT(structData); } uint64_t SBTraceOptions::getMetaDataBufferSize() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint64_t, SBTraceOptions, + getMetaDataBufferSize); + if (m_traceoptions_sp) return m_traceoptions_sp->getTraceBufferSize(); return 0; } void SBTraceOptions::setTraceParams(lldb::SBStructuredData ¶ms) { + LLDB_RECORD_METHOD(void, SBTraceOptions, setTraceParams, + (lldb::SBStructuredData &), params); + if (m_traceoptions_sp && params.m_impl_up) { StructuredData::ObjectSP obj_sp = params.m_impl_up->GetObjectSP(); if (obj_sp && obj_sp->GetAsDictionary() != nullptr) @@ -62,33 +80,80 @@ } void SBTraceOptions::setType(lldb::TraceType type) { + LLDB_RECORD_METHOD(void, SBTraceOptions, setType, (lldb::TraceType), type); + if (m_traceoptions_sp) m_traceoptions_sp->setType(type); } void SBTraceOptions::setTraceBufferSize(uint64_t size) { + LLDB_RECORD_METHOD(void, SBTraceOptions, setTraceBufferSize, (uint64_t), + size); + if (m_traceoptions_sp) m_traceoptions_sp->setTraceBufferSize(size); } void SBTraceOptions::setMetaDataBufferSize(uint64_t size) { + LLDB_RECORD_METHOD(void, SBTraceOptions, setMetaDataBufferSize, (uint64_t), + size); + if (m_traceoptions_sp) m_traceoptions_sp->setMetaDataBufferSize(size); } bool SBTraceOptions::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTraceOptions, IsValid); + return this->operator bool(); +} +SBTraceOptions::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTraceOptions, operator bool); + if (m_traceoptions_sp) return true; return false; } void SBTraceOptions::setThreadID(lldb::tid_t thread_id) { + LLDB_RECORD_METHOD(void, SBTraceOptions, setThreadID, (lldb::tid_t), + thread_id); + if (m_traceoptions_sp) m_traceoptions_sp->setThreadID(thread_id); } lldb::tid_t SBTraceOptions::getThreadID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::tid_t, SBTraceOptions, getThreadID); + if (m_traceoptions_sp) return m_traceoptions_sp->getThreadID(); return LLDB_INVALID_THREAD_ID; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTraceOptions>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTraceOptions, ()); + LLDB_REGISTER_METHOD_CONST(lldb::TraceType, SBTraceOptions, getType, ()); + LLDB_REGISTER_METHOD_CONST(uint64_t, SBTraceOptions, getTraceBufferSize, + ()); + LLDB_REGISTER_METHOD(lldb::SBStructuredData, SBTraceOptions, getTraceParams, + (lldb::SBError &)); + LLDB_REGISTER_METHOD_CONST(uint64_t, SBTraceOptions, getMetaDataBufferSize, + ()); + LLDB_REGISTER_METHOD(void, SBTraceOptions, setTraceParams, + (lldb::SBStructuredData &)); + LLDB_REGISTER_METHOD(void, SBTraceOptions, setType, (lldb::TraceType)); + LLDB_REGISTER_METHOD(void, SBTraceOptions, setTraceBufferSize, (uint64_t)); + LLDB_REGISTER_METHOD(void, SBTraceOptions, setMetaDataBufferSize, + (uint64_t)); + LLDB_REGISTER_METHOD(bool, SBTraceOptions, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTraceOptions, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBTraceOptions, setThreadID, (lldb::tid_t)); + LLDB_REGISTER_METHOD(lldb::tid_t, SBTraceOptions, getThreadID, ()); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBType.cpp b/src/llvm-project/lldb/source/API/SBType.cpp index 77d7dc6..5402128 100644 --- a/src/llvm-project/lldb/source/API/SBType.cpp +++ b/src/llvm-project/lldb/source/API/SBType.cpp
@@ -1,13 +1,13 @@ //===-- SBType.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBDefines.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBTypeEnumMember.h" @@ -16,15 +16,16 @@ #include "lldb/Symbol/Type.h" #include "lldb/Symbol/TypeSystem.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" #include "llvm/ADT/APSInt.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -SBType::SBType() : m_opaque_sp() {} +SBType::SBType() : m_opaque_sp() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBType); } SBType::SBType(const CompilerType &type) : m_opaque_sp(new TypeImpl( @@ -37,16 +38,20 @@ : m_opaque_sp(type_impl_sp) {} SBType::SBType(const SBType &rhs) : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR(SBType, (const lldb::SBType &), rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } } // SBType::SBType (TypeImpl* impl) : -// m_opaque_ap(impl) +// m_opaque_up(impl) //{} // bool SBType::operator==(SBType &rhs) { + LLDB_RECORD_METHOD(bool, SBType, operator==,(lldb::SBType &), rhs); + if (!IsValid()) return !rhs.IsValid(); @@ -57,6 +62,8 @@ } bool SBType::operator!=(SBType &rhs) { + LLDB_RECORD_METHOD(bool, SBType, operator!=,(lldb::SBType &), rhs); + if (!IsValid()) return rhs.IsValid(); @@ -73,17 +80,20 @@ } SBType &SBType::operator=(const SBType &rhs) { + LLDB_RECORD_METHOD(lldb::SBType &, SBType, operator=,(const lldb::SBType &), + rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } SBType::~SBType() {} TypeImpl &SBType::ref() { - if (m_opaque_sp.get() == NULL) - m_opaque_sp.reset(new TypeImpl()); + if (m_opaque_sp.get() == nullptr) + m_opaque_sp = std::make_shared<TypeImpl>(); return *m_opaque_sp; } @@ -96,13 +106,21 @@ } bool SBType::IsValid() const { - if (m_opaque_sp.get() == NULL) + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBType, IsValid); + return this->operator bool(); +} +SBType::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBType, operator bool); + + if (m_opaque_sp.get() == nullptr) return false; return m_opaque_sp->IsValid(); } uint64_t SBType::GetByteSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint64_t, SBType, GetByteSize); + if (IsValid()) if (llvm::Optional<uint64_t> size = m_opaque_sp->GetCompilerType(false).GetByteSize(nullptr)) @@ -111,12 +129,16 @@ } bool SBType::IsPointerType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsPointerType); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsPointerType(); } bool SBType::IsArrayType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsArrayType); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsArrayType(nullptr, nullptr, @@ -124,63 +146,88 @@ } bool SBType::IsVectorType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsVectorType); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsVectorType(nullptr, nullptr); } bool SBType::IsReferenceType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsReferenceType); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsReferenceType(); } SBType SBType::GetPointerType() { - if (!IsValid()) - return SBType(); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetPointerType); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointerType()))); + if (!IsValid()) + return LLDB_RECORD_RESULT(SBType()); + + return LLDB_RECORD_RESULT( + SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointerType())))); } SBType SBType::GetPointeeType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetPointeeType); + if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointeeType()))); + return LLDB_RECORD_RESULT(SBType()); + return LLDB_RECORD_RESULT( + SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointeeType())))); } SBType SBType::GetReferenceType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetReferenceType); + if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetReferenceType()))); + return LLDB_RECORD_RESULT(SBType()); + return LLDB_RECORD_RESULT( + SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetReferenceType())))); } SBType SBType::GetTypedefedType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetTypedefedType); + if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetTypedefedType()))); + return LLDB_RECORD_RESULT(SBType()); + return LLDB_RECORD_RESULT( + SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetTypedefedType())))); } SBType SBType::GetDereferencedType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetDereferencedType); + if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetDereferencedType()))); + return LLDB_RECORD_RESULT(SBType()); + return LLDB_RECORD_RESULT( + SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetDereferencedType())))); } SBType SBType::GetArrayElementType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetArrayElementType); + if (!IsValid()) - return SBType(); - return SBType(TypeImplSP( - new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayElementType()))); + return LLDB_RECORD_RESULT(SBType()); + return LLDB_RECORD_RESULT(SBType(TypeImplSP( + new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayElementType())))); } SBType SBType::GetArrayType(uint64_t size) { + LLDB_RECORD_METHOD(lldb::SBType, SBType, GetArrayType, (uint64_t), size); + if (!IsValid()) - return SBType(); - return SBType(TypeImplSP( - new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayType(size)))); + return LLDB_RECORD_RESULT(SBType()); + return LLDB_RECORD_RESULT(SBType(TypeImplSP( + new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayType(size))))); } SBType SBType::GetVectorElementType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetVectorElementType); + SBType type_sb; if (IsValid()) { CompilerType vector_element_type; @@ -188,44 +235,57 @@ nullptr)) type_sb.SetSP(TypeImplSP(new TypeImpl(vector_element_type))); } - return type_sb; + return LLDB_RECORD_RESULT(type_sb); } bool SBType::IsFunctionType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsFunctionType); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsFunctionType(); } bool SBType::IsPolymorphicClass() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsPolymorphicClass); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsPolymorphicClass(); } bool SBType::IsTypedefType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsTypedefType); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsTypedefType(); } bool SBType::IsAnonymousType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsAnonymousType); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(true).IsAnonymousType(); } lldb::SBType SBType::GetFunctionReturnType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetFunctionReturnType); + if (IsValid()) { CompilerType return_type( m_opaque_sp->GetCompilerType(true).GetFunctionReturnType()); if (return_type.IsValid()) - return SBType(return_type); + return LLDB_RECORD_RESULT(SBType(return_type)); } - return lldb::SBType(); + return LLDB_RECORD_RESULT(lldb::SBType()); } lldb::SBTypeList SBType::GetFunctionArgumentTypes() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeList, SBType, + GetFunctionArgumentTypes); + SBTypeList sb_type_list; if (IsValid()) { CompilerType func_type(m_opaque_sp->GetCompilerType(true)); @@ -234,10 +294,12 @@ sb_type_list.Append(SBType(func_type.GetFunctionArgumentAtIndex(i))); } } - return sb_type_list; + return LLDB_RECORD_RESULT(sb_type_list); } uint32_t SBType::GetNumberOfMemberFunctions() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBType, GetNumberOfMemberFunctions); + if (IsValid()) { return m_opaque_sp->GetCompilerType(true).GetNumMemberFunctions(); } @@ -245,51 +307,71 @@ } lldb::SBTypeMemberFunction SBType::GetMemberFunctionAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBTypeMemberFunction, SBType, + GetMemberFunctionAtIndex, (uint32_t), idx); + SBTypeMemberFunction sb_func_type; if (IsValid()) sb_func_type.reset(new TypeMemberFunctionImpl( m_opaque_sp->GetCompilerType(true).GetMemberFunctionAtIndex(idx))); - return sb_func_type; + return LLDB_RECORD_RESULT(sb_func_type); } lldb::SBType SBType::GetUnqualifiedType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetUnqualifiedType); + if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetUnqualifiedType()))); + return LLDB_RECORD_RESULT(SBType()); + return LLDB_RECORD_RESULT( + SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetUnqualifiedType())))); } lldb::SBType SBType::GetCanonicalType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBType, GetCanonicalType); + if (IsValid()) - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetCanonicalType()))); - return SBType(); + return LLDB_RECORD_RESULT( + SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetCanonicalType())))); + return LLDB_RECORD_RESULT(SBType()); } lldb::BasicType SBType::GetBasicType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::BasicType, SBType, GetBasicType); + if (IsValid()) return m_opaque_sp->GetCompilerType(false).GetBasicTypeEnumeration(); return eBasicTypeInvalid; } SBType SBType::GetBasicType(lldb::BasicType basic_type) { + LLDB_RECORD_METHOD(lldb::SBType, SBType, GetBasicType, (lldb::BasicType), + basic_type); + if (IsValid() && m_opaque_sp->IsValid()) - return SBType( - m_opaque_sp->GetTypeSystem(false)->GetBasicTypeFromAST(basic_type)); - return SBType(); + return LLDB_RECORD_RESULT(SBType( + m_opaque_sp->GetTypeSystem(false)->GetBasicTypeFromAST(basic_type))); + return LLDB_RECORD_RESULT(SBType()); } uint32_t SBType::GetNumberOfDirectBaseClasses() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBType, GetNumberOfDirectBaseClasses); + if (IsValid()) return m_opaque_sp->GetCompilerType(true).GetNumDirectBaseClasses(); return 0; } uint32_t SBType::GetNumberOfVirtualBaseClasses() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBType, GetNumberOfVirtualBaseClasses); + if (IsValid()) return m_opaque_sp->GetCompilerType(true).GetNumVirtualBaseClasses(); return 0; } uint32_t SBType::GetNumberOfFields() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBType, GetNumberOfFields); + if (IsValid()) return m_opaque_sp->GetCompilerType(true).GetNumFields(); return 0; @@ -297,6 +379,10 @@ bool SBType::GetDescription(SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBType, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + Stream &strm = description.ref(); if (m_opaque_sp) { @@ -308,6 +394,9 @@ } SBTypeMember SBType::GetDirectBaseClassAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBTypeMember, SBType, GetDirectBaseClassAtIndex, + (uint32_t), idx); + SBTypeMember sb_type_member; if (IsValid()) { uint32_t bit_offset = 0; @@ -318,10 +407,13 @@ sb_type_member.reset(new TypeMemberImpl( TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); } - return sb_type_member; + return LLDB_RECORD_RESULT(sb_type_member); } SBTypeMember SBType::GetVirtualBaseClassAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBTypeMember, SBType, GetVirtualBaseClassAtIndex, + (uint32_t), idx); + SBTypeMember sb_type_member; if (IsValid()) { uint32_t bit_offset = 0; @@ -332,17 +424,20 @@ sb_type_member.reset(new TypeMemberImpl( TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); } - return sb_type_member; + return LLDB_RECORD_RESULT(sb_type_member); } SBTypeEnumMemberList SBType::GetEnumMembers() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeEnumMemberList, SBType, + GetEnumMembers); + 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, - const ConstString &name, + ConstString name, const llvm::APSInt &value) -> bool { SBTypeEnumMember enum_member( lldb::TypeEnumMemberImplSP(new TypeEnumMemberImpl( @@ -352,10 +447,13 @@ }); } } - return sb_enum_member_list; + return LLDB_RECORD_RESULT(sb_enum_member_list); } SBTypeMember SBType::GetFieldAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBTypeMember, SBType, GetFieldAtIndex, (uint32_t), + idx); + SBTypeMember sb_type_member; if (IsValid()) { CompilerType this_type(m_opaque_sp->GetCompilerType(false)); @@ -376,48 +474,63 @@ } } } - return sb_type_member; + return LLDB_RECORD_RESULT(sb_type_member); } bool SBType::IsTypeComplete() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBType, IsTypeComplete); + if (!IsValid()) return false; return m_opaque_sp->GetCompilerType(false).IsCompleteType(); } uint32_t SBType::GetTypeFlags() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBType, GetTypeFlags); + if (!IsValid()) return 0; return m_opaque_sp->GetCompilerType(true).GetTypeInfo(); } const char *SBType::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBType, GetName); + if (!IsValid()) return ""; return m_opaque_sp->GetName().GetCString(); } const char *SBType::GetDisplayTypeName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBType, GetDisplayTypeName); + if (!IsValid()) return ""; return m_opaque_sp->GetDisplayTypeName().GetCString(); } lldb::TypeClass SBType::GetTypeClass() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::TypeClass, SBType, GetTypeClass); + if (IsValid()) return m_opaque_sp->GetCompilerType(true).GetTypeClass(); return lldb::eTypeClassInvalid; } uint32_t SBType::GetNumberOfTemplateArguments() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBType, GetNumberOfTemplateArguments); + if (IsValid()) return m_opaque_sp->GetCompilerType(false).GetNumTemplateArguments(); return 0; } lldb::SBType SBType::GetTemplateArgumentType(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBType, SBType, GetTemplateArgumentType, (uint32_t), + idx); + if (!IsValid()) - return SBType(); + return LLDB_RECORD_RESULT(SBType()); CompilerType type; switch(GetTemplateArgumentKind(idx)) { @@ -433,132 +546,190 @@ break; } if (type.IsValid()) - return SBType(type); - return SBType(); + return LLDB_RECORD_RESULT(SBType(type)); + return LLDB_RECORD_RESULT(SBType()); } lldb::TemplateArgumentKind SBType::GetTemplateArgumentKind(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::TemplateArgumentKind, SBType, + GetTemplateArgumentKind, (uint32_t), idx); + if (IsValid()) return m_opaque_sp->GetCompilerType(false).GetTemplateArgumentKind(idx); return eTemplateArgumentKindNull; } -SBTypeList::SBTypeList() : m_opaque_ap(new TypeListImpl()) {} +SBTypeList::SBTypeList() : m_opaque_up(new TypeListImpl()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeList); +} SBTypeList::SBTypeList(const SBTypeList &rhs) - : m_opaque_ap(new TypeListImpl()) { + : m_opaque_up(new TypeListImpl()) { + LLDB_RECORD_CONSTRUCTOR(SBTypeList, (const lldb::SBTypeList &), 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() { return (m_opaque_ap != NULL); } +bool SBTypeList::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeList, IsValid); + return this->operator bool(); +} +SBTypeList::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeList, operator bool); + + return (m_opaque_up != nullptr); +} SBTypeList &SBTypeList::operator=(const SBTypeList &rhs) { + LLDB_RECORD_METHOD(lldb::SBTypeList &, + SBTypeList, operator=,(const lldb::SBTypeList &), rhs); + if (this != &rhs) { - m_opaque_ap.reset(new TypeListImpl()); + m_opaque_up.reset(new 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; + return LLDB_RECORD_RESULT(*this); } void SBTypeList::Append(SBType type) { + LLDB_RECORD_METHOD(void, SBTypeList, Append, (lldb::SBType), type); + if (type.IsValid()) - m_opaque_ap->Append(type.m_opaque_sp); + m_opaque_up->Append(type.m_opaque_sp); } SBType SBTypeList::GetTypeAtIndex(uint32_t index) { - if (m_opaque_ap) - return SBType(m_opaque_ap->GetTypeAtIndex(index)); - return SBType(); + LLDB_RECORD_METHOD(lldb::SBType, SBTypeList, GetTypeAtIndex, (uint32_t), + index); + + if (m_opaque_up) + return LLDB_RECORD_RESULT(SBType(m_opaque_up->GetTypeAtIndex(index))); + return LLDB_RECORD_RESULT(SBType()); } -uint32_t SBTypeList::GetSize() { return m_opaque_ap->GetSize(); } +uint32_t SBTypeList::GetSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeList, GetSize); + + return m_opaque_up->GetSize(); +} SBTypeList::~SBTypeList() {} -SBTypeMember::SBTypeMember() : m_opaque_ap() {} +SBTypeMember::SBTypeMember() : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeMember); +} SBTypeMember::~SBTypeMember() {} -SBTypeMember::SBTypeMember(const SBTypeMember &rhs) : m_opaque_ap() { +SBTypeMember::SBTypeMember(const SBTypeMember &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBTypeMember, (const lldb::SBTypeMember &), rhs); + if (this != &rhs) { if (rhs.IsValid()) - m_opaque_ap.reset(new TypeMemberImpl(rhs.ref())); + m_opaque_up.reset(new TypeMemberImpl(rhs.ref())); } } lldb::SBTypeMember &SBTypeMember::operator=(const lldb::SBTypeMember &rhs) { + LLDB_RECORD_METHOD(lldb::SBTypeMember &, + SBTypeMember, operator=,(const lldb::SBTypeMember &), rhs); + if (this != &rhs) { if (rhs.IsValid()) - m_opaque_ap.reset(new TypeMemberImpl(rhs.ref())); + m_opaque_up.reset(new TypeMemberImpl(rhs.ref())); } - return *this; + return LLDB_RECORD_RESULT(*this); } -bool SBTypeMember::IsValid() const { return m_opaque_ap.get(); } +bool SBTypeMember::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeMember, IsValid); + return this->operator bool(); +} +SBTypeMember::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeMember, operator bool); + + return m_opaque_up.get(); +} const char *SBTypeMember::GetName() { - if (m_opaque_ap) - return m_opaque_ap->GetName().GetCString(); - return NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeMember, GetName); + + if (m_opaque_up) + return m_opaque_up->GetName().GetCString(); + return nullptr; } SBType SBTypeMember::GetType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBTypeMember, GetType); + SBType sb_type; - if (m_opaque_ap) { - sb_type.SetSP(m_opaque_ap->GetTypeImpl()); + if (m_opaque_up) { + sb_type.SetSP(m_opaque_up->GetTypeImpl()); } - return sb_type; + return LLDB_RECORD_RESULT(sb_type); } uint64_t SBTypeMember::GetOffsetInBytes() { - if (m_opaque_ap) - return m_opaque_ap->GetBitOffset() / 8u; + LLDB_RECORD_METHOD_NO_ARGS(uint64_t, SBTypeMember, GetOffsetInBytes); + + if (m_opaque_up) + return m_opaque_up->GetBitOffset() / 8u; return 0; } uint64_t SBTypeMember::GetOffsetInBits() { - if (m_opaque_ap) - return m_opaque_ap->GetBitOffset(); + LLDB_RECORD_METHOD_NO_ARGS(uint64_t, SBTypeMember, GetOffsetInBits); + + if (m_opaque_up) + return m_opaque_up->GetBitOffset(); return 0; } bool SBTypeMember::IsBitfield() { - if (m_opaque_ap) - return m_opaque_ap->GetIsBitfield(); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeMember, IsBitfield); + + if (m_opaque_up) + return m_opaque_up->GetIsBitfield(); return false; } uint32_t SBTypeMember::GetBitfieldSizeInBits() { - if (m_opaque_ap) - return m_opaque_ap->GetBitfieldBitSize(); + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeMember, GetBitfieldSizeInBits); + + if (m_opaque_up) + return m_opaque_up->GetBitfieldBitSize(); return 0; } bool SBTypeMember::GetDescription(lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeMember, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + Stream &strm = description.ref(); - if (m_opaque_ap) { - const uint32_t bit_offset = m_opaque_ap->GetBitOffset(); + 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_ap->GetName().GetCString(); + 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_ap->GetTypeImpl()); + 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_ap->GetIsBitfield()) { - const uint32_t bitfield_bit_size = m_opaque_ap->GetBitfieldBitSize(); + if (m_opaque_up->GetIsBitfield()) { + const uint32_t bitfield_bit_size = m_opaque_up->GetBitfieldBitSize(); strm.Printf(" : %u", bitfield_bit_size); } } else { @@ -568,40 +739,63 @@ } void SBTypeMember::reset(TypeMemberImpl *type_member_impl) { - m_opaque_ap.reset(type_member_impl); + m_opaque_up.reset(type_member_impl); } TypeMemberImpl &SBTypeMember::ref() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new TypeMemberImpl()); - return *m_opaque_ap; + if (m_opaque_up == nullptr) + m_opaque_up.reset(new TypeMemberImpl()); + return *m_opaque_up; } -const TypeMemberImpl &SBTypeMember::ref() const { return *m_opaque_ap; } +const TypeMemberImpl &SBTypeMember::ref() const { return *m_opaque_up; } -SBTypeMemberFunction::SBTypeMemberFunction() : m_opaque_sp() {} +SBTypeMemberFunction::SBTypeMemberFunction() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeMemberFunction); +} SBTypeMemberFunction::~SBTypeMemberFunction() {} SBTypeMemberFunction::SBTypeMemberFunction(const SBTypeMemberFunction &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTypeMemberFunction, + (const lldb::SBTypeMemberFunction &), rhs); +} lldb::SBTypeMemberFunction &SBTypeMemberFunction:: operator=(const lldb::SBTypeMemberFunction &rhs) { + LLDB_RECORD_METHOD( + lldb::SBTypeMemberFunction &, + SBTypeMemberFunction, operator=,(const lldb::SBTypeMemberFunction &), + rhs); + if (this != &rhs) m_opaque_sp = rhs.m_opaque_sp; - return *this; + return LLDB_RECORD_RESULT(*this); } -bool SBTypeMemberFunction::IsValid() const { return m_opaque_sp.get(); } +bool SBTypeMemberFunction::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeMemberFunction, IsValid); + return this->operator bool(); +} +SBTypeMemberFunction::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeMemberFunction, operator bool); + + return m_opaque_sp.get(); +} const char *SBTypeMemberFunction::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeMemberFunction, GetName); + if (m_opaque_sp) return m_opaque_sp->GetName().GetCString(); - return NULL; + return nullptr; } const char *SBTypeMemberFunction::GetDemangledName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeMemberFunction, + GetDemangledName); + if (m_opaque_sp) { ConstString mangled_str = m_opaque_sp->GetMangledName(); if (mangled_str) { @@ -609,47 +803,63 @@ return mangled.GetDemangledName(mangled.GuessLanguage()).GetCString(); } } - return NULL; + return nullptr; } const char *SBTypeMemberFunction::GetMangledName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeMemberFunction, + GetMangledName); + if (m_opaque_sp) return m_opaque_sp->GetMangledName().GetCString(); - return NULL; + return nullptr; } SBType SBTypeMemberFunction::GetType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBTypeMemberFunction, GetType); + SBType sb_type; if (m_opaque_sp) { sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetType()))); } - return sb_type; + return LLDB_RECORD_RESULT(sb_type); } lldb::SBType SBTypeMemberFunction::GetReturnType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBTypeMemberFunction, GetReturnType); + SBType sb_type; if (m_opaque_sp) { sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetReturnType()))); } - return sb_type; + return LLDB_RECORD_RESULT(sb_type); } uint32_t SBTypeMemberFunction::GetNumberOfArguments() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeMemberFunction, + GetNumberOfArguments); + if (m_opaque_sp) return m_opaque_sp->GetNumArguments(); return 0; } lldb::SBType SBTypeMemberFunction::GetArgumentTypeAtIndex(uint32_t i) { + LLDB_RECORD_METHOD(lldb::SBType, SBTypeMemberFunction, GetArgumentTypeAtIndex, + (uint32_t), i); + SBType sb_type; if (m_opaque_sp) { sb_type.SetSP( lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetArgumentAtIndex(i)))); } - return sb_type; + return LLDB_RECORD_RESULT(sb_type); } lldb::MemberFunctionKind SBTypeMemberFunction::GetKind() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::MemberFunctionKind, SBTypeMemberFunction, + GetKind); + if (m_opaque_sp) return m_opaque_sp->GetKind(); return lldb::eMemberFunctionKindUnknown; @@ -657,6 +867,10 @@ bool SBTypeMemberFunction::GetDescription( lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeMemberFunction, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + Stream &strm = description.ref(); if (m_opaque_sp) @@ -671,10 +885,124 @@ TypeMemberFunctionImpl &SBTypeMemberFunction::ref() { if (!m_opaque_sp) - m_opaque_sp.reset(new TypeMemberFunctionImpl()); + m_opaque_sp = std::make_shared<TypeMemberFunctionImpl>(); return *m_opaque_sp.get(); } const TypeMemberFunctionImpl &SBTypeMemberFunction::ref() const { return *m_opaque_sp.get(); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBType>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBType, ()); + LLDB_REGISTER_CONSTRUCTOR(SBType, (const lldb::SBType &)); + LLDB_REGISTER_METHOD(bool, SBType, operator==,(lldb::SBType &)); + LLDB_REGISTER_METHOD(bool, SBType, operator!=,(lldb::SBType &)); + LLDB_REGISTER_METHOD(lldb::SBType &, + SBType, operator=,(const lldb::SBType &)); + LLDB_REGISTER_METHOD_CONST(bool, SBType, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBType, operator bool, ()); + LLDB_REGISTER_METHOD(uint64_t, SBType, GetByteSize, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsPointerType, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsArrayType, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsVectorType, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsReferenceType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetPointerType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetPointeeType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetReferenceType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetTypedefedType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetDereferencedType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetArrayElementType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetArrayType, (uint64_t)); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetVectorElementType, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsFunctionType, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsPolymorphicClass, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsTypedefType, ()); + LLDB_REGISTER_METHOD(bool, SBType, IsAnonymousType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetFunctionReturnType, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeList, SBType, GetFunctionArgumentTypes, + ()); + LLDB_REGISTER_METHOD(uint32_t, SBType, GetNumberOfMemberFunctions, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeMemberFunction, SBType, + GetMemberFunctionAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetUnqualifiedType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetCanonicalType, ()); + LLDB_REGISTER_METHOD(lldb::BasicType, SBType, GetBasicType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetBasicType, (lldb::BasicType)); + LLDB_REGISTER_METHOD(uint32_t, SBType, GetNumberOfDirectBaseClasses, ()); + LLDB_REGISTER_METHOD(uint32_t, SBType, GetNumberOfVirtualBaseClasses, ()); + LLDB_REGISTER_METHOD(uint32_t, SBType, GetNumberOfFields, ()); + LLDB_REGISTER_METHOD(bool, SBType, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD(lldb::SBTypeMember, SBType, GetDirectBaseClassAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeMember, SBType, GetVirtualBaseClassAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeEnumMemberList, SBType, GetEnumMembers, + ()); + LLDB_REGISTER_METHOD(lldb::SBTypeMember, SBType, GetFieldAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBType, IsTypeComplete, ()); + LLDB_REGISTER_METHOD(uint32_t, SBType, GetTypeFlags, ()); + LLDB_REGISTER_METHOD(const char *, SBType, GetName, ()); + LLDB_REGISTER_METHOD(const char *, SBType, GetDisplayTypeName, ()); + LLDB_REGISTER_METHOD(lldb::TypeClass, SBType, GetTypeClass, ()); + LLDB_REGISTER_METHOD(uint32_t, SBType, GetNumberOfTemplateArguments, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBType, GetTemplateArgumentType, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::TemplateArgumentKind, SBType, + GetTemplateArgumentKind, (uint32_t)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeList, (const lldb::SBTypeList &)); + LLDB_REGISTER_METHOD(bool, SBTypeList, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeList, operator bool, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeList &, + SBTypeList, operator=,(const lldb::SBTypeList &)); + LLDB_REGISTER_METHOD(void, SBTypeList, Append, (lldb::SBType)); + LLDB_REGISTER_METHOD(lldb::SBType, SBTypeList, GetTypeAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBTypeList, GetSize, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeMember, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeMember, (const lldb::SBTypeMember &)); + LLDB_REGISTER_METHOD(lldb::SBTypeMember &, + SBTypeMember, operator=,(const lldb::SBTypeMember &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeMember, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeMember, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeMember, GetName, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBTypeMember, GetType, ()); + LLDB_REGISTER_METHOD(uint64_t, SBTypeMember, GetOffsetInBytes, ()); + LLDB_REGISTER_METHOD(uint64_t, SBTypeMember, GetOffsetInBits, ()); + LLDB_REGISTER_METHOD(bool, SBTypeMember, IsBitfield, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeMember, GetBitfieldSizeInBits, ()); + LLDB_REGISTER_METHOD(bool, SBTypeMember, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeMemberFunction, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeMemberFunction, + (const lldb::SBTypeMemberFunction &)); + LLDB_REGISTER_METHOD( + lldb::SBTypeMemberFunction &, + SBTypeMemberFunction, operator=,(const lldb::SBTypeMemberFunction &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeMemberFunction, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeMemberFunction, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeMemberFunction, GetName, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeMemberFunction, GetDemangledName, + ()); + LLDB_REGISTER_METHOD(const char *, SBTypeMemberFunction, GetMangledName, + ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBTypeMemberFunction, GetType, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBTypeMemberFunction, GetReturnType, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeMemberFunction, GetNumberOfArguments, + ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBTypeMemberFunction, + GetArgumentTypeAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::MemberFunctionKind, SBTypeMemberFunction, + GetKind, ()); + LLDB_REGISTER_METHOD(bool, SBTypeMemberFunction, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTypeCategory.cpp b/src/llvm-project/lldb/source/API/SBTypeCategory.cpp index 7c2a37e..43d5a3a 100644 --- a/src/llvm-project/lldb/source/API/SBTypeCategory.cpp +++ b/src/llvm-project/lldb/source/API/SBTypeCategory.cpp
@@ -1,14 +1,14 @@ //===-- SBTypeCategory.cpp ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBTypeFilter.h" @@ -27,26 +27,42 @@ typedef std::pair<lldb::TypeCategoryImplSP, user_id_t> ImplType; -SBTypeCategory::SBTypeCategory() : m_opaque_sp() {} +SBTypeCategory::SBTypeCategory() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeCategory); +} SBTypeCategory::SBTypeCategory(const char *name) : m_opaque_sp() { DataVisualization::Categories::GetCategory(ConstString(name), m_opaque_sp); } SBTypeCategory::SBTypeCategory(const lldb::SBTypeCategory &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTypeCategory, (const lldb::SBTypeCategory &), rhs); +} SBTypeCategory::~SBTypeCategory() {} -bool SBTypeCategory::IsValid() const { return (m_opaque_sp.get() != NULL); } +bool SBTypeCategory::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeCategory, IsValid); + return this->operator bool(); +} +SBTypeCategory::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeCategory, operator bool); + + return (m_opaque_sp.get() != nullptr); +} bool SBTypeCategory::GetEnabled() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeCategory, GetEnabled); + if (!IsValid()) return false; return m_opaque_sp->IsEnabled(); } void SBTypeCategory::SetEnabled(bool enabled) { + LLDB_RECORD_METHOD(void, SBTypeCategory, SetEnabled, (bool), enabled); + if (!IsValid()) return; if (enabled) @@ -56,29 +72,41 @@ } const char *SBTypeCategory::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeCategory, GetName); + if (!IsValid()) - return NULL; + return nullptr; return m_opaque_sp->GetName(); } lldb::LanguageType SBTypeCategory::GetLanguageAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::LanguageType, SBTypeCategory, GetLanguageAtIndex, + (uint32_t), idx); + if (IsValid()) return m_opaque_sp->GetLanguageAtIndex(idx); return lldb::eLanguageTypeUnknown; } uint32_t SBTypeCategory::GetNumLanguages() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeCategory, GetNumLanguages); + if (IsValid()) return m_opaque_sp->GetNumLanguages(); return 0; } void SBTypeCategory::AddLanguage(lldb::LanguageType language) { + LLDB_RECORD_METHOD(void, SBTypeCategory, AddLanguage, (lldb::LanguageType), + language); + if (IsValid()) m_opaque_sp->AddLanguage(language); } uint32_t SBTypeCategory::GetNumFormats() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeCategory, GetNumFormats); + if (!IsValid()) return 0; @@ -87,6 +115,8 @@ } uint32_t SBTypeCategory::GetNumSummaries() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeCategory, GetNumSummaries); + if (!IsValid()) return 0; return m_opaque_sp->GetTypeSummariesContainer()->GetCount() + @@ -94,61 +124,77 @@ } uint32_t SBTypeCategory::GetNumFilters() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeCategory, GetNumFilters); + if (!IsValid()) return 0; return m_opaque_sp->GetTypeFiltersContainer()->GetCount() + m_opaque_sp->GetRegexTypeFiltersContainer()->GetCount(); } -#ifndef LLDB_DISABLE_PYTHON uint32_t SBTypeCategory::GetNumSynthetics() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeCategory, GetNumSynthetics); + if (!IsValid()) return 0; return m_opaque_sp->GetTypeSyntheticsContainer()->GetCount() + m_opaque_sp->GetRegexTypeSyntheticsContainer()->GetCount(); } -#endif lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForFilterAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForFilterAtIndex, (uint32_t), index); + if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier( - m_opaque_sp->GetTypeNameSpecifierForFilterAtIndex(index)); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier()); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForFilterAtIndex(index))); } lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForFormatAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForFormatAtIndex, (uint32_t), index); + if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier( - m_opaque_sp->GetTypeNameSpecifierForFormatAtIndex(index)); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier()); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForFormatAtIndex(index))); } lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForSummaryAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForSummaryAtIndex, (uint32_t), index); + if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier( - m_opaque_sp->GetTypeNameSpecifierForSummaryAtIndex(index)); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier()); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForSummaryAtIndex(index))); } -#ifndef LLDB_DISABLE_PYTHON lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForSyntheticAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForSyntheticAtIndex, (uint32_t), + index); + if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier( - m_opaque_sp->GetTypeNameSpecifierForSyntheticAtIndex(index)); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier()); + return LLDB_RECORD_RESULT(SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForSyntheticAtIndex(index))); } -#endif SBTypeFilter SBTypeCategory::GetFilterForType(SBTypeNameSpecifier spec) { + LLDB_RECORD_METHOD(lldb::SBTypeFilter, SBTypeCategory, GetFilterForType, + (lldb::SBTypeNameSpecifier), spec); + if (!IsValid()) - return SBTypeFilter(); + return LLDB_RECORD_RESULT(SBTypeFilter()); if (!spec.IsValid()) - return SBTypeFilter(); + return LLDB_RECORD_RESULT(SBTypeFilter()); lldb::TypeFilterImplSP children_sp; @@ -160,19 +206,22 @@ ConstString(spec.GetName()), children_sp); if (!children_sp) - return lldb::SBTypeFilter(); + return LLDB_RECORD_RESULT(lldb::SBTypeFilter()); TypeFilterImplSP filter_sp = std::static_pointer_cast<TypeFilterImpl>(children_sp); - return lldb::SBTypeFilter(filter_sp); + return LLDB_RECORD_RESULT(lldb::SBTypeFilter(filter_sp)); } SBTypeFormat SBTypeCategory::GetFormatForType(SBTypeNameSpecifier spec) { + LLDB_RECORD_METHOD(lldb::SBTypeFormat, SBTypeCategory, GetFormatForType, + (lldb::SBTypeNameSpecifier), spec); + if (!IsValid()) - return SBTypeFormat(); + return LLDB_RECORD_RESULT(SBTypeFormat()); if (!spec.IsValid()) - return SBTypeFormat(); + return LLDB_RECORD_RESULT(SBTypeFormat()); lldb::TypeFormatImplSP format_sp; @@ -184,18 +233,20 @@ ConstString(spec.GetName()), format_sp); if (!format_sp) - return lldb::SBTypeFormat(); + return LLDB_RECORD_RESULT(lldb::SBTypeFormat()); - return lldb::SBTypeFormat(format_sp); + return LLDB_RECORD_RESULT(lldb::SBTypeFormat(format_sp)); } -#ifndef LLDB_DISABLE_PYTHON SBTypeSummary SBTypeCategory::GetSummaryForType(SBTypeNameSpecifier spec) { + LLDB_RECORD_METHOD(lldb::SBTypeSummary, SBTypeCategory, GetSummaryForType, + (lldb::SBTypeNameSpecifier), spec); + if (!IsValid()) - return SBTypeSummary(); + return LLDB_RECORD_RESULT(SBTypeSummary()); if (!spec.IsValid()) - return SBTypeSummary(); + return LLDB_RECORD_RESULT(SBTypeSummary()); lldb::TypeSummaryImplSP summary_sp; @@ -207,19 +258,20 @@ ConstString(spec.GetName()), summary_sp); if (!summary_sp) - return lldb::SBTypeSummary(); + return LLDB_RECORD_RESULT(lldb::SBTypeSummary()); - return lldb::SBTypeSummary(summary_sp); + return LLDB_RECORD_RESULT(lldb::SBTypeSummary(summary_sp)); } -#endif // LLDB_DISABLE_PYTHON -#ifndef LLDB_DISABLE_PYTHON SBTypeSynthetic SBTypeCategory::GetSyntheticForType(SBTypeNameSpecifier spec) { + LLDB_RECORD_METHOD(lldb::SBTypeSynthetic, SBTypeCategory, GetSyntheticForType, + (lldb::SBTypeNameSpecifier), spec); + if (!IsValid()) - return SBTypeSynthetic(); + return LLDB_RECORD_RESULT(SBTypeSynthetic()); if (!spec.IsValid()) - return SBTypeSynthetic(); + return LLDB_RECORD_RESULT(SBTypeSynthetic()); lldb::SyntheticChildrenSP children_sp; @@ -231,65 +283,76 @@ ConstString(spec.GetName()), children_sp); if (!children_sp) - return lldb::SBTypeSynthetic(); + return LLDB_RECORD_RESULT(lldb::SBTypeSynthetic()); ScriptedSyntheticChildrenSP synth_sp = std::static_pointer_cast<ScriptedSyntheticChildren>(children_sp); - return lldb::SBTypeSynthetic(synth_sp); + return LLDB_RECORD_RESULT(lldb::SBTypeSynthetic(synth_sp)); } -#endif -#ifndef LLDB_DISABLE_PYTHON SBTypeFilter SBTypeCategory::GetFilterAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBTypeFilter, SBTypeCategory, GetFilterAtIndex, + (uint32_t), index); + if (!IsValid()) - return SBTypeFilter(); + return LLDB_RECORD_RESULT(SBTypeFilter()); lldb::SyntheticChildrenSP children_sp = m_opaque_sp->GetSyntheticAtIndex((index)); if (!children_sp.get()) - return lldb::SBTypeFilter(); + return LLDB_RECORD_RESULT(lldb::SBTypeFilter()); TypeFilterImplSP filter_sp = std::static_pointer_cast<TypeFilterImpl>(children_sp); - return lldb::SBTypeFilter(filter_sp); + return LLDB_RECORD_RESULT(lldb::SBTypeFilter(filter_sp)); } -#endif SBTypeFormat SBTypeCategory::GetFormatAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBTypeFormat, SBTypeCategory, GetFormatAtIndex, + (uint32_t), index); + if (!IsValid()) - return SBTypeFormat(); - return SBTypeFormat(m_opaque_sp->GetFormatAtIndex((index))); + return LLDB_RECORD_RESULT(SBTypeFormat()); + return LLDB_RECORD_RESULT( + SBTypeFormat(m_opaque_sp->GetFormatAtIndex((index)))); } -#ifndef LLDB_DISABLE_PYTHON SBTypeSummary SBTypeCategory::GetSummaryAtIndex(uint32_t index) { - if (!IsValid()) - return SBTypeSummary(); - return SBTypeSummary(m_opaque_sp->GetSummaryAtIndex((index))); -} -#endif + LLDB_RECORD_METHOD(lldb::SBTypeSummary, SBTypeCategory, GetSummaryAtIndex, + (uint32_t), index); -#ifndef LLDB_DISABLE_PYTHON -SBTypeSynthetic SBTypeCategory::GetSyntheticAtIndex(uint32_t index) { if (!IsValid()) - return SBTypeSynthetic(); + return LLDB_RECORD_RESULT(SBTypeSummary()); + return LLDB_RECORD_RESULT( + SBTypeSummary(m_opaque_sp->GetSummaryAtIndex((index)))); +} + +SBTypeSynthetic SBTypeCategory::GetSyntheticAtIndex(uint32_t index) { + LLDB_RECORD_METHOD(lldb::SBTypeSynthetic, SBTypeCategory, GetSyntheticAtIndex, + (uint32_t), index); + + if (!IsValid()) + return LLDB_RECORD_RESULT(SBTypeSynthetic()); lldb::SyntheticChildrenSP children_sp = m_opaque_sp->GetSyntheticAtIndex((index)); if (!children_sp.get()) - return lldb::SBTypeSynthetic(); + return LLDB_RECORD_RESULT(lldb::SBTypeSynthetic()); ScriptedSyntheticChildrenSP synth_sp = std::static_pointer_cast<ScriptedSyntheticChildren>(children_sp); - return lldb::SBTypeSynthetic(synth_sp); + return LLDB_RECORD_RESULT(lldb::SBTypeSynthetic(synth_sp)); } -#endif bool SBTypeCategory::AddTypeFormat(SBTypeNameSpecifier type_name, SBTypeFormat format) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, AddTypeFormat, + (lldb::SBTypeNameSpecifier, lldb::SBTypeFormat), type_name, + format); + if (!IsValid()) return false; @@ -312,6 +375,9 @@ } bool SBTypeCategory::DeleteTypeFormat(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, DeleteTypeFormat, + (lldb::SBTypeNameSpecifier), type_name); + if (!IsValid()) return false; @@ -326,9 +392,12 @@ ConstString(type_name.GetName())); } -#ifndef LLDB_DISABLE_PYTHON bool SBTypeCategory::AddTypeSummary(SBTypeNameSpecifier type_name, SBTypeSummary summary) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, AddTypeSummary, + (lldb::SBTypeNameSpecifier, lldb::SBTypeSummary), + type_name, summary); + if (!IsValid()) return false; @@ -356,7 +425,7 @@ DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); if (debugger_sp) { ScriptInterpreter *interpreter_ptr = - debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); + debugger_sp->GetScriptInterpreter(); if (interpreter_ptr) { std::string output; if (interpreter_ptr->GenerateTypeScriptFunction(input, output, @@ -383,9 +452,11 @@ return true; } -#endif bool SBTypeCategory::DeleteTypeSummary(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, DeleteTypeSummary, + (lldb::SBTypeNameSpecifier), type_name); + if (!IsValid()) return false; @@ -402,6 +473,10 @@ bool SBTypeCategory::AddTypeFilter(SBTypeNameSpecifier type_name, SBTypeFilter filter) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, AddTypeFilter, + (lldb::SBTypeNameSpecifier, lldb::SBTypeFilter), type_name, + filter); + if (!IsValid()) return false; @@ -424,6 +499,9 @@ } bool SBTypeCategory::DeleteTypeFilter(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, DeleteTypeFilter, + (lldb::SBTypeNameSpecifier), type_name); + if (!IsValid()) return false; @@ -438,9 +516,12 @@ ConstString(type_name.GetName())); } -#ifndef LLDB_DISABLE_PYTHON bool SBTypeCategory::AddTypeSynthetic(SBTypeNameSpecifier type_name, SBTypeSynthetic synth) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, AddTypeSynthetic, + (lldb::SBTypeNameSpecifier, lldb::SBTypeSynthetic), + type_name, synth); + if (!IsValid()) return false; @@ -468,7 +549,7 @@ DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); if (debugger_sp) { ScriptInterpreter *interpreter_ptr = - debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); + debugger_sp->GetScriptInterpreter(); if (interpreter_ptr) { std::string output; if (interpreter_ptr->GenerateTypeSynthClass(input, output, @@ -497,6 +578,9 @@ } bool SBTypeCategory::DeleteTypeSynthetic(SBTypeNameSpecifier type_name) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, DeleteTypeSynthetic, + (lldb::SBTypeNameSpecifier), type_name); + if (!IsValid()) return false; @@ -510,10 +594,13 @@ return m_opaque_sp->GetTypeSyntheticsContainer()->Delete( ConstString(type_name.GetName())); } -#endif // LLDB_DISABLE_PYTHON bool SBTypeCategory::GetDescription(lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + if (!IsValid()) return false; description.Printf("Category name: %s\n", GetName()); @@ -522,13 +609,20 @@ lldb::SBTypeCategory &SBTypeCategory:: operator=(const lldb::SBTypeCategory &rhs) { + LLDB_RECORD_METHOD(lldb::SBTypeCategory &, + SBTypeCategory, operator=,(const lldb::SBTypeCategory &), + rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBTypeCategory::operator==(lldb::SBTypeCategory &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, operator==,(lldb::SBTypeCategory &), + rhs); + if (!IsValid()) return !rhs.IsValid(); @@ -536,6 +630,9 @@ } bool SBTypeCategory::operator!=(lldb::SBTypeCategory &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeCategory, operator!=,(lldb::SBTypeCategory &), + rhs); + if (!IsValid()) return rhs.IsValid(); @@ -563,3 +660,78 @@ return (strcmp(m_opaque_sp->GetName(), "default") == 0); } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTypeCategory>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeCategory, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeCategory, (const lldb::SBTypeCategory &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeCategory, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeCategory, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, GetEnabled, ()); + LLDB_REGISTER_METHOD(void, SBTypeCategory, SetEnabled, (bool)); + LLDB_REGISTER_METHOD(const char *, SBTypeCategory, GetName, ()); + LLDB_REGISTER_METHOD(lldb::LanguageType, SBTypeCategory, GetLanguageAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBTypeCategory, GetNumLanguages, ()); + LLDB_REGISTER_METHOD(void, SBTypeCategory, AddLanguage, + (lldb::LanguageType)); + LLDB_REGISTER_METHOD(uint32_t, SBTypeCategory, GetNumFormats, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeCategory, GetNumSummaries, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeCategory, GetNumFilters, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeCategory, GetNumSynthetics, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForSyntheticAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeSummary, SBTypeCategory, GetSummaryForType, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeSynthetic, SBTypeCategory, + GetSyntheticForType, (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeFilter, SBTypeCategory, GetFilterAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeSummary, SBTypeCategory, GetSummaryAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeSynthetic, SBTypeCategory, + GetSyntheticAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, AddTypeSummary, + (lldb::SBTypeNameSpecifier, lldb::SBTypeSummary)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, AddTypeSynthetic, + (lldb::SBTypeNameSpecifier, lldb::SBTypeSynthetic)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, DeleteTypeSynthetic, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForFilterAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForFormatAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeNameSpecifier, SBTypeCategory, + GetTypeNameSpecifierForSummaryAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBTypeFilter, SBTypeCategory, GetFilterForType, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeFormat, SBTypeCategory, GetFormatForType, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(lldb::SBTypeFormat, SBTypeCategory, GetFormatAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, AddTypeFormat, + (lldb::SBTypeNameSpecifier, lldb::SBTypeFormat)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, DeleteTypeFormat, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, DeleteTypeSummary, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, AddTypeFilter, + (lldb::SBTypeNameSpecifier, lldb::SBTypeFilter)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, DeleteTypeFilter, + (lldb::SBTypeNameSpecifier)); + LLDB_REGISTER_METHOD(bool, SBTypeCategory, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD( + lldb::SBTypeCategory &, + SBTypeCategory, operator=,(const lldb::SBTypeCategory &)); + LLDB_REGISTER_METHOD(bool, + SBTypeCategory, operator==,(lldb::SBTypeCategory &)); + LLDB_REGISTER_METHOD(bool, + SBTypeCategory, operator!=,(lldb::SBTypeCategory &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTypeEnumMember.cpp b/src/llvm-project/lldb/source/API/SBTypeEnumMember.cpp index 87be40e..bd0755a 100644 --- a/src/llvm-project/lldb/source/API/SBTypeEnumMember.cpp +++ b/src/llvm-project/lldb/source/API/SBTypeEnumMember.cpp
@@ -1,13 +1,14 @@ //===-- SBTypeEnumMember.cpp ---------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBDefines.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBType.h" @@ -15,58 +16,81 @@ #include "lldb/Symbol/Type.h" #include "lldb/Utility/Stream.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -SBTypeEnumMember::SBTypeEnumMember() : m_opaque_sp() {} +SBTypeEnumMember::SBTypeEnumMember() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeEnumMember); +} SBTypeEnumMember::~SBTypeEnumMember() {} + SBTypeEnumMember::SBTypeEnumMember( const lldb::TypeEnumMemberImplSP &enum_member_sp) : m_opaque_sp(enum_member_sp) {} SBTypeEnumMember::SBTypeEnumMember(const SBTypeEnumMember &rhs) : m_opaque_sp() { - if (this != &rhs) { - if (rhs.IsValid()) - m_opaque_sp.reset(new TypeEnumMemberImpl(rhs.ref())); - } + LLDB_RECORD_CONSTRUCTOR(SBTypeEnumMember, (const lldb::SBTypeEnumMember &), + rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); } SBTypeEnumMember &SBTypeEnumMember::operator=(const SBTypeEnumMember &rhs) { - if (this != &rhs) { - if (rhs.IsValid()) - m_opaque_sp.reset(new TypeEnumMemberImpl(rhs.ref())); - } - return *this; + LLDB_RECORD_METHOD( + SBTypeEnumMember &, + SBTypeEnumMember, operator=,(const lldb::SBTypeEnumMember &), rhs); + + if (this != &rhs) + m_opaque_sp = clone(rhs.m_opaque_sp); + return LLDB_RECORD_RESULT(*this); } -bool SBTypeEnumMember::IsValid() const { return m_opaque_sp.get(); } +bool SBTypeEnumMember::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeEnumMember, IsValid); + return this->operator bool(); +} +SBTypeEnumMember::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeEnumMember, operator bool); + + return m_opaque_sp.get(); +} const char *SBTypeEnumMember::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeEnumMember, GetName); + if (m_opaque_sp.get()) return m_opaque_sp->GetName().GetCString(); - return NULL; + return nullptr; } int64_t SBTypeEnumMember::GetValueAsSigned() { + LLDB_RECORD_METHOD_NO_ARGS(int64_t, SBTypeEnumMember, GetValueAsSigned); + if (m_opaque_sp.get()) return m_opaque_sp->GetValueAsSigned(); return 0; } uint64_t SBTypeEnumMember::GetValueAsUnsigned() { + LLDB_RECORD_METHOD_NO_ARGS(uint64_t, SBTypeEnumMember, GetValueAsUnsigned); + if (m_opaque_sp.get()) return m_opaque_sp->GetValueAsUnsigned(); return 0; } SBType SBTypeEnumMember::GetType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBTypeEnumMember, GetType); + SBType sb_type; if (m_opaque_sp.get()) { sb_type.SetSP(m_opaque_sp->GetIntegerType()); } - return sb_type; + return LLDB_RECORD_RESULT(sb_type); } void SBTypeEnumMember::reset(TypeEnumMemberImpl *type_member_impl) { @@ -74,8 +98,8 @@ } TypeEnumMemberImpl &SBTypeEnumMember::ref() { - if (m_opaque_sp.get() == NULL) - m_opaque_sp.reset(new TypeEnumMemberImpl()); + if (m_opaque_sp.get() == nullptr) + m_opaque_sp = std::make_shared<TypeEnumMemberImpl>(); return *m_opaque_sp.get(); } @@ -84,49 +108,82 @@ } SBTypeEnumMemberList::SBTypeEnumMemberList() - : m_opaque_ap(new TypeEnumMemberListImpl()) {} + : m_opaque_up(new TypeEnumMemberListImpl()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeEnumMemberList); +} SBTypeEnumMemberList::SBTypeEnumMemberList(const SBTypeEnumMemberList &rhs) - : m_opaque_ap(new TypeEnumMemberListImpl()) { + : m_opaque_up(new TypeEnumMemberListImpl()) { + LLDB_RECORD_CONSTRUCTOR(SBTypeEnumMemberList, + (const lldb::SBTypeEnumMemberList &), 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() { return (m_opaque_ap != NULL); } +bool SBTypeEnumMemberList::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeEnumMemberList, IsValid); + return this->operator bool(); +} +SBTypeEnumMemberList::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeEnumMemberList, operator bool); + + return (m_opaque_up != nullptr); +} SBTypeEnumMemberList &SBTypeEnumMemberList:: operator=(const SBTypeEnumMemberList &rhs) { + LLDB_RECORD_METHOD( + lldb::SBTypeEnumMemberList &, + SBTypeEnumMemberList, operator=,(const lldb::SBTypeEnumMemberList &), + rhs); + if (this != &rhs) { - m_opaque_ap.reset(new TypeEnumMemberListImpl()); + m_opaque_up.reset(new 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; + return LLDB_RECORD_RESULT(*this); } void SBTypeEnumMemberList::Append(SBTypeEnumMember enum_member) { + LLDB_RECORD_METHOD(void, SBTypeEnumMemberList, Append, + (lldb::SBTypeEnumMember), enum_member); + if (enum_member.IsValid()) - m_opaque_ap->Append(enum_member.m_opaque_sp); + m_opaque_up->Append(enum_member.m_opaque_sp); } SBTypeEnumMember SBTypeEnumMemberList::GetTypeEnumMemberAtIndex(uint32_t index) { - if (m_opaque_ap) - return SBTypeEnumMember(m_opaque_ap->GetTypeEnumMemberAtIndex(index)); - return SBTypeEnumMember(); + LLDB_RECORD_METHOD(lldb::SBTypeEnumMember, SBTypeEnumMemberList, + GetTypeEnumMemberAtIndex, (uint32_t), index); + + if (m_opaque_up) + return LLDB_RECORD_RESULT( + SBTypeEnumMember(m_opaque_up->GetTypeEnumMemberAtIndex(index))); + return LLDB_RECORD_RESULT(SBTypeEnumMember()); } -uint32_t SBTypeEnumMemberList::GetSize() { return m_opaque_ap->GetSize(); } +uint32_t SBTypeEnumMemberList::GetSize() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeEnumMemberList, GetSize); + + return m_opaque_up->GetSize(); +} SBTypeEnumMemberList::~SBTypeEnumMemberList() {} bool SBTypeEnumMember::GetDescription( lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeEnumMember, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + Stream &strm = description.ref(); if (m_opaque_sp.get()) { @@ -139,3 +196,40 @@ } return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTypeEnumMember>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeEnumMember, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeEnumMember, + (const lldb::SBTypeEnumMember &)); + LLDB_REGISTER_METHOD( + lldb::SBTypeEnumMember &, + SBTypeEnumMember, operator=,(const lldb::SBTypeEnumMember &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeEnumMember, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeEnumMember, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeEnumMember, GetName, ()); + LLDB_REGISTER_METHOD(int64_t, SBTypeEnumMember, GetValueAsSigned, ()); + LLDB_REGISTER_METHOD(uint64_t, SBTypeEnumMember, GetValueAsUnsigned, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBTypeEnumMember, GetType, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeEnumMemberList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeEnumMemberList, + (const lldb::SBTypeEnumMemberList &)); + LLDB_REGISTER_METHOD(bool, SBTypeEnumMemberList, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeEnumMemberList, operator bool, ()); + LLDB_REGISTER_METHOD( + lldb::SBTypeEnumMemberList &, + SBTypeEnumMemberList, operator=,(const lldb::SBTypeEnumMemberList &)); + LLDB_REGISTER_METHOD(void, SBTypeEnumMemberList, Append, + (lldb::SBTypeEnumMember)); + LLDB_REGISTER_METHOD(lldb::SBTypeEnumMember, SBTypeEnumMemberList, + GetTypeEnumMemberAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(uint32_t, SBTypeEnumMemberList, GetSize, ()); + LLDB_REGISTER_METHOD(bool, SBTypeEnumMember, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTypeFilter.cpp b/src/llvm-project/lldb/source/API/SBTypeFilter.cpp index 9709d2e..d40301b 100644 --- a/src/llvm-project/lldb/source/API/SBTypeFilter.cpp +++ b/src/llvm-project/lldb/source/API/SBTypeFilter.cpp
@@ -1,14 +1,14 @@ //===-- SBTypeFilter.cpp ------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" @@ -17,31 +17,53 @@ using namespace lldb; using namespace lldb_private; -SBTypeFilter::SBTypeFilter() : m_opaque_sp() {} +SBTypeFilter::SBTypeFilter() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeFilter); +} SBTypeFilter::SBTypeFilter(uint32_t options) - : m_opaque_sp(TypeFilterImplSP(new TypeFilterImpl(options))) {} + : m_opaque_sp(TypeFilterImplSP(new TypeFilterImpl(options))) { + LLDB_RECORD_CONSTRUCTOR(SBTypeFilter, (uint32_t), options); +} SBTypeFilter::SBTypeFilter(const lldb::SBTypeFilter &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTypeFilter, (const lldb::SBTypeFilter &), rhs); +} SBTypeFilter::~SBTypeFilter() {} -bool SBTypeFilter::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBTypeFilter::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeFilter, IsValid); + return this->operator bool(); +} +SBTypeFilter::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeFilter, operator bool); + + return m_opaque_sp.get() != nullptr; +} uint32_t SBTypeFilter::GetOptions() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeFilter, GetOptions); + if (IsValid()) return m_opaque_sp->GetOptions(); return 0; } void SBTypeFilter::SetOptions(uint32_t value) { + LLDB_RECORD_METHOD(void, SBTypeFilter, SetOptions, (uint32_t), value); + if (CopyOnWrite_Impl()) m_opaque_sp->SetOptions(value); } bool SBTypeFilter::GetDescription(lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeFilter, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + if (!IsValid()) return false; else { @@ -51,27 +73,38 @@ } void SBTypeFilter::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBTypeFilter, Clear); + if (CopyOnWrite_Impl()) m_opaque_sp->Clear(); } uint32_t SBTypeFilter::GetNumberOfExpressionPaths() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeFilter, + GetNumberOfExpressionPaths); + if (IsValid()) return m_opaque_sp->GetCount(); return 0; } const char *SBTypeFilter::GetExpressionPathAtIndex(uint32_t i) { + LLDB_RECORD_METHOD(const char *, SBTypeFilter, GetExpressionPathAtIndex, + (uint32_t), i); + if (IsValid()) { const char *item = m_opaque_sp->GetExpressionPathAtIndex(i); if (item && *item == '.') item++; return item; } - return NULL; + return nullptr; } bool SBTypeFilter::ReplaceExpressionPathAtIndex(uint32_t i, const char *item) { + LLDB_RECORD_METHOD(bool, SBTypeFilter, ReplaceExpressionPathAtIndex, + (uint32_t, const char *), i, item); + if (CopyOnWrite_Impl()) return m_opaque_sp->SetExpressionPathAtIndex(i, item); else @@ -79,18 +112,27 @@ } void SBTypeFilter::AppendExpressionPath(const char *item) { + LLDB_RECORD_METHOD(void, SBTypeFilter, AppendExpressionPath, (const char *), + item); + if (CopyOnWrite_Impl()) m_opaque_sp->AddExpressionPath(item); } lldb::SBTypeFilter &SBTypeFilter::operator=(const lldb::SBTypeFilter &rhs) { + LLDB_RECORD_METHOD(lldb::SBTypeFilter &, + SBTypeFilter, operator=,(const lldb::SBTypeFilter &), rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBTypeFilter::operator==(lldb::SBTypeFilter &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeFilter, operator==,(lldb::SBTypeFilter &), + rhs); + if (!IsValid()) return !rhs.IsValid(); @@ -98,6 +140,9 @@ } bool SBTypeFilter::IsEqualTo(lldb::SBTypeFilter &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeFilter, IsEqualTo, (lldb::SBTypeFilter &), + rhs); + if (!IsValid()) return !rhs.IsValid(); @@ -113,6 +158,9 @@ } bool SBTypeFilter::operator!=(lldb::SBTypeFilter &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeFilter, operator!=,(lldb::SBTypeFilter &), + rhs); + if (!IsValid()) return !rhs.IsValid(); @@ -143,3 +191,36 @@ return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTypeFilter>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeFilter, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeFilter, (uint32_t)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeFilter, (const lldb::SBTypeFilter &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeFilter, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeFilter, operator bool, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeFilter, GetOptions, ()); + LLDB_REGISTER_METHOD(void, SBTypeFilter, SetOptions, (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTypeFilter, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD(void, SBTypeFilter, Clear, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeFilter, GetNumberOfExpressionPaths, + ()); + LLDB_REGISTER_METHOD(const char *, SBTypeFilter, GetExpressionPathAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTypeFilter, ReplaceExpressionPathAtIndex, + (uint32_t, const char *)); + LLDB_REGISTER_METHOD(void, SBTypeFilter, AppendExpressionPath, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBTypeFilter &, + SBTypeFilter, operator=,(const lldb::SBTypeFilter &)); + LLDB_REGISTER_METHOD(bool, SBTypeFilter, operator==,(lldb::SBTypeFilter &)); + LLDB_REGISTER_METHOD(bool, SBTypeFilter, IsEqualTo, (lldb::SBTypeFilter &)); + LLDB_REGISTER_METHOD(bool, SBTypeFilter, operator!=,(lldb::SBTypeFilter &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTypeFormat.cpp b/src/llvm-project/lldb/source/API/SBTypeFormat.cpp index 66bfd36..6024631 100644 --- a/src/llvm-project/lldb/source/API/SBTypeFormat.cpp +++ b/src/llvm-project/lldb/source/API/SBTypeFormat.cpp
@@ -1,14 +1,14 @@ //===-- SBTypeFormat.cpp ------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" @@ -17,30 +17,52 @@ using namespace lldb; using namespace lldb_private; -SBTypeFormat::SBTypeFormat() : m_opaque_sp() {} +SBTypeFormat::SBTypeFormat() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeFormat); +} SBTypeFormat::SBTypeFormat(lldb::Format format, uint32_t options) : m_opaque_sp( - TypeFormatImplSP(new TypeFormatImpl_Format(format, options))) {} + TypeFormatImplSP(new TypeFormatImpl_Format(format, options))) { + LLDB_RECORD_CONSTRUCTOR(SBTypeFormat, (lldb::Format, uint32_t), format, + options); +} SBTypeFormat::SBTypeFormat(const char *type, uint32_t options) : m_opaque_sp(TypeFormatImplSP(new TypeFormatImpl_EnumType( - ConstString(type ? type : ""), options))) {} + ConstString(type ? type : ""), options))) { + LLDB_RECORD_CONSTRUCTOR(SBTypeFormat, (const char *, uint32_t), type, + options); +} SBTypeFormat::SBTypeFormat(const lldb::SBTypeFormat &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTypeFormat, (const lldb::SBTypeFormat &), rhs); +} SBTypeFormat::~SBTypeFormat() {} -bool SBTypeFormat::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBTypeFormat::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeFormat, IsValid); + return this->operator bool(); +} +SBTypeFormat::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeFormat, operator bool); + + return m_opaque_sp.get() != nullptr; +} lldb::Format SBTypeFormat::GetFormat() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::Format, SBTypeFormat, GetFormat); + 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_RECORD_METHOD_NO_ARGS(const char *, SBTypeFormat, GetTypeName); + if (IsValid() && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeEnum) return ((TypeFormatImpl_EnumType *)m_opaque_sp.get()) ->GetTypeName() @@ -49,29 +71,41 @@ } uint32_t SBTypeFormat::GetOptions() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeFormat, GetOptions); + if (IsValid()) return m_opaque_sp->GetOptions(); return 0; } void SBTypeFormat::SetFormat(lldb::Format fmt) { + LLDB_RECORD_METHOD(void, SBTypeFormat, SetFormat, (lldb::Format), fmt); + if (CopyOnWrite_Impl(Type::eTypeFormat)) ((TypeFormatImpl_Format *)m_opaque_sp.get())->SetFormat(fmt); } void SBTypeFormat::SetTypeName(const char *type) { + LLDB_RECORD_METHOD(void, SBTypeFormat, SetTypeName, (const char *), type); + if (CopyOnWrite_Impl(Type::eTypeEnum)) ((TypeFormatImpl_EnumType *)m_opaque_sp.get()) ->SetTypeName(ConstString(type ? type : "")); } void SBTypeFormat::SetOptions(uint32_t value) { + LLDB_RECORD_METHOD(void, SBTypeFormat, SetOptions, (uint32_t), value); + if (CopyOnWrite_Impl(Type::eTypeKeepSame)) m_opaque_sp->SetOptions(value); } bool SBTypeFormat::GetDescription(lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeFormat, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + if (!IsValid()) return false; else { @@ -81,19 +115,28 @@ } lldb::SBTypeFormat &SBTypeFormat::operator=(const lldb::SBTypeFormat &rhs) { + LLDB_RECORD_METHOD(lldb::SBTypeFormat &, + SBTypeFormat, operator=,(const lldb::SBTypeFormat &), rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBTypeFormat::operator==(lldb::SBTypeFormat &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeFormat, operator==,(lldb::SBTypeFormat &), + rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp == rhs.m_opaque_sp; } bool SBTypeFormat::IsEqualTo(lldb::SBTypeFormat &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeFormat, IsEqualTo, (lldb::SBTypeFormat &), + rhs); + if (!IsValid()) return !rhs.IsValid(); @@ -104,6 +147,9 @@ } bool SBTypeFormat::operator!=(lldb::SBTypeFormat &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeFormat, operator!=,(lldb::SBTypeFormat &), + rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp != rhs.m_opaque_sp; @@ -146,3 +192,32 @@ return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTypeFormat>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeFormat, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeFormat, (lldb::Format, uint32_t)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeFormat, (const char *, uint32_t)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeFormat, (const lldb::SBTypeFormat &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeFormat, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeFormat, operator bool, ()); + LLDB_REGISTER_METHOD(lldb::Format, SBTypeFormat, GetFormat, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeFormat, GetTypeName, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeFormat, GetOptions, ()); + LLDB_REGISTER_METHOD(void, SBTypeFormat, SetFormat, (lldb::Format)); + LLDB_REGISTER_METHOD(void, SBTypeFormat, SetTypeName, (const char *)); + LLDB_REGISTER_METHOD(void, SBTypeFormat, SetOptions, (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTypeFormat, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD(lldb::SBTypeFormat &, + SBTypeFormat, operator=,(const lldb::SBTypeFormat &)); + LLDB_REGISTER_METHOD(bool, SBTypeFormat, operator==,(lldb::SBTypeFormat &)); + LLDB_REGISTER_METHOD(bool, SBTypeFormat, IsEqualTo, (lldb::SBTypeFormat &)); + LLDB_REGISTER_METHOD(bool, SBTypeFormat, operator!=,(lldb::SBTypeFormat &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTypeNameSpecifier.cpp b/src/llvm-project/lldb/source/API/SBTypeNameSpecifier.cpp index 5ffb3d9..895f697 100644 --- a/src/llvm-project/lldb/source/API/SBTypeNameSpecifier.cpp +++ b/src/llvm-project/lldb/source/API/SBTypeNameSpecifier.cpp
@@ -1,14 +1,14 @@ //===-- SBTypeNameSpecifier.cpp ------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBType.h" @@ -18,44 +18,68 @@ using namespace lldb; using namespace lldb_private; -SBTypeNameSpecifier::SBTypeNameSpecifier() : m_opaque_sp() {} +SBTypeNameSpecifier::SBTypeNameSpecifier() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeNameSpecifier); +} SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex) : m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) { - if (name == NULL || (*name) == 0) + LLDB_RECORD_CONSTRUCTOR(SBTypeNameSpecifier, (const char *, bool), name, + is_regex); + + if (name == nullptr || (*name) == 0) m_opaque_sp.reset(); } SBTypeNameSpecifier::SBTypeNameSpecifier(SBType type) : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR(SBTypeNameSpecifier, (lldb::SBType), 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) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTypeNameSpecifier, + (const lldb::SBTypeNameSpecifier &), rhs); +} SBTypeNameSpecifier::~SBTypeNameSpecifier() {} -bool SBTypeNameSpecifier::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBTypeNameSpecifier::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeNameSpecifier, IsValid); + return this->operator bool(); +} +SBTypeNameSpecifier::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeNameSpecifier, operator bool); + + return m_opaque_sp.get() != nullptr; +} const char *SBTypeNameSpecifier::GetName() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeNameSpecifier, GetName); + if (!IsValid()) - return NULL; + return nullptr; return m_opaque_sp->GetName(); } SBType SBTypeNameSpecifier::GetType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBTypeNameSpecifier, GetType); + if (!IsValid()) - return SBType(); + return LLDB_RECORD_RESULT(SBType()); lldb_private::CompilerType c_type = m_opaque_sp->GetCompilerType(); if (c_type.IsValid()) - return SBType(c_type); - return SBType(); + return LLDB_RECORD_RESULT(SBType(c_type)); + return LLDB_RECORD_RESULT(SBType()); } bool SBTypeNameSpecifier::IsRegex() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeNameSpecifier, IsRegex); + if (!IsValid()) return false; @@ -64,6 +88,10 @@ bool SBTypeNameSpecifier::GetDescription( lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeNameSpecifier, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + if (!IsValid()) return false; description.Printf("SBTypeNameSpecifier(%s,%s)", GetName(), @@ -73,31 +101,44 @@ lldb::SBTypeNameSpecifier &SBTypeNameSpecifier:: operator=(const lldb::SBTypeNameSpecifier &rhs) { + LLDB_RECORD_METHOD( + lldb::SBTypeNameSpecifier &, + SBTypeNameSpecifier, operator=,(const lldb::SBTypeNameSpecifier &), rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBTypeNameSpecifier::operator==(lldb::SBTypeNameSpecifier &rhs) { + LLDB_RECORD_METHOD( + bool, SBTypeNameSpecifier, operator==,(lldb::SBTypeNameSpecifier &), rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp == rhs.m_opaque_sp; } bool SBTypeNameSpecifier::IsEqualTo(lldb::SBTypeNameSpecifier &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeNameSpecifier, IsEqualTo, + (lldb::SBTypeNameSpecifier &), rhs); + if (!IsValid()) return !rhs.IsValid(); if (IsRegex() != rhs.IsRegex()) return false; - if (GetName() == NULL || rhs.GetName() == NULL) + if (GetName() == nullptr || rhs.GetName() == nullptr) return false; return (strcmp(GetName(), rhs.GetName()) == 0); } bool SBTypeNameSpecifier::operator!=(lldb::SBTypeNameSpecifier &rhs) { + LLDB_RECORD_METHOD( + bool, SBTypeNameSpecifier, operator!=,(lldb::SBTypeNameSpecifier &), rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp != rhs.m_opaque_sp; @@ -115,3 +156,34 @@ SBTypeNameSpecifier::SBTypeNameSpecifier( const lldb::TypeNameSpecifierImplSP &type_namespec_sp) : m_opaque_sp(type_namespec_sp) {} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTypeNameSpecifier>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeNameSpecifier, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeNameSpecifier, (const char *, bool)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeNameSpecifier, (lldb::SBType)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeNameSpecifier, + (const lldb::SBTypeNameSpecifier &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeNameSpecifier, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeNameSpecifier, operator bool, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeNameSpecifier, GetName, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBTypeNameSpecifier, GetType, ()); + LLDB_REGISTER_METHOD(bool, SBTypeNameSpecifier, IsRegex, ()); + LLDB_REGISTER_METHOD(bool, SBTypeNameSpecifier, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD( + lldb::SBTypeNameSpecifier &, + SBTypeNameSpecifier, operator=,(const lldb::SBTypeNameSpecifier &)); + LLDB_REGISTER_METHOD( + bool, SBTypeNameSpecifier, operator==,(lldb::SBTypeNameSpecifier &)); + LLDB_REGISTER_METHOD(bool, SBTypeNameSpecifier, IsEqualTo, + (lldb::SBTypeNameSpecifier &)); + LLDB_REGISTER_METHOD( + bool, SBTypeNameSpecifier, operator!=,(lldb::SBTypeNameSpecifier &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTypeSummary.cpp b/src/llvm-project/lldb/source/API/SBTypeSummary.cpp index 76c94ae..8ffb234 100644 --- a/src/llvm-project/lldb/source/API/SBTypeSummary.cpp +++ b/src/llvm-project/lldb/source/API/SBTypeSummary.cpp
@@ -1,14 +1,15 @@ //===-- SBTypeSummary.cpp -----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" +#include "Utils.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBValue.h" #include "lldb/DataFormatters/DataVisualization.h" @@ -19,109 +20,154 @@ using namespace lldb_private; SBTypeSummaryOptions::SBTypeSummaryOptions() { - m_opaque_ap.reset(new TypeSummaryOptions()); + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeSummaryOptions); + + m_opaque_up.reset(new TypeSummaryOptions()); } SBTypeSummaryOptions::SBTypeSummaryOptions( const lldb::SBTypeSummaryOptions &rhs) { - if (rhs.m_opaque_ap) - m_opaque_ap.reset(new TypeSummaryOptions(*rhs.m_opaque_ap)); - else - m_opaque_ap.reset(new TypeSummaryOptions()); + LLDB_RECORD_CONSTRUCTOR(SBTypeSummaryOptions, + (const lldb::SBTypeSummaryOptions &), rhs); + + m_opaque_up = clone(rhs.m_opaque_up); } SBTypeSummaryOptions::~SBTypeSummaryOptions() {} -bool SBTypeSummaryOptions::IsValid() { return m_opaque_ap.get(); } +bool SBTypeSummaryOptions::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeSummaryOptions, IsValid); + return this->operator bool(); +} +SBTypeSummaryOptions::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeSummaryOptions, operator bool); + + return m_opaque_up.get(); +} lldb::LanguageType SBTypeSummaryOptions::GetLanguage() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::LanguageType, SBTypeSummaryOptions, + GetLanguage); + if (IsValid()) - return m_opaque_ap->GetLanguage(); + return m_opaque_up->GetLanguage(); return lldb::eLanguageTypeUnknown; } lldb::TypeSummaryCapping SBTypeSummaryOptions::GetCapping() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::TypeSummaryCapping, SBTypeSummaryOptions, + GetCapping); + if (IsValid()) - return m_opaque_ap->GetCapping(); + return m_opaque_up->GetCapping(); return eTypeSummaryCapped; } void SBTypeSummaryOptions::SetLanguage(lldb::LanguageType l) { + LLDB_RECORD_METHOD(void, SBTypeSummaryOptions, SetLanguage, + (lldb::LanguageType), l); + if (IsValid()) - m_opaque_ap->SetLanguage(l); + m_opaque_up->SetLanguage(l); } void SBTypeSummaryOptions::SetCapping(lldb::TypeSummaryCapping c) { + LLDB_RECORD_METHOD(void, SBTypeSummaryOptions, SetCapping, + (lldb::TypeSummaryCapping), c); + if (IsValid()) - m_opaque_ap->SetCapping(c); + m_opaque_up->SetCapping(c); } lldb_private::TypeSummaryOptions *SBTypeSummaryOptions::operator->() { - return m_opaque_ap.get(); + return m_opaque_up.get(); } const lldb_private::TypeSummaryOptions *SBTypeSummaryOptions:: operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } lldb_private::TypeSummaryOptions *SBTypeSummaryOptions::get() { - return m_opaque_ap.get(); + return m_opaque_up.get(); } lldb_private::TypeSummaryOptions &SBTypeSummaryOptions::ref() { - return *m_opaque_ap; + return *m_opaque_up; } const lldb_private::TypeSummaryOptions &SBTypeSummaryOptions::ref() const { - return *m_opaque_ap; + return *m_opaque_up; } SBTypeSummaryOptions::SBTypeSummaryOptions( const lldb_private::TypeSummaryOptions *lldb_object_ptr) { + LLDB_RECORD_CONSTRUCTOR(SBTypeSummaryOptions, + (const lldb_private::TypeSummaryOptions *), + lldb_object_ptr); + SetOptions(lldb_object_ptr); } void SBTypeSummaryOptions::SetOptions( const lldb_private::TypeSummaryOptions *lldb_object_ptr) { if (lldb_object_ptr) - m_opaque_ap.reset(new TypeSummaryOptions(*lldb_object_ptr)); + m_opaque_up.reset(new TypeSummaryOptions(*lldb_object_ptr)); else - m_opaque_ap.reset(new TypeSummaryOptions()); + m_opaque_up.reset(new TypeSummaryOptions()); } -SBTypeSummary::SBTypeSummary() : m_opaque_sp() {} +SBTypeSummary::SBTypeSummary() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeSummary); +} SBTypeSummary SBTypeSummary::CreateWithSummaryString(const char *data, uint32_t options) { - if (!data || data[0] == 0) - return SBTypeSummary(); + LLDB_RECORD_STATIC_METHOD(lldb::SBTypeSummary, SBTypeSummary, + CreateWithSummaryString, (const char *, uint32_t), + data, options); - return SBTypeSummary( - TypeSummaryImplSP(new StringSummaryFormat(options, data))); + if (!data || data[0] == 0) + return LLDB_RECORD_RESULT(SBTypeSummary()); + + return LLDB_RECORD_RESULT( + SBTypeSummary(TypeSummaryImplSP(new StringSummaryFormat(options, data)))); } SBTypeSummary SBTypeSummary::CreateWithFunctionName(const char *data, uint32_t options) { - if (!data || data[0] == 0) - return SBTypeSummary(); + LLDB_RECORD_STATIC_METHOD(lldb::SBTypeSummary, SBTypeSummary, + CreateWithFunctionName, (const char *, uint32_t), + data, options); - return SBTypeSummary( - TypeSummaryImplSP(new ScriptSummaryFormat(options, data))); + if (!data || data[0] == 0) + return LLDB_RECORD_RESULT(SBTypeSummary()); + + return LLDB_RECORD_RESULT( + SBTypeSummary(TypeSummaryImplSP(new ScriptSummaryFormat(options, data)))); } SBTypeSummary SBTypeSummary::CreateWithScriptCode(const char *data, uint32_t options) { - if (!data || data[0] == 0) - return SBTypeSummary(); + LLDB_RECORD_STATIC_METHOD(lldb::SBTypeSummary, SBTypeSummary, + CreateWithScriptCode, (const char *, uint32_t), + data, options); - return SBTypeSummary( - TypeSummaryImplSP(new ScriptSummaryFormat(options, "", data))); + if (!data || data[0] == 0) + return LLDB_RECORD_RESULT(SBTypeSummary()); + + return LLDB_RECORD_RESULT(SBTypeSummary( + TypeSummaryImplSP(new ScriptSummaryFormat(options, "", data)))); } SBTypeSummary SBTypeSummary::CreateWithCallback(FormatCallback cb, uint32_t options, const char *description) { + LLDB_RECORD_DUMMY( + lldb::SBTypeSummary, SBTypeSummary, CreateWithCallback, + (lldb::SBTypeSummary::FormatCallback, uint32_t, const char *), cb, + options, description); + SBTypeSummary retval; if (cb) { retval.SetSP(TypeSummaryImplSP(new CXXFunctionSummaryFormat( @@ -143,13 +189,25 @@ } SBTypeSummary::SBTypeSummary(const lldb::SBTypeSummary &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTypeSummary, (const lldb::SBTypeSummary &), rhs); +} SBTypeSummary::~SBTypeSummary() {} -bool SBTypeSummary::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBTypeSummary::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeSummary, IsValid); + return this->operator bool(); +} +SBTypeSummary::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeSummary, operator bool); + + return m_opaque_sp.get() != nullptr; +} bool SBTypeSummary::IsFunctionCode() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeSummary, IsFunctionCode); + if (!IsValid()) return false; if (ScriptSummaryFormat *script_summary_ptr = @@ -161,6 +219,8 @@ } bool SBTypeSummary::IsFunctionName() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeSummary, IsFunctionName); + if (!IsValid()) return false; if (ScriptSummaryFormat *script_summary_ptr = @@ -172,6 +232,8 @@ } bool SBTypeSummary::IsSummaryString() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeSummary, IsSummaryString); + if (!IsValid()) return false; @@ -179,8 +241,10 @@ } const char *SBTypeSummary::GetData() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeSummary, GetData); + if (!IsValid()) - return NULL; + return nullptr; if (ScriptSummaryFormat *script_summary_ptr = llvm::dyn_cast<ScriptSummaryFormat>(m_opaque_sp.get())) { const char *fname = script_summary_ptr->GetFunctionName(); @@ -195,18 +259,25 @@ } uint32_t SBTypeSummary::GetOptions() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeSummary, GetOptions); + if (!IsValid()) return lldb::eTypeOptionNone; return m_opaque_sp->GetOptions(); } void SBTypeSummary::SetOptions(uint32_t value) { + LLDB_RECORD_METHOD(void, SBTypeSummary, SetOptions, (uint32_t), value); + if (!CopyOnWrite_Impl()) return; m_opaque_sp->SetOptions(value); } void SBTypeSummary::SetSummaryString(const char *data) { + LLDB_RECORD_METHOD(void, SBTypeSummary, SetSummaryString, (const char *), + data); + if (!IsValid()) return; if (!llvm::isa<StringSummaryFormat>(m_opaque_sp.get())) @@ -217,6 +288,9 @@ } void SBTypeSummary::SetFunctionName(const char *data) { + LLDB_RECORD_METHOD(void, SBTypeSummary, SetFunctionName, (const char *), + data); + if (!IsValid()) return; if (!llvm::isa<ScriptSummaryFormat>(m_opaque_sp.get())) @@ -227,6 +301,9 @@ } void SBTypeSummary::SetFunctionCode(const char *data) { + LLDB_RECORD_METHOD(void, SBTypeSummary, SetFunctionCode, (const char *), + data); + if (!IsValid()) return; if (!llvm::isa<ScriptSummaryFormat>(m_opaque_sp.get())) @@ -238,6 +315,10 @@ bool SBTypeSummary::GetDescription(lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeSummary, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + if (!CopyOnWrite_Impl()) return false; else { @@ -247,6 +328,9 @@ } bool SBTypeSummary::DoesPrintValue(lldb::SBValue value) { + LLDB_RECORD_METHOD(bool, SBTypeSummary, DoesPrintValue, (lldb::SBValue), + value); + if (!IsValid()) return false; lldb::ValueObjectSP value_sp = value.GetSP(); @@ -254,19 +338,29 @@ } lldb::SBTypeSummary &SBTypeSummary::operator=(const lldb::SBTypeSummary &rhs) { + LLDB_RECORD_METHOD(lldb::SBTypeSummary &, + SBTypeSummary, operator=,(const lldb::SBTypeSummary &), + rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBTypeSummary::operator==(lldb::SBTypeSummary &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeSummary, operator==,(lldb::SBTypeSummary &), + rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp == rhs.m_opaque_sp; } bool SBTypeSummary::IsEqualTo(lldb::SBTypeSummary &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeSummary, IsEqualTo, (lldb::SBTypeSummary &), + rhs); + if (IsValid()) { // valid and invalid are different if (!rhs.IsValid()) @@ -305,6 +399,9 @@ } bool SBTypeSummary::operator!=(lldb::SBTypeSummary &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeSummary, operator!=,(lldb::SBTypeSummary &), + rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp != rhs.m_opaque_sp; @@ -376,3 +473,65 @@ return true; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTypeSummaryOptions>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeSummaryOptions, ()); + LLDB_REGISTER_CONSTRUCTOR(SBTypeSummaryOptions, + (const lldb::SBTypeSummaryOptions &)); + LLDB_REGISTER_METHOD(bool, SBTypeSummaryOptions, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeSummaryOptions, operator bool, ()); + LLDB_REGISTER_METHOD(lldb::LanguageType, SBTypeSummaryOptions, GetLanguage, + ()); + LLDB_REGISTER_METHOD(lldb::TypeSummaryCapping, SBTypeSummaryOptions, + GetCapping, ()); + LLDB_REGISTER_METHOD(void, SBTypeSummaryOptions, SetLanguage, + (lldb::LanguageType)); + LLDB_REGISTER_METHOD(void, SBTypeSummaryOptions, SetCapping, + (lldb::TypeSummaryCapping)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeSummaryOptions, + (const lldb_private::TypeSummaryOptions *)); +} + +template <> +void RegisterMethods<SBTypeSummary>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeSummary, ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBTypeSummary, SBTypeSummary, + CreateWithSummaryString, + (const char *, uint32_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBTypeSummary, SBTypeSummary, + CreateWithFunctionName, + (const char *, uint32_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBTypeSummary, SBTypeSummary, + CreateWithScriptCode, (const char *, uint32_t)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeSummary, (const lldb::SBTypeSummary &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeSummary, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeSummary, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBTypeSummary, IsFunctionCode, ()); + LLDB_REGISTER_METHOD(bool, SBTypeSummary, IsFunctionName, ()); + LLDB_REGISTER_METHOD(bool, SBTypeSummary, IsSummaryString, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeSummary, GetData, ()); + LLDB_REGISTER_METHOD(uint32_t, SBTypeSummary, GetOptions, ()); + LLDB_REGISTER_METHOD(void, SBTypeSummary, SetOptions, (uint32_t)); + LLDB_REGISTER_METHOD(void, SBTypeSummary, SetSummaryString, (const char *)); + LLDB_REGISTER_METHOD(void, SBTypeSummary, SetFunctionName, (const char *)); + LLDB_REGISTER_METHOD(void, SBTypeSummary, SetFunctionCode, (const char *)); + LLDB_REGISTER_METHOD(bool, SBTypeSummary, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD(bool, SBTypeSummary, DoesPrintValue, (lldb::SBValue)); + LLDB_REGISTER_METHOD( + lldb::SBTypeSummary &, + SBTypeSummary, operator=,(const lldb::SBTypeSummary &)); + LLDB_REGISTER_METHOD(bool, + SBTypeSummary, operator==,(lldb::SBTypeSummary &)); + LLDB_REGISTER_METHOD(bool, SBTypeSummary, IsEqualTo, + (lldb::SBTypeSummary &)); + LLDB_REGISTER_METHOD(bool, + SBTypeSummary, operator!=,(lldb::SBTypeSummary &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBTypeSynthetic.cpp b/src/llvm-project/lldb/source/API/SBTypeSynthetic.cpp index 750d917..df6fce1 100644 --- a/src/llvm-project/lldb/source/API/SBTypeSynthetic.cpp +++ b/src/llvm-project/lldb/source/API/SBTypeSynthetic.cpp
@@ -1,14 +1,14 @@ //===-- SBTypeSynthetic.cpp -----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" @@ -17,34 +17,55 @@ using namespace lldb; using namespace lldb_private; -#ifndef LLDB_DISABLE_PYTHON - -SBTypeSynthetic::SBTypeSynthetic() : m_opaque_sp() {} +SBTypeSynthetic::SBTypeSynthetic() : m_opaque_sp() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBTypeSynthetic); +} SBTypeSynthetic SBTypeSynthetic::CreateWithClassName(const char *data, uint32_t options) { + LLDB_RECORD_STATIC_METHOD(lldb::SBTypeSynthetic, SBTypeSynthetic, + CreateWithClassName, (const char *, uint32_t), data, + options); + if (!data || data[0] == 0) - return SBTypeSynthetic(); - return SBTypeSynthetic(ScriptedSyntheticChildrenSP( - new ScriptedSyntheticChildren(options, data, ""))); + return LLDB_RECORD_RESULT(SBTypeSynthetic()); + return LLDB_RECORD_RESULT(SBTypeSynthetic(ScriptedSyntheticChildrenSP( + new ScriptedSyntheticChildren(options, data, "")))); } SBTypeSynthetic SBTypeSynthetic::CreateWithScriptCode(const char *data, uint32_t options) { + LLDB_RECORD_STATIC_METHOD(lldb::SBTypeSynthetic, SBTypeSynthetic, + CreateWithScriptCode, (const char *, uint32_t), + data, options); + if (!data || data[0] == 0) - return SBTypeSynthetic(); - return SBTypeSynthetic(ScriptedSyntheticChildrenSP( - new ScriptedSyntheticChildren(options, "", data))); + return LLDB_RECORD_RESULT(SBTypeSynthetic()); + return LLDB_RECORD_RESULT(SBTypeSynthetic(ScriptedSyntheticChildrenSP( + new ScriptedSyntheticChildren(options, "", data)))); } SBTypeSynthetic::SBTypeSynthetic(const lldb::SBTypeSynthetic &rhs) - : m_opaque_sp(rhs.m_opaque_sp) {} + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_RECORD_CONSTRUCTOR(SBTypeSynthetic, (const lldb::SBTypeSynthetic &), + rhs); +} SBTypeSynthetic::~SBTypeSynthetic() {} -bool SBTypeSynthetic::IsValid() const { return m_opaque_sp.get() != NULL; } +bool SBTypeSynthetic::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeSynthetic, IsValid); + return this->operator bool(); +} +SBTypeSynthetic::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBTypeSynthetic, operator bool); + + return m_opaque_sp.get() != nullptr; +} bool SBTypeSynthetic::IsClassCode() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeSynthetic, IsClassCode); + if (!IsValid()) return false; const char *code = m_opaque_sp->GetPythonCode(); @@ -52,14 +73,18 @@ } bool SBTypeSynthetic::IsClassName() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBTypeSynthetic, IsClassName); + if (!IsValid()) return false; return !IsClassCode(); } const char *SBTypeSynthetic::GetData() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBTypeSynthetic, GetData); + if (!IsValid()) - return NULL; + return nullptr; if (IsClassCode()) return m_opaque_sp->GetPythonCode(); else @@ -67,22 +92,30 @@ } void SBTypeSynthetic::SetClassName(const char *data) { + LLDB_RECORD_METHOD(void, SBTypeSynthetic, SetClassName, (const char *), data); + if (IsValid() && data && *data) m_opaque_sp->SetPythonClassName(data); } void SBTypeSynthetic::SetClassCode(const char *data) { + LLDB_RECORD_METHOD(void, SBTypeSynthetic, SetClassCode, (const char *), data); + if (IsValid() && data && *data) m_opaque_sp->SetPythonCode(data); } uint32_t SBTypeSynthetic::GetOptions() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBTypeSynthetic, GetOptions); + if (!IsValid()) return lldb::eTypeOptionNone; return m_opaque_sp->GetOptions(); } void SBTypeSynthetic::SetOptions(uint32_t value) { + LLDB_RECORD_METHOD(void, SBTypeSynthetic, SetOptions, (uint32_t), value); + if (!CopyOnWrite_Impl()) return; m_opaque_sp->SetOptions(value); @@ -90,6 +123,10 @@ bool SBTypeSynthetic::GetDescription(lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_RECORD_METHOD(bool, SBTypeSynthetic, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + description_level); + if (m_opaque_sp) { description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); return true; @@ -99,19 +136,29 @@ lldb::SBTypeSynthetic &SBTypeSynthetic:: operator=(const lldb::SBTypeSynthetic &rhs) { + LLDB_RECORD_METHOD(lldb::SBTypeSynthetic &, + SBTypeSynthetic, operator=,(const lldb::SBTypeSynthetic &), + rhs); + if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } - return *this; + return LLDB_RECORD_RESULT(*this); } bool SBTypeSynthetic::operator==(lldb::SBTypeSynthetic &rhs) { + LLDB_RECORD_METHOD( + bool, SBTypeSynthetic, operator==,(lldb::SBTypeSynthetic &), rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp == rhs.m_opaque_sp; } bool SBTypeSynthetic::IsEqualTo(lldb::SBTypeSynthetic &rhs) { + LLDB_RECORD_METHOD(bool, SBTypeSynthetic, IsEqualTo, + (lldb::SBTypeSynthetic &), rhs); + if (!IsValid()) return !rhs.IsValid(); @@ -128,6 +175,9 @@ } bool SBTypeSynthetic::operator!=(lldb::SBTypeSynthetic &rhs) { + LLDB_RECORD_METHOD( + bool, SBTypeSynthetic, operator!=,(lldb::SBTypeSynthetic &), rhs); + if (!IsValid()) return !rhs.IsValid(); return m_opaque_sp != rhs.m_opaque_sp; @@ -161,4 +211,38 @@ return true; } -#endif // LLDB_DISABLE_PYTHON +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBTypeSynthetic>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBTypeSynthetic, ()); + LLDB_REGISTER_STATIC_METHOD(lldb::SBTypeSynthetic, SBTypeSynthetic, + CreateWithClassName, (const char *, uint32_t)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBTypeSynthetic, SBTypeSynthetic, + CreateWithScriptCode, (const char *, uint32_t)); + LLDB_REGISTER_CONSTRUCTOR(SBTypeSynthetic, (const lldb::SBTypeSynthetic &)); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeSynthetic, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBTypeSynthetic, operator bool, ()); + LLDB_REGISTER_METHOD(bool, SBTypeSynthetic, IsClassCode, ()); + LLDB_REGISTER_METHOD(bool, SBTypeSynthetic, IsClassName, ()); + LLDB_REGISTER_METHOD(const char *, SBTypeSynthetic, GetData, ()); + LLDB_REGISTER_METHOD(void, SBTypeSynthetic, SetClassName, (const char *)); + LLDB_REGISTER_METHOD(void, SBTypeSynthetic, SetClassCode, (const char *)); + LLDB_REGISTER_METHOD(uint32_t, SBTypeSynthetic, GetOptions, ()); + LLDB_REGISTER_METHOD(void, SBTypeSynthetic, SetOptions, (uint32_t)); + LLDB_REGISTER_METHOD(bool, SBTypeSynthetic, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD( + lldb::SBTypeSynthetic &, + SBTypeSynthetic, operator=,(const lldb::SBTypeSynthetic &)); + LLDB_REGISTER_METHOD(bool, + SBTypeSynthetic, operator==,(lldb::SBTypeSynthetic &)); + LLDB_REGISTER_METHOD(bool, SBTypeSynthetic, IsEqualTo, + (lldb::SBTypeSynthetic &)); + LLDB_REGISTER_METHOD(bool, + SBTypeSynthetic, operator!=,(lldb::SBTypeSynthetic &)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBUnixSignals.cpp b/src/llvm-project/lldb/source/API/SBUnixSignals.cpp index 14bdd39..277a92d 100644 --- a/src/llvm-project/lldb/source/API/SBUnixSignals.cpp +++ b/src/llvm-project/lldb/source/API/SBUnixSignals.cpp
@@ -1,17 +1,16 @@ //===-- SBUnixSignals.cpp -------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/UnixSignals.h" -#include "lldb/Utility/Log.h" #include "lldb/lldb-defines.h" #include "lldb/API/SBUnixSignals.h" @@ -19,10 +18,14 @@ using namespace lldb; using namespace lldb_private; -SBUnixSignals::SBUnixSignals() {} +SBUnixSignals::SBUnixSignals() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBUnixSignals); +} SBUnixSignals::SBUnixSignals(const SBUnixSignals &rhs) - : m_opaque_wp(rhs.m_opaque_wp) {} + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_RECORD_CONSTRUCTOR(SBUnixSignals, (const lldb::SBUnixSignals &), rhs); +} SBUnixSignals::SBUnixSignals(ProcessSP &process_sp) : m_opaque_wp(process_sp ? process_sp->GetUnixSignals() : nullptr) {} @@ -31,9 +34,13 @@ : m_opaque_wp(platform_sp ? platform_sp->GetUnixSignals() : nullptr) {} const SBUnixSignals &SBUnixSignals::operator=(const SBUnixSignals &rhs) { + LLDB_RECORD_METHOD(const lldb::SBUnixSignals &, + SBUnixSignals, operator=,(const lldb::SBUnixSignals &), + rhs); + if (this != &rhs) m_opaque_wp = rhs.m_opaque_wp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBUnixSignals::~SBUnixSignals() {} @@ -44,11 +51,26 @@ m_opaque_wp = signals_sp; } -void SBUnixSignals::Clear() { m_opaque_wp.reset(); } +void SBUnixSignals::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBUnixSignals, Clear); -bool SBUnixSignals::IsValid() const { return static_cast<bool>(GetSP()); } + m_opaque_wp.reset(); +} + +bool SBUnixSignals::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBUnixSignals, IsValid); + return this->operator bool(); +} +SBUnixSignals::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBUnixSignals, operator bool); + + return static_cast<bool>(GetSP()); +} const char *SBUnixSignals::GetSignalAsCString(int32_t signo) const { + LLDB_RECORD_METHOD_CONST(const char *, SBUnixSignals, GetSignalAsCString, + (int32_t), signo); + if (auto signals_sp = GetSP()) return signals_sp->GetSignalAsCString(signo); @@ -56,6 +78,9 @@ } int32_t SBUnixSignals::GetSignalNumberFromName(const char *name) const { + LLDB_RECORD_METHOD_CONST(int32_t, SBUnixSignals, GetSignalNumberFromName, + (const char *), name); + if (auto signals_sp = GetSP()) return signals_sp->GetSignalNumberFromName(name); @@ -63,6 +88,9 @@ } bool SBUnixSignals::GetShouldSuppress(int32_t signo) const { + LLDB_RECORD_METHOD_CONST(bool, SBUnixSignals, GetShouldSuppress, (int32_t), + signo); + if (auto signals_sp = GetSP()) return signals_sp->GetShouldSuppress(signo); @@ -70,13 +98,10 @@ } bool SBUnixSignals::SetShouldSuppress(int32_t signo, bool value) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - auto signals_sp = GetSP(); + LLDB_RECORD_METHOD(bool, SBUnixSignals, SetShouldSuppress, (int32_t, bool), + signo, value); - if (log) { - log->Printf("SBUnixSignals(%p)::SetShouldSuppress (signo=%d, value=%d)", - static_cast<void *>(signals_sp.get()), signo, value); - } + auto signals_sp = GetSP(); if (signals_sp) return signals_sp->SetShouldSuppress(signo, value); @@ -85,6 +110,9 @@ } bool SBUnixSignals::GetShouldStop(int32_t signo) const { + LLDB_RECORD_METHOD_CONST(bool, SBUnixSignals, GetShouldStop, (int32_t), + signo); + if (auto signals_sp = GetSP()) return signals_sp->GetShouldStop(signo); @@ -92,13 +120,10 @@ } bool SBUnixSignals::SetShouldStop(int32_t signo, bool value) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - auto signals_sp = GetSP(); + LLDB_RECORD_METHOD(bool, SBUnixSignals, SetShouldStop, (int32_t, bool), signo, + value); - if (log) { - log->Printf("SBUnixSignals(%p)::SetShouldStop (signo=%d, value=%d)", - static_cast<void *>(signals_sp.get()), signo, value); - } + auto signals_sp = GetSP(); if (signals_sp) return signals_sp->SetShouldStop(signo, value); @@ -107,6 +132,9 @@ } bool SBUnixSignals::GetShouldNotify(int32_t signo) const { + LLDB_RECORD_METHOD_CONST(bool, SBUnixSignals, GetShouldNotify, (int32_t), + signo); + if (auto signals_sp = GetSP()) return signals_sp->GetShouldNotify(signo); @@ -114,13 +142,10 @@ } bool SBUnixSignals::SetShouldNotify(int32_t signo, bool value) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - auto signals_sp = GetSP(); + LLDB_RECORD_METHOD(bool, SBUnixSignals, SetShouldNotify, (int32_t, bool), + signo, value); - if (log) { - log->Printf("SBUnixSignals(%p)::SetShouldNotify (signo=%d, value=%d)", - static_cast<void *>(signals_sp.get()), signo, value); - } + auto signals_sp = GetSP(); if (signals_sp) return signals_sp->SetShouldNotify(signo, value); @@ -129,6 +154,8 @@ } int32_t SBUnixSignals::GetNumSignals() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(int32_t, SBUnixSignals, GetNumSignals); + if (auto signals_sp = GetSP()) return signals_sp->GetNumSignals(); @@ -136,8 +163,44 @@ } int32_t SBUnixSignals::GetSignalAtIndex(int32_t index) const { + LLDB_RECORD_METHOD_CONST(int32_t, SBUnixSignals, GetSignalAtIndex, (int32_t), + index); + if (auto signals_sp = GetSP()) return signals_sp->GetSignalAtIndex(index); return LLDB_INVALID_SIGNAL_NUMBER; } + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBUnixSignals>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBUnixSignals, ()); + LLDB_REGISTER_CONSTRUCTOR(SBUnixSignals, (const lldb::SBUnixSignals &)); + LLDB_REGISTER_METHOD( + const lldb::SBUnixSignals &, + SBUnixSignals, operator=,(const lldb::SBUnixSignals &)); + LLDB_REGISTER_METHOD(void, SBUnixSignals, Clear, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBUnixSignals, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBUnixSignals, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(const char *, SBUnixSignals, GetSignalAsCString, + (int32_t)); + LLDB_REGISTER_METHOD_CONST(int32_t, SBUnixSignals, GetSignalNumberFromName, + (const char *)); + LLDB_REGISTER_METHOD_CONST(bool, SBUnixSignals, GetShouldSuppress, + (int32_t)); + LLDB_REGISTER_METHOD(bool, SBUnixSignals, SetShouldSuppress, + (int32_t, bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBUnixSignals, GetShouldStop, (int32_t)); + LLDB_REGISTER_METHOD(bool, SBUnixSignals, SetShouldStop, (int32_t, bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBUnixSignals, GetShouldNotify, (int32_t)); + LLDB_REGISTER_METHOD(bool, SBUnixSignals, SetShouldNotify, (int32_t, bool)); + LLDB_REGISTER_METHOD_CONST(int32_t, SBUnixSignals, GetNumSignals, ()); + LLDB_REGISTER_METHOD_CONST(int32_t, SBUnixSignals, GetSignalAtIndex, + (int32_t)); +} + +} +}
diff --git a/src/llvm-project/lldb/source/API/SBValue.cpp b/src/llvm-project/lldb/source/API/SBValue.cpp index a61a2a1..83830076 100644 --- a/src/llvm-project/lldb/source/API/SBValue.cpp +++ b/src/llvm-project/lldb/source/API/SBValue.cpp
@@ -1,13 +1,13 @@ //===-- SBValue.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBDeclaration.h" #include "lldb/API/SBStream.h" @@ -36,7 +36,6 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Scalar.h" #include "lldb/Utility/Stream.h" @@ -47,6 +46,8 @@ #include "lldb/API/SBTarget.h" #include "lldb/API/SBThread.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -56,7 +57,7 @@ ValueImpl(lldb::ValueObjectSP in_valobj_sp, lldb::DynamicValueType use_dynamic, bool use_synthetic, - const char *name = NULL) + const char *name = nullptr) : m_valobj_sp(), m_use_dynamic(use_dynamic), m_use_synthetic(use_synthetic), m_name(name) { if (in_valobj_sp) { @@ -83,7 +84,7 @@ } bool IsValid() { - if (m_valobj_sp.get() == NULL) + if (m_valobj_sp.get() == nullptr) return false; else { // FIXME: This check is necessary but not sufficient. We for sure don't @@ -107,7 +108,6 @@ lldb::ValueObjectSP GetSP(Process::StopLocker &stop_locker, std::unique_lock<std::recursive_mutex> &lock, Status &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (!m_valobj_sp) { error.SetErrorString("invalid value object"); return m_valobj_sp; @@ -126,9 +126,6 @@ // 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. - if (log) - log->Printf("SBValue(%p)::GetSP() => error: process is running", - static_cast<void *>(value_sp.get())); error.SetErrorString("process must be stopped."); return ValueObjectSP(); } @@ -218,32 +215,55 @@ Status m_lock_error; }; -SBValue::SBValue() : m_opaque_sp() {} +SBValue::SBValue() : m_opaque_sp() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBValue); } -SBValue::SBValue(const lldb::ValueObjectSP &value_sp) { SetSP(value_sp); } +SBValue::SBValue(const lldb::ValueObjectSP &value_sp) { + LLDB_RECORD_CONSTRUCTOR(SBValue, (const lldb::ValueObjectSP &), value_sp); -SBValue::SBValue(const SBValue &rhs) { SetSP(rhs.m_opaque_sp); } + SetSP(value_sp); +} + +SBValue::SBValue(const SBValue &rhs) { + LLDB_RECORD_CONSTRUCTOR(SBValue, (const lldb::SBValue &), rhs); + + SetSP(rhs.m_opaque_sp); +} SBValue &SBValue::operator=(const SBValue &rhs) { + LLDB_RECORD_METHOD(lldb::SBValue &, + SBValue, operator=,(const lldb::SBValue &), rhs); + if (this != &rhs) { SetSP(rhs.m_opaque_sp); } - return *this; + return LLDB_RECORD_RESULT(*this); } SBValue::~SBValue() {} bool SBValue::IsValid() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, IsValid); + return this->operator bool(); +} +SBValue::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBValue, operator bool); + // 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() != NULL && m_opaque_sp->IsValid() && - m_opaque_sp->GetRootSP().get() != NULL; + return m_opaque_sp.get() != nullptr && m_opaque_sp->IsValid() && + m_opaque_sp->GetRootSP().get() != nullptr; } -void SBValue::Clear() { m_opaque_sp.reset(); } +void SBValue::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBValue, Clear); + + m_opaque_sp.reset(); +} SBError SBValue::GetError() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBValue, GetError); + SBError sb_error; ValueLocker locker; @@ -254,10 +274,12 @@ sb_error.SetErrorStringWithFormat("error: %s", locker.GetError().AsCString()); - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } user_id_t SBValue::GetID() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::user_id_t, SBValue, GetID); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) @@ -266,69 +288,46 @@ } const char *SBValue::GetName() { - const char *name = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetName); + + const char *name = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) name = value_sp->GetName().GetCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (name) - log->Printf("SBValue(%p)::GetName () => \"%s\"", - static_cast<void *>(value_sp.get()), name); - else - log->Printf("SBValue(%p)::GetName () => NULL", - static_cast<void *>(value_sp.get())); - } - return name; } const char *SBValue::GetTypeName() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *name = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetTypeName); + + const char *name = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { name = value_sp->GetQualifiedTypeName().GetCString(); } - if (log) { - if (name) - log->Printf("SBValue(%p)::GetTypeName () => \"%s\"", - static_cast<void *>(value_sp.get()), name); - else - log->Printf("SBValue(%p)::GetTypeName () => NULL", - static_cast<void *>(value_sp.get())); - } - return name; } const char *SBValue::GetDisplayTypeName() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *name = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetDisplayTypeName); + + const char *name = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { name = value_sp->GetDisplayTypeName().GetCString(); } - if (log) { - if (name) - log->Printf("SBValue(%p)::GetTypeName () => \"%s\"", - static_cast<void *>(value_sp.get()), name); - else - log->Printf("SBValue(%p)::GetTypeName () => NULL", - static_cast<void *>(value_sp.get())); - } - return name; } size_t SBValue::GetByteSize() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBValue, GetByteSize); + size_t result = 0; ValueLocker locker; @@ -337,15 +336,12 @@ result = value_sp->GetByteSize(); } - if (log) - log->Printf("SBValue(%p)::GetByteSize () => %" PRIu64, - static_cast<void *>(value_sp.get()), - static_cast<uint64_t>(result)); - return result; } bool SBValue::IsInScope() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, IsInScope); + bool result = false; ValueLocker locker; @@ -354,109 +350,51 @@ result = value_sp->IsInScope(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBValue(%p)::IsInScope () => %i", - static_cast<void *>(value_sp.get()), result); - return result; } const char *SBValue::GetValue() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetValue); - const char *cstr = NULL; + const char *cstr = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { cstr = value_sp->GetValueAsCString(); } - if (log) { - if (cstr) - log->Printf("SBValue(%p)::GetValue() => \"%s\"", - static_cast<void *>(value_sp.get()), cstr); - else - log->Printf("SBValue(%p)::GetValue() => NULL", - static_cast<void *>(value_sp.get())); - } return cstr; } ValueType SBValue::GetValueType() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::ValueType, SBValue, GetValueType); + ValueType result = eValueTypeInvalid; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) result = value_sp->GetValueType(); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - switch (result) { - case eValueTypeInvalid: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeInvalid", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeVariableGlobal: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableGlobal", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeVariableStatic: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableStatic", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeVariableArgument: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableArgument", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeVariableLocal: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableLocal", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeRegister: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeRegister", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeRegisterSet: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeRegisterSet", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeConstResult: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeConstResult", - static_cast<void *>(value_sp.get())); - break; - case eValueTypeVariableThreadLocal: - log->Printf( - "SBValue(%p)::GetValueType () => eValueTypeVariableThreadLocal", - static_cast<void *>(value_sp.get())); - break; - } - } return result; } const char *SBValue::GetObjectDescription() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *cstr = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetObjectDescription); + + const char *cstr = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { cstr = value_sp->GetObjectDescription(); } - if (log) { - if (cstr) - log->Printf("SBValue(%p)::GetObjectDescription() => \"%s\"", - static_cast<void *>(value_sp.get()), cstr); - else - log->Printf("SBValue(%p)::GetObjectDescription() => NULL", - static_cast<void *>(value_sp.get())); - } + return cstr; } const char *SBValue::GetTypeValidatorResult() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *cstr = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetTypeValidatorResult); + + const char *cstr = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { @@ -468,41 +406,28 @@ cstr = validation.second.c_str(); } } - if (log) { - if (cstr) - log->Printf("SBValue(%p)::GetTypeValidatorResult() => \"%s\"", - static_cast<void *>(value_sp.get()), cstr); - else - log->Printf("SBValue(%p)::GetTypeValidatorResult() => NULL", - static_cast<void *>(value_sp.get())); - } + return cstr; } SBType SBValue::GetType() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBType, SBValue, GetType); + SBType sb_type; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); TypeImplSP type_sp; if (value_sp) { - type_sp.reset(new TypeImpl(value_sp->GetTypeImpl())); + type_sp = std::make_shared<TypeImpl>(value_sp->GetTypeImpl()); sb_type.SetSP(type_sp); } - if (log) { - if (type_sp) - log->Printf("SBValue(%p)::GetType => SBType(%p)", - static_cast<void *>(value_sp.get()), - static_cast<void *>(type_sp.get())); - else - log->Printf("SBValue(%p)::GetType => NULL", - static_cast<void *>(value_sp.get())); - } - return sb_type; + + return LLDB_RECORD_RESULT(sb_type); } bool SBValue::GetValueDidChange() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, GetValueDidChange); + bool result = false; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -510,35 +435,29 @@ if (value_sp->UpdateValueIfNeeded(false)) result = value_sp->GetValueDidChange(); } - if (log) - log->Printf("SBValue(%p)::GetValueDidChange() => %i", - static_cast<void *>(value_sp.get()), result); return result; } const char *SBValue::GetSummary() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *cstr = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetSummary); + + const char *cstr = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { cstr = value_sp->GetSummaryAsCString(); } - if (log) { - if (cstr) - log->Printf("SBValue(%p)::GetSummary() => \"%s\"", - static_cast<void *>(value_sp.get()), cstr); - else - log->Printf("SBValue(%p)::GetSummary() => NULL", - static_cast<void *>(value_sp.get())); - } + return cstr; } const char *SBValue::GetSummary(lldb::SBStream &stream, lldb::SBTypeSummaryOptions &options) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(const char *, SBValue, GetSummary, + (lldb::SBStream &, lldb::SBTypeSummaryOptions &), stream, + options); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { @@ -547,61 +466,49 @@ stream.Printf("%s", buffer.c_str()); } const char *cstr = stream.GetData(); - if (log) { - if (cstr) - log->Printf("SBValue(%p)::GetSummary() => \"%s\"", - static_cast<void *>(value_sp.get()), cstr); - else - log->Printf("SBValue(%p)::GetSummary() => NULL", - static_cast<void *>(value_sp.get())); - } return cstr; } const char *SBValue::GetLocation() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const char *cstr = NULL; + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBValue, GetLocation); + + const char *cstr = nullptr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { cstr = value_sp->GetLocationAsCString(); } - if (log) { - if (cstr) - log->Printf("SBValue(%p)::GetLocation() => \"%s\"", - static_cast<void *>(value_sp.get()), cstr); - else - log->Printf("SBValue(%p)::GetLocation() => NULL", - static_cast<void *>(value_sp.get())); - } return cstr; } // Deprecated - use the one that takes an lldb::SBError bool SBValue::SetValueFromCString(const char *value_str) { + LLDB_RECORD_METHOD(bool, SBValue, SetValueFromCString, (const char *), + value_str); + lldb::SBError dummy; return SetValueFromCString(value_str, dummy); } bool SBValue::SetValueFromCString(const char *value_str, lldb::SBError &error) { + LLDB_RECORD_METHOD(bool, SBValue, SetValueFromCString, + (const char *, lldb::SBError &), value_str, error); + bool success = false; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (value_sp) { success = value_sp->SetValueFromCString(value_str, error.ref()); } else error.SetErrorStringWithFormat("Could not get value: %s", locker.GetError().AsCString()); - if (log) - log->Printf("SBValue(%p)::SetValueFromCString(\"%s\") => %i", - static_cast<void *>(value_sp.get()), value_str, success); - return success; } lldb::SBTypeFormat SBValue::GetTypeFormat() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeFormat, SBValue, GetTypeFormat); + lldb::SBTypeFormat format; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -612,10 +519,12 @@ format.SetSP(format_sp); } } - return format; + return LLDB_RECORD_RESULT(format); } lldb::SBTypeSummary SBValue::GetTypeSummary() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeSummary, SBValue, GetTypeSummary); + lldb::SBTypeSummary summary; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -626,10 +535,12 @@ summary.SetSP(summary_sp); } } - return summary; + return LLDB_RECORD_RESULT(summary); } lldb::SBTypeFilter SBValue::GetTypeFilter() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeFilter, SBValue, GetTypeFilter); + lldb::SBTypeFilter filter; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -644,11 +555,12 @@ } } } - return filter; + return LLDB_RECORD_RESULT(filter); } -#ifndef LLDB_DISABLE_PYTHON lldb::SBTypeSynthetic SBValue::GetTypeSynthetic() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeSynthetic, SBValue, GetTypeSynthetic); + lldb::SBTypeSynthetic synthetic; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -663,12 +575,15 @@ } } } - return synthetic; + return LLDB_RECORD_RESULT(synthetic); } -#endif lldb::SBValue SBValue::CreateChildAtOffset(const char *name, uint32_t offset, SBType type) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, CreateChildAtOffset, + (const char *, uint32_t, lldb::SBType), name, offset, + type); + lldb::SBValue sb_value; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -681,20 +596,12 @@ GetPreferDynamicValue(), GetPreferSyntheticValue(), name); } } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (new_value_sp) - log->Printf("SBValue(%p)::CreateChildAtOffset => \"%s\"", - static_cast<void *>(value_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf("SBValue(%p)::CreateChildAtOffset => NULL", - static_cast<void *>(value_sp.get())); - } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBValue::Cast(SBType type) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, Cast, (lldb::SBType), type); + lldb::SBValue sb_value; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -702,20 +609,27 @@ if (value_sp && type_sp) sb_value.SetSP(value_sp->Cast(type_sp->GetCompilerType(false)), GetPreferDynamicValue(), GetPreferSyntheticValue()); - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBValue::CreateValueFromExpression(const char *name, const char *expression) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, CreateValueFromExpression, + (const char *, const char *), name, expression); + SBExpressionOptions options; options.ref().SetKeepInMemory(true); - return CreateValueFromExpression(name, expression, options); + return LLDB_RECORD_RESULT( + CreateValueFromExpression(name, expression, options)); } lldb::SBValue SBValue::CreateValueFromExpression(const char *name, const char *expression, SBExpressionOptions &options) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, CreateValueFromExpression, + (const char *, const char *, lldb::SBExpressionOptions &), + name, expression, options); + lldb::SBValue sb_value; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -728,23 +642,16 @@ new_value_sp->SetName(ConstString(name)); } sb_value.SetSP(new_value_sp); - if (log) { - if (new_value_sp) - log->Printf("SBValue(%p)::CreateValueFromExpression(name=\"%s\", " - "expression=\"%s\") => SBValue (%p)", - static_cast<void *>(value_sp.get()), name, expression, - static_cast<void *>(new_value_sp.get())); - else - log->Printf("SBValue(%p)::CreateValueFromExpression(name=\"%s\", " - "expression=\"%s\") => NULL", - static_cast<void *>(value_sp.get()), name, expression); - } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBValue::CreateValueFromAddress(const char *name, lldb::addr_t address, SBType sb_type) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, CreateValueFromAddress, + (const char *, lldb::addr_t, lldb::SBType), name, address, + sb_type); + lldb::SBValue sb_value; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -757,21 +664,15 @@ exe_ctx, ast_type); } sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (new_value_sp) - log->Printf("SBValue(%p)::CreateValueFromAddress => \"%s\"", - static_cast<void *>(value_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf("SBValue(%p)::CreateValueFromAddress => NULL", - static_cast<void *>(value_sp.get())); - } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBValue::CreateValueFromData(const char *name, SBData data, SBType sb_type) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, CreateValueFromData, + (const char *, lldb::SBData, lldb::SBType), name, data, + sb_type); + lldb::SBValue sb_value; lldb::ValueObjectSP new_value_sp; ValueLocker locker; @@ -784,20 +685,12 @@ new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad); } sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (new_value_sp) - log->Printf("SBValue(%p)::CreateValueFromData => \"%s\"", - static_cast<void *>(value_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf("SBValue(%p)::CreateValueFromData => NULL", - static_cast<void *>(value_sp.get())); - } - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } SBValue SBValue::GetChildAtIndex(uint32_t idx) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, GetChildAtIndex, (uint32_t), idx); + const bool can_create_synthetic = false; lldb::DynamicValueType use_dynamic = eNoDynamicValues; TargetSP target_sp; @@ -807,14 +700,18 @@ if (target_sp) use_dynamic = target_sp->GetPreferDynamicValue(); - return GetChildAtIndex(idx, use_dynamic, can_create_synthetic); + return LLDB_RECORD_RESULT( + GetChildAtIndex(idx, use_dynamic, can_create_synthetic)); } SBValue SBValue::GetChildAtIndex(uint32_t idx, lldb::DynamicValueType use_dynamic, bool can_create_synthetic) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, GetChildAtIndex, + (uint32_t, lldb::DynamicValueType, bool), idx, use_dynamic, + can_create_synthetic); + lldb::ValueObjectSP child_sp; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -828,35 +725,27 @@ SBValue sb_value; sb_value.SetSP(child_sp, use_dynamic, GetPreferSyntheticValue()); - if (log) - log->Printf("SBValue(%p)::GetChildAtIndex (%u) => SBValue(%p)", - static_cast<void *>(value_sp.get()), idx, - static_cast<void *>(value_sp.get())); - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } uint32_t SBValue::GetIndexOfChildWithName(const char *name) { + LLDB_RECORD_METHOD(uint32_t, SBValue, GetIndexOfChildWithName, (const char *), + name); + uint32_t idx = UINT32_MAX; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { idx = value_sp->GetIndexOfChildWithName(ConstString(name)); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (idx == UINT32_MAX) - log->Printf( - "SBValue(%p)::GetIndexOfChildWithName (name=\"%s\") => NOT FOUND", - static_cast<void *>(value_sp.get()), name); - else - log->Printf("SBValue(%p)::GetIndexOfChildWithName (name=\"%s\") => %u", - static_cast<void *>(value_sp.get()), name, idx); - } return idx; } SBValue SBValue::GetChildMemberWithName(const char *name) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, GetChildMemberWithName, + (const char *), name); + lldb::DynamicValueType use_dynamic_value = eNoDynamicValues; TargetSP target_sp; if (m_opaque_sp) @@ -864,17 +753,19 @@ if (target_sp) use_dynamic_value = target_sp->GetPreferDynamicValue(); - return GetChildMemberWithName(name, use_dynamic_value); + return LLDB_RECORD_RESULT(GetChildMemberWithName(name, use_dynamic_value)); } SBValue SBValue::GetChildMemberWithName(const char *name, lldb::DynamicValueType use_dynamic_value) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, GetChildMemberWithName, + (const char *, lldb::DynamicValueType), name, + use_dynamic_value); + lldb::ValueObjectSP child_sp; const ConstString str_name(name); - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { @@ -884,26 +775,25 @@ SBValue sb_value; sb_value.SetSP(child_sp, use_dynamic_value, GetPreferSyntheticValue()); - if (log) - log->Printf( - "SBValue(%p)::GetChildMemberWithName (name=\"%s\") => SBValue(%p)", - static_cast<void *>(value_sp.get()), name, - static_cast<void *>(value_sp.get())); - - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::SBValue SBValue::GetDynamicValue(lldb::DynamicValueType use_dynamic) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, GetDynamicValue, + (lldb::DynamicValueType), 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; + return LLDB_RECORD_RESULT(value_sb); } lldb::SBValue SBValue::GetStaticValue() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValue, SBValue, GetStaticValue); + SBValue value_sb; if (IsValid()) { ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), @@ -911,42 +801,57 @@ m_opaque_sp->GetUseSynthetic())); value_sb.SetSP(proxy_sp); } - return value_sb; + return LLDB_RECORD_RESULT(value_sb); } lldb::SBValue SBValue::GetNonSyntheticValue() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValue, SBValue, GetNonSyntheticValue); + 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; + return LLDB_RECORD_RESULT(value_sb); } lldb::DynamicValueType SBValue::GetPreferDynamicValue() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::DynamicValueType, SBValue, + GetPreferDynamicValue); + if (!IsValid()) return eNoDynamicValues; return m_opaque_sp->GetUseDynamic(); } void SBValue::SetPreferDynamicValue(lldb::DynamicValueType use_dynamic) { + LLDB_RECORD_METHOD(void, SBValue, SetPreferDynamicValue, + (lldb::DynamicValueType), use_dynamic); + if (IsValid()) return m_opaque_sp->SetUseDynamic(use_dynamic); } bool SBValue::GetPreferSyntheticValue() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, GetPreferSyntheticValue); + if (!IsValid()) return false; return m_opaque_sp->GetUseSynthetic(); } void SBValue::SetPreferSyntheticValue(bool use_synthetic) { + LLDB_RECORD_METHOD(void, SBValue, SetPreferSyntheticValue, (bool), + use_synthetic); + if (IsValid()) return m_opaque_sp->SetUseSynthetic(use_synthetic); } bool SBValue::IsDynamic() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, IsDynamic); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) @@ -955,6 +860,8 @@ } bool SBValue::IsSynthetic() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, IsSynthetic); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) @@ -963,6 +870,8 @@ } bool SBValue::IsSyntheticChildrenGenerated() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, IsSyntheticChildrenGenerated); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) @@ -971,6 +880,8 @@ } void SBValue::SetSyntheticChildrenGenerated(bool is) { + LLDB_RECORD_METHOD(void, SBValue, SetSyntheticChildrenGenerated, (bool), is); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) @@ -978,7 +889,9 @@ } lldb::SBValue SBValue::GetValueForExpressionPath(const char *expr_path) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBValue, SBValue, GetValueForExpressionPath, + (const char *), expr_path); + lldb::ValueObjectSP child_sp; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -990,16 +903,13 @@ SBValue sb_value; sb_value.SetSP(child_sp, GetPreferDynamicValue(), GetPreferSyntheticValue()); - if (log) - log->Printf("SBValue(%p)::GetValueForExpressionPath (expr_path=\"%s\") => " - "SBValue(%p)", - static_cast<void *>(value_sp.get()), expr_path, - static_cast<void *>(value_sp.get())); - - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } int64_t SBValue::GetValueAsSigned(SBError &error, int64_t fail_value) { + LLDB_RECORD_METHOD(int64_t, SBValue, GetValueAsSigned, + (lldb::SBError &, int64_t), error, fail_value); + error.Clear(); ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1018,6 +928,9 @@ } uint64_t SBValue::GetValueAsUnsigned(SBError &error, uint64_t fail_value) { + LLDB_RECORD_METHOD(uint64_t, SBValue, GetValueAsUnsigned, + (lldb::SBError &, uint64_t), error, fail_value); + error.Clear(); ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1036,6 +949,8 @@ } int64_t SBValue::GetValueAsSigned(int64_t fail_value) { + LLDB_RECORD_METHOD(int64_t, SBValue, GetValueAsSigned, (int64_t), fail_value); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { @@ -1045,6 +960,9 @@ } uint64_t SBValue::GetValueAsUnsigned(uint64_t fail_value) { + LLDB_RECORD_METHOD(uint64_t, SBValue, GetValueAsUnsigned, (uint64_t), + fail_value); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { @@ -1054,52 +972,51 @@ } bool SBValue::MightHaveChildren() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, MightHaveChildren); + bool has_children = false; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) has_children = value_sp->MightHaveChildren(); - if (log) - log->Printf("SBValue(%p)::MightHaveChildren() => %i", - static_cast<void *>(value_sp.get()), has_children); return has_children; } bool SBValue::IsRuntimeSupportValue() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, IsRuntimeSupportValue); + bool is_support = false; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) is_support = value_sp->IsRuntimeSupportValue(); - if (log) - log->Printf("SBValue(%p)::IsRuntimeSupportValue() => %i", - static_cast<void *>(value_sp.get()), is_support); return is_support; } -uint32_t SBValue::GetNumChildren() { return GetNumChildren(UINT32_MAX); } +uint32_t SBValue::GetNumChildren() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBValue, GetNumChildren); + + return GetNumChildren(UINT32_MAX); +} uint32_t SBValue::GetNumChildren(uint32_t max) { + LLDB_RECORD_METHOD(uint32_t, SBValue, GetNumChildren, (uint32_t), max); + uint32_t num_children = 0; - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) num_children = value_sp->GetNumChildren(max); - if (log) - log->Printf("SBValue(%p)::GetNumChildren (%u) => %u", - static_cast<void *>(value_sp.get()), max, num_children); - return num_children; } SBValue SBValue::Dereference() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValue, SBValue, Dereference); + SBValue sb_value; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1107,104 +1024,77 @@ Status error; sb_value = value_sp->Dereference(error); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBValue(%p)::Dereference () => SBValue(%p)", - static_cast<void *>(value_sp.get()), - static_cast<void *>(value_sp.get())); - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } // Deprecated - please use GetType().IsPointerType() instead. -bool SBValue::TypeIsPointerType() { return GetType().IsPointerType(); } +bool SBValue::TypeIsPointerType() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBValue, TypeIsPointerType); + + return GetType().IsPointerType(); +} void *SBValue::GetOpaqueType() { + LLDB_RECORD_METHOD_NO_ARGS(void *, SBValue, GetOpaqueType); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) return value_sp->GetCompilerType().GetOpaqueQualType(); - return NULL; + return nullptr; } lldb::SBTarget SBValue::GetTarget() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTarget, SBValue, GetTarget); + SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { target_sp = m_opaque_sp->GetTargetSP(); sb_target.SetSP(target_sp); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (target_sp.get() == NULL) - log->Printf("SBValue(%p)::GetTarget () => NULL", - static_cast<void *>(m_opaque_sp.get())); - else - log->Printf("SBValue(%p)::GetTarget () => %p", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(target_sp.get())); - } - return sb_target; + + return LLDB_RECORD_RESULT(sb_target); } lldb::SBProcess SBValue::GetProcess() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBProcess, SBValue, GetProcess); + SBProcess sb_process; ProcessSP process_sp; if (m_opaque_sp) { process_sp = m_opaque_sp->GetProcessSP(); sb_process.SetSP(process_sp); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (process_sp.get() == NULL) - log->Printf("SBValue(%p)::GetProcess () => NULL", - static_cast<void *>(m_opaque_sp.get())); - else - log->Printf("SBValue(%p)::GetProcess () => %p", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(process_sp.get())); - } - return sb_process; + + return LLDB_RECORD_RESULT(sb_process); } lldb::SBThread SBValue::GetThread() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBThread, SBValue, GetThread); + SBThread sb_thread; ThreadSP thread_sp; if (m_opaque_sp) { thread_sp = m_opaque_sp->GetThreadSP(); sb_thread.SetThread(thread_sp); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (thread_sp.get() == NULL) - log->Printf("SBValue(%p)::GetThread () => NULL", - static_cast<void *>(m_opaque_sp.get())); - else - log->Printf("SBValue(%p)::GetThread () => %p", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(thread_sp.get())); - } - return sb_thread; + + return LLDB_RECORD_RESULT(sb_thread); } lldb::SBFrame SBValue::GetFrame() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFrame, SBValue, GetFrame); + SBFrame sb_frame; StackFrameSP frame_sp; if (m_opaque_sp) { frame_sp = m_opaque_sp->GetFrameSP(); sb_frame.SetFrameSP(frame_sp); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) { - if (frame_sp.get() == NULL) - log->Printf("SBValue(%p)::GetFrame () => NULL", - static_cast<void *>(m_opaque_sp.get())); - else - log->Printf("SBValue(%p)::GetFrame () => %p", - static_cast<void *>(m_opaque_sp.get()), - static_cast<void *>(frame_sp.get())); - } - return sb_frame; + + return LLDB_RECORD_RESULT(sb_frame); } lldb::ValueObjectSP SBValue::GetSP(ValueLocker &locker) const { @@ -1216,8 +1106,10 @@ } lldb::ValueObjectSP SBValue::GetSP() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::ValueObjectSP, SBValue, GetSP); + ValueLocker locker; - return GetSP(locker); + return LLDB_RECORD_RESULT(GetSP(locker)); } void SBValue::SetSP(ValueImplSP impl_sp) { m_opaque_sp = impl_sp; } @@ -1275,6 +1167,9 @@ } bool SBValue::GetExpressionPath(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBValue, GetExpressionPath, (lldb::SBStream &), + description); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { @@ -1286,6 +1181,9 @@ bool SBValue::GetExpressionPath(SBStream &description, bool qualify_cxx_base_classes) { + LLDB_RECORD_METHOD(bool, SBValue, GetExpressionPath, (lldb::SBStream &, bool), + description, qualify_cxx_base_classes); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { @@ -1295,7 +1193,86 @@ return false; } +lldb::SBValue SBValue::EvaluateExpression(const char *expr) const { + LLDB_RECORD_METHOD_CONST(lldb::SBValue, SBValue, EvaluateExpression, + (const char *), expr); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return LLDB_RECORD_RESULT(SBValue()); + + lldb::TargetSP target_sp = value_sp->GetTargetSP(); + if (!target_sp) + return LLDB_RECORD_RESULT(SBValue()); + + lldb::SBExpressionOptions options; + options.SetFetchDynamicValue(target_sp->GetPreferDynamicValue()); + options.SetUnwindOnError(true); + options.SetIgnoreBreakpoints(true); + + return LLDB_RECORD_RESULT(EvaluateExpression(expr, options, nullptr)); +} + +lldb::SBValue +SBValue::EvaluateExpression(const char *expr, + const SBExpressionOptions &options) const { + LLDB_RECORD_METHOD_CONST(lldb::SBValue, SBValue, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &), + expr, options); + + return LLDB_RECORD_RESULT(EvaluateExpression(expr, options, nullptr)); +} + +lldb::SBValue SBValue::EvaluateExpression(const char *expr, + const SBExpressionOptions &options, + const char *name) const { + LLDB_RECORD_METHOD_CONST( + lldb::SBValue, SBValue, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &, const char *), expr, + options, name); + + + if (!expr || expr[0] == '\0') { + return LLDB_RECORD_RESULT(SBValue()); + } + + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) { + return LLDB_RECORD_RESULT(SBValue()); + } + + lldb::TargetSP target_sp = value_sp->GetTargetSP(); + if (!target_sp) { + return LLDB_RECORD_RESULT(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 LLDB_RECORD_RESULT(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 LLDB_RECORD_RESULT(result); +} + bool SBValue::GetDescription(SBStream &description) { + LLDB_RECORD_METHOD(bool, SBValue, GetDescription, (lldb::SBStream &), + description); + Stream &strm = description.ref(); ValueLocker locker; @@ -1309,6 +1286,8 @@ } lldb::Format SBValue::GetFormat() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::Format, SBValue, GetFormat); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) @@ -1317,6 +1296,8 @@ } void SBValue::SetFormat(lldb::Format format) { + LLDB_RECORD_METHOD(void, SBValue, SetFormat, (lldb::Format), format); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) @@ -1324,6 +1305,8 @@ } lldb::SBValue SBValue::AddressOf() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValue, SBValue, AddressOf); + SBValue sb_value; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1332,16 +1315,13 @@ sb_value.SetSP(value_sp->AddressOf(error), GetPreferDynamicValue(), GetPreferSyntheticValue()); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBValue(%p)::AddressOf () => SBValue(%p)", - static_cast<void *>(value_sp.get()), - static_cast<void *>(value_sp.get())); - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } lldb::addr_t SBValue::GetLoadAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBValue, GetLoadAddress); + lldb::addr_t value = LLDB_INVALID_ADDRESS; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1365,15 +1345,13 @@ value = LLDB_INVALID_ADDRESS; } } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBValue(%p)::GetLoadAddress () => (%" PRIu64 ")", - static_cast<void *>(value_sp.get()), value); return value; } lldb::SBAddress SBValue::GetAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBAddress, SBValue, GetAddress); + Address addr; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1396,18 +1374,14 @@ } } } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBValue(%p)::GetAddress () => (%s,%" PRIu64 ")", - static_cast<void *>(value_sp.get()), - (addr.GetSection() ? addr.GetSection()->GetName().GetCString() - : "NULL"), - addr.GetOffset()); - return SBAddress(new Address(addr)); + + return LLDB_RECORD_RESULT(SBAddress(new Address(addr))); } lldb::SBData SBValue::GetPointeeData(uint32_t item_idx, uint32_t item_count) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(lldb::SBData, SBValue, GetPointeeData, + (uint32_t, uint32_t), item_idx, item_count); + lldb::SBData sb_data; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1420,16 +1394,13 @@ *sb_data = data_sp; } } - if (log) - log->Printf("SBValue(%p)::GetPointeeData (%d, %d) => SBData(%p)", - static_cast<void *>(value_sp.get()), item_idx, item_count, - static_cast<void *>(sb_data.get())); - return sb_data; + return LLDB_RECORD_RESULT(sb_data); } lldb::SBData SBValue::GetData() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBData, SBValue, GetData); + lldb::SBData sb_data; ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); @@ -1440,16 +1411,14 @@ if (error.Success()) *sb_data = data_sp; } - if (log) - log->Printf("SBValue(%p)::GetData () => SBData(%p)", - static_cast<void *>(value_sp.get()), - static_cast<void *>(sb_data.get())); - return sb_data; + return LLDB_RECORD_RESULT(sb_data); } bool SBValue::SetData(lldb::SBData &data, SBError &error) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD(bool, SBValue, SetData, (lldb::SBData &, lldb::SBError &), + data, error); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); bool ret = true; @@ -1458,10 +1427,6 @@ DataExtractor *data_extractor = data.get(); if (!data_extractor) { - if (log) - log->Printf("SBValue(%p)::SetData() => error: no data to set", - static_cast<void *>(value_sp.get())); - error.SetErrorString("No data to set"); ret = false; } else { @@ -1482,14 +1447,12 @@ ret = false; } - if (log) - log->Printf("SBValue(%p)::SetData (%p) => %s", - static_cast<void *>(value_sp.get()), - static_cast<void *>(data.get()), ret ? "true" : "false"); return ret; } lldb::SBDeclaration SBValue::GetDeclaration() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBDeclaration, SBValue, GetDeclaration); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); SBDeclaration decl_sb; @@ -1498,11 +1461,15 @@ if (value_sp->GetDeclaration(decl)) decl_sb.SetDeclaration(decl); } - return decl_sb; + return LLDB_RECORD_RESULT(decl_sb); } lldb::SBWatchpoint SBValue::Watch(bool resolve_location, bool read, bool write, SBError &error) { + LLDB_RECORD_METHOD(lldb::SBWatchpoint, SBValue, Watch, + (bool, bool, bool, lldb::SBError &), resolve_location, + read, write, error); + SBWatchpoint sb_watchpoint; // If the SBValue is not valid, there's no point in even trying to watch it. @@ -1512,18 +1479,18 @@ if (value_sp && target_sp) { // Read and Write cannot both be false. if (!read && !write) - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); // If the value is not in scope, don't try and watch and invalid value if (!IsInScope()) - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); addr_t addr = GetLoadAddress(); if (addr == LLDB_INVALID_ADDRESS) - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); size_t byte_size = GetByteSize(); if (byte_size == 0) - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); uint32_t watch_type = 0; if (read) @@ -1550,23 +1517,13 @@ } } } else if (target_sp) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBValue(%p)::Watch() => error getting SBValue: %s", - static_cast<void *>(value_sp.get()), - locker.GetError().AsCString()); - error.SetErrorStringWithFormat("could not get SBValue: %s", locker.GetError().AsCString()); } else { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBValue(%p)::Watch() => error getting SBValue: no target", - static_cast<void *>(value_sp.get())); error.SetErrorString("could not set watchpoint, a target is required"); } - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); } // FIXME: Remove this method impl (as well as the decl in .h) once it is no @@ -1574,24 +1531,160 @@ // Backward compatibility fix in the interim. lldb::SBWatchpoint SBValue::Watch(bool resolve_location, bool read, bool write) { + LLDB_RECORD_METHOD(lldb::SBWatchpoint, SBValue, Watch, (bool, bool, bool), + resolve_location, read, write); + SBError error; - return Watch(resolve_location, read, write, error); + return LLDB_RECORD_RESULT(Watch(resolve_location, read, write, error)); } lldb::SBWatchpoint SBValue::WatchPointee(bool resolve_location, bool read, bool write, SBError &error) { + LLDB_RECORD_METHOD(lldb::SBWatchpoint, SBValue, WatchPointee, + (bool, bool, bool, lldb::SBError &), resolve_location, + read, write, error); + SBWatchpoint sb_watchpoint; if (IsInScope() && GetType().IsPointerType()) sb_watchpoint = Dereference().Watch(resolve_location, read, write, error); - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); } lldb::SBValue SBValue::Persist() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValue, SBValue, Persist); + ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); SBValue persisted_sb; if (value_sp) { persisted_sb.SetSP(value_sp->Persist()); } - return persisted_sb; + return LLDB_RECORD_RESULT(persisted_sb); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBValue>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBValue, ()); + LLDB_REGISTER_CONSTRUCTOR(SBValue, (const lldb::ValueObjectSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBValue, (const lldb::SBValue &)); + LLDB_REGISTER_METHOD(lldb::SBValue &, + SBValue, operator=,(const lldb::SBValue &)); + LLDB_REGISTER_METHOD(bool, SBValue, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBValue, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBValue, Clear, ()); + LLDB_REGISTER_METHOD(lldb::SBError, SBValue, GetError, ()); + LLDB_REGISTER_METHOD(lldb::user_id_t, SBValue, GetID, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetName, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetTypeName, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetDisplayTypeName, ()); + LLDB_REGISTER_METHOD(size_t, SBValue, GetByteSize, ()); + LLDB_REGISTER_METHOD(bool, SBValue, IsInScope, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetValue, ()); + LLDB_REGISTER_METHOD(lldb::ValueType, SBValue, GetValueType, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetObjectDescription, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetTypeValidatorResult, ()); + LLDB_REGISTER_METHOD(lldb::SBType, SBValue, GetType, ()); + LLDB_REGISTER_METHOD(bool, SBValue, GetValueDidChange, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetSummary, ()); + LLDB_REGISTER_METHOD(const char *, SBValue, GetSummary, + (lldb::SBStream &, lldb::SBTypeSummaryOptions &)); + LLDB_REGISTER_METHOD(const char *, SBValue, GetLocation, ()); + LLDB_REGISTER_METHOD(bool, SBValue, SetValueFromCString, (const char *)); + LLDB_REGISTER_METHOD(bool, SBValue, SetValueFromCString, + (const char *, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBTypeFormat, SBValue, GetTypeFormat, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeSummary, SBValue, GetTypeSummary, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeFilter, SBValue, GetTypeFilter, ()); + LLDB_REGISTER_METHOD(lldb::SBTypeSynthetic, SBValue, GetTypeSynthetic, ()); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, CreateChildAtOffset, + (const char *, uint32_t, lldb::SBType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, Cast, (lldb::SBType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, CreateValueFromExpression, + (const char *, const char *)); + LLDB_REGISTER_METHOD( + lldb::SBValue, SBValue, CreateValueFromExpression, + (const char *, const char *, lldb::SBExpressionOptions &)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, CreateValueFromAddress, + (const char *, lldb::addr_t, lldb::SBType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, CreateValueFromData, + (const char *, lldb::SBData, lldb::SBType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetChildAtIndex, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetChildAtIndex, + (uint32_t, lldb::DynamicValueType, bool)); + LLDB_REGISTER_METHOD(uint32_t, SBValue, GetIndexOfChildWithName, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetChildMemberWithName, + (const char *)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetChildMemberWithName, + (const char *, lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetDynamicValue, + (lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetStaticValue, ()); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetNonSyntheticValue, ()); + LLDB_REGISTER_METHOD(lldb::DynamicValueType, SBValue, GetPreferDynamicValue, + ()); + LLDB_REGISTER_METHOD(void, SBValue, SetPreferDynamicValue, + (lldb::DynamicValueType)); + LLDB_REGISTER_METHOD(bool, SBValue, GetPreferSyntheticValue, ()); + LLDB_REGISTER_METHOD(void, SBValue, SetPreferSyntheticValue, (bool)); + LLDB_REGISTER_METHOD(bool, SBValue, IsDynamic, ()); + LLDB_REGISTER_METHOD(bool, SBValue, IsSynthetic, ()); + LLDB_REGISTER_METHOD(bool, SBValue, IsSyntheticChildrenGenerated, ()); + LLDB_REGISTER_METHOD(void, SBValue, SetSyntheticChildrenGenerated, (bool)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, GetValueForExpressionPath, + (const char *)); + LLDB_REGISTER_METHOD(int64_t, SBValue, GetValueAsSigned, + (lldb::SBError &, int64_t)); + LLDB_REGISTER_METHOD(uint64_t, SBValue, GetValueAsUnsigned, + (lldb::SBError &, uint64_t)); + LLDB_REGISTER_METHOD(int64_t, SBValue, GetValueAsSigned, (int64_t)); + LLDB_REGISTER_METHOD(uint64_t, SBValue, GetValueAsUnsigned, (uint64_t)); + LLDB_REGISTER_METHOD(bool, SBValue, MightHaveChildren, ()); + LLDB_REGISTER_METHOD(bool, SBValue, IsRuntimeSupportValue, ()); + LLDB_REGISTER_METHOD(uint32_t, SBValue, GetNumChildren, ()); + LLDB_REGISTER_METHOD(uint32_t, SBValue, GetNumChildren, (uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, Dereference, ()); + LLDB_REGISTER_METHOD(bool, SBValue, TypeIsPointerType, ()); + LLDB_REGISTER_METHOD(void *, SBValue, GetOpaqueType, ()); + LLDB_REGISTER_METHOD(lldb::SBTarget, SBValue, GetTarget, ()); + LLDB_REGISTER_METHOD(lldb::SBProcess, SBValue, GetProcess, ()); + LLDB_REGISTER_METHOD(lldb::SBThread, SBValue, GetThread, ()); + LLDB_REGISTER_METHOD(lldb::SBFrame, SBValue, GetFrame, ()); + LLDB_REGISTER_METHOD_CONST(lldb::ValueObjectSP, SBValue, GetSP, ()); + LLDB_REGISTER_METHOD(bool, SBValue, GetExpressionPath, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(bool, SBValue, GetExpressionPath, + (lldb::SBStream &, bool)); + LLDB_REGISTER_METHOD_CONST(lldb::SBValue, SBValue, EvaluateExpression, + (const char *)); + LLDB_REGISTER_METHOD_CONST( + lldb::SBValue, SBValue, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &)); + LLDB_REGISTER_METHOD_CONST( + lldb::SBValue, SBValue, EvaluateExpression, + (const char *, const lldb::SBExpressionOptions &, const char *)); + LLDB_REGISTER_METHOD(bool, SBValue, GetDescription, (lldb::SBStream &)); + LLDB_REGISTER_METHOD(lldb::Format, SBValue, GetFormat, ()); + LLDB_REGISTER_METHOD(void, SBValue, SetFormat, (lldb::Format)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, AddressOf, ()); + LLDB_REGISTER_METHOD(lldb::addr_t, SBValue, GetLoadAddress, ()); + LLDB_REGISTER_METHOD(lldb::SBAddress, SBValue, GetAddress, ()); + LLDB_REGISTER_METHOD(lldb::SBData, SBValue, GetPointeeData, + (uint32_t, uint32_t)); + LLDB_REGISTER_METHOD(lldb::SBData, SBValue, GetData, ()); + LLDB_REGISTER_METHOD(bool, SBValue, SetData, + (lldb::SBData &, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBDeclaration, SBValue, GetDeclaration, ()); + LLDB_REGISTER_METHOD(lldb::SBWatchpoint, SBValue, Watch, + (bool, bool, bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBWatchpoint, SBValue, Watch, + (bool, bool, bool)); + LLDB_REGISTER_METHOD(lldb::SBWatchpoint, SBValue, WatchPointee, + (bool, bool, bool, lldb::SBError &)); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValue, Persist, ()); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBValueList.cpp b/src/llvm-project/lldb/source/API/SBValueList.cpp index 82b464b..7e909df 100644 --- a/src/llvm-project/lldb/source/API/SBValueList.cpp +++ b/src/llvm-project/lldb/source/API/SBValueList.cpp
@@ -1,17 +1,16 @@ //===-- SBValueList.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBValue.h" #include "lldb/Core/ValueObjectList.h" -#include "lldb/Utility/Log.h" #include <vector> @@ -68,142 +67,165 @@ std::vector<lldb::SBValue> m_values; }; -SBValueList::SBValueList() : m_opaque_ap() {} - -SBValueList::SBValueList(const SBValueList &rhs) : m_opaque_ap() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (rhs.IsValid()) - m_opaque_ap.reset(new ValueListImpl(*rhs)); - - if (log) { - log->Printf( - "SBValueList::SBValueList (rhs.ap=%p) => this.ap = %p", - static_cast<void *>(rhs.IsValid() ? rhs.m_opaque_ap.get() : NULL), - static_cast<void *>(m_opaque_ap.get())); - } +SBValueList::SBValueList() : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBValueList); } -SBValueList::SBValueList(const ValueListImpl *lldb_object_ptr) : m_opaque_ap() { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); +SBValueList::SBValueList(const SBValueList &rhs) : m_opaque_up() { + LLDB_RECORD_CONSTRUCTOR(SBValueList, (const lldb::SBValueList &), rhs); + if (rhs.IsValid()) + m_opaque_up.reset(new ValueListImpl(*rhs)); +} + +SBValueList::SBValueList(const ValueListImpl *lldb_object_ptr) : m_opaque_up() { if (lldb_object_ptr) - m_opaque_ap.reset(new ValueListImpl(*lldb_object_ptr)); - - if (log) { - log->Printf("SBValueList::SBValueList (lldb_object_ptr=%p) => this.ap = %p", - static_cast<const void *>(lldb_object_ptr), - static_cast<void *>(m_opaque_ap.get())); - } + m_opaque_up.reset(new ValueListImpl(*lldb_object_ptr)); } SBValueList::~SBValueList() {} -bool SBValueList::IsValid() const { return (m_opaque_ap != NULL); } +bool SBValueList::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBValueList, IsValid); + return this->operator bool(); +} +SBValueList::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBValueList, operator bool); -void SBValueList::Clear() { m_opaque_ap.reset(); } + return (m_opaque_up != nullptr); +} + +void SBValueList::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBValueList, Clear); + + m_opaque_up.reset(); +} const SBValueList &SBValueList::operator=(const SBValueList &rhs) { + LLDB_RECORD_METHOD(const lldb::SBValueList &, + SBValueList, operator=,(const lldb::SBValueList &), rhs); + if (this != &rhs) { if (rhs.IsValid()) - m_opaque_ap.reset(new ValueListImpl(*rhs)); + m_opaque_up.reset(new ValueListImpl(*rhs)); else - m_opaque_ap.reset(); + m_opaque_up.reset(); } - return *this; + return LLDB_RECORD_RESULT(*this); } -ValueListImpl *SBValueList::operator->() { return m_opaque_ap.get(); } +ValueListImpl *SBValueList::operator->() { return m_opaque_up.get(); } -ValueListImpl &SBValueList::operator*() { return *m_opaque_ap; } +ValueListImpl &SBValueList::operator*() { return *m_opaque_up; } const ValueListImpl *SBValueList::operator->() const { - return m_opaque_ap.get(); + return m_opaque_up.get(); } -const ValueListImpl &SBValueList::operator*() const { return *m_opaque_ap; } +const ValueListImpl &SBValueList::operator*() const { return *m_opaque_up; } void SBValueList::Append(const SBValue &val_obj) { + LLDB_RECORD_METHOD(void, SBValueList, Append, (const lldb::SBValue &), + val_obj); + CreateIfNeeded(); - m_opaque_ap->Append(val_obj); + m_opaque_up->Append(val_obj); } void SBValueList::Append(lldb::ValueObjectSP &val_obj_sp) { if (val_obj_sp) { CreateIfNeeded(); - m_opaque_ap->Append(SBValue(val_obj_sp)); + m_opaque_up->Append(SBValue(val_obj_sp)); } } void SBValueList::Append(const lldb::SBValueList &value_list) { + LLDB_RECORD_METHOD(void, SBValueList, Append, (const lldb::SBValueList &), + value_list); + if (value_list.IsValid()) { CreateIfNeeded(); - m_opaque_ap->Append(*value_list); + m_opaque_up->Append(*value_list); } } SBValue SBValueList::GetValueAtIndex(uint32_t idx) const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_CONST(lldb::SBValue, SBValueList, GetValueAtIndex, + (uint32_t), idx); - // if (log) - // log->Printf ("SBValueList::GetValueAtIndex (uint32_t idx) idx = %d", - // idx); SBValue sb_value; - if (m_opaque_ap) - sb_value = m_opaque_ap->GetValueAtIndex(idx); + if (m_opaque_up) + sb_value = m_opaque_up->GetValueAtIndex(idx); - if (log) { - SBStream sstr; - sb_value.GetDescription(sstr); - log->Printf("SBValueList::GetValueAtIndex (this.ap=%p, idx=%d) => SBValue " - "(this.sp = %p, '%s')", - static_cast<void *>(m_opaque_ap.get()), idx, - static_cast<void *>(sb_value.GetSP().get()), sstr.GetData()); - } - - return sb_value; + return LLDB_RECORD_RESULT(sb_value); } uint32_t SBValueList::GetSize() const { - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - // if (log) - // log->Printf ("SBValueList::GetSize ()"); + LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBValueList, GetSize); uint32_t size = 0; - if (m_opaque_ap) - size = m_opaque_ap->GetSize(); - - if (log) - log->Printf("SBValueList::GetSize (this.ap=%p) => %d", - static_cast<void *>(m_opaque_ap.get()), size); + if (m_opaque_up) + size = m_opaque_up->GetSize(); return size; } void SBValueList::CreateIfNeeded() { - if (m_opaque_ap == NULL) - m_opaque_ap.reset(new ValueListImpl()); + if (m_opaque_up == nullptr) + m_opaque_up.reset(new ValueListImpl()); } SBValue SBValueList::FindValueObjectByUID(lldb::user_id_t uid) { + LLDB_RECORD_METHOD(lldb::SBValue, SBValueList, FindValueObjectByUID, + (lldb::user_id_t), uid); + SBValue sb_value; - if (m_opaque_ap) - sb_value = m_opaque_ap->FindValueByUID(uid); - return sb_value; + if (m_opaque_up) + sb_value = m_opaque_up->FindValueByUID(uid); + return LLDB_RECORD_RESULT(sb_value); } SBValue SBValueList::GetFirstValueByName(const char *name) const { + LLDB_RECORD_METHOD_CONST(lldb::SBValue, SBValueList, GetFirstValueByName, + (const char *), name); + SBValue sb_value; - if (m_opaque_ap) - sb_value = m_opaque_ap->GetFirstValueByName(name); - return sb_value; + if (m_opaque_up) + sb_value = m_opaque_up->GetFirstValueByName(name); + return LLDB_RECORD_RESULT(sb_value); } -void *SBValueList::opaque_ptr() { return m_opaque_ap.get(); } +void *SBValueList::opaque_ptr() { return m_opaque_up.get(); } ValueListImpl &SBValueList::ref() { CreateIfNeeded(); - return *m_opaque_ap; + return *m_opaque_up; +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBValueList>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBValueList, ()); + LLDB_REGISTER_CONSTRUCTOR(SBValueList, (const lldb::SBValueList &)); + LLDB_REGISTER_METHOD_CONST(bool, SBValueList, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBValueList, operator bool, ()); + LLDB_REGISTER_METHOD(void, SBValueList, Clear, ()); + LLDB_REGISTER_METHOD(const lldb::SBValueList &, + SBValueList, operator=,(const lldb::SBValueList &)); + LLDB_REGISTER_METHOD(void, SBValueList, Append, (const lldb::SBValue &)); + LLDB_REGISTER_METHOD(void, SBValueList, Append, + (const lldb::SBValueList &)); + LLDB_REGISTER_METHOD_CONST(lldb::SBValue, SBValueList, GetValueAtIndex, + (uint32_t)); + LLDB_REGISTER_METHOD_CONST(uint32_t, SBValueList, GetSize, ()); + LLDB_REGISTER_METHOD(lldb::SBValue, SBValueList, FindValueObjectByUID, + (lldb::user_id_t)); + LLDB_REGISTER_METHOD_CONST(lldb::SBValue, SBValueList, GetFirstValueByName, + (const char *)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBVariablesOptions.cpp b/src/llvm-project/lldb/source/API/SBVariablesOptions.cpp index 2651ce1..bf0197c 100644 --- a/src/llvm-project/lldb/source/API/SBVariablesOptions.cpp +++ b/src/llvm-project/lldb/source/API/SBVariablesOptions.cpp
@@ -1,14 +1,14 @@ //===-- SBVariablesOptions.cpp --------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBTarget.h" #include "lldb/Target/Target.h" @@ -81,98 +81,196 @@ }; SBVariablesOptions::SBVariablesOptions() - : m_opaque_ap(new VariablesOptionsImpl()) {} + : m_opaque_up(new VariablesOptionsImpl()) { + LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBVariablesOptions); +} SBVariablesOptions::SBVariablesOptions(const SBVariablesOptions &options) - : m_opaque_ap(new VariablesOptionsImpl(options.ref())) {} + : m_opaque_up(new VariablesOptionsImpl(options.ref())) { + LLDB_RECORD_CONSTRUCTOR(SBVariablesOptions, + (const lldb::SBVariablesOptions &), options); +} SBVariablesOptions &SBVariablesOptions:: operator=(const SBVariablesOptions &options) { - m_opaque_ap.reset(new VariablesOptionsImpl(options.ref())); - return *this; + LLDB_RECORD_METHOD( + lldb::SBVariablesOptions &, + SBVariablesOptions, operator=,(const lldb::SBVariablesOptions &), + options); + + m_opaque_up.reset(new VariablesOptionsImpl(options.ref())); + return LLDB_RECORD_RESULT(*this); } SBVariablesOptions::~SBVariablesOptions() = default; -bool SBVariablesOptions::IsValid() const { return m_opaque_ap != nullptr; } +bool SBVariablesOptions::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBVariablesOptions, IsValid); + return this->operator bool(); +} +SBVariablesOptions::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBVariablesOptions, operator bool); + + return m_opaque_up != nullptr; +} bool SBVariablesOptions::GetIncludeArguments() const { - return m_opaque_ap->GetIncludeArguments(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBVariablesOptions, + GetIncludeArguments); + + return m_opaque_up->GetIncludeArguments(); } void SBVariablesOptions::SetIncludeArguments(bool arguments) { - m_opaque_ap->SetIncludeArguments(arguments); + LLDB_RECORD_METHOD(void, SBVariablesOptions, SetIncludeArguments, (bool), + arguments); + + m_opaque_up->SetIncludeArguments(arguments); } bool SBVariablesOptions::GetIncludeRecognizedArguments( const lldb::SBTarget &target) const { - return m_opaque_ap->GetIncludeRecognizedArguments(target.GetSP()); + LLDB_RECORD_METHOD_CONST(bool, SBVariablesOptions, + GetIncludeRecognizedArguments, + (const lldb::SBTarget &), target); + + return m_opaque_up->GetIncludeRecognizedArguments(target.GetSP()); } void SBVariablesOptions::SetIncludeRecognizedArguments(bool arguments) { - m_opaque_ap->SetIncludeRecognizedArguments(arguments); + LLDB_RECORD_METHOD(void, SBVariablesOptions, SetIncludeRecognizedArguments, + (bool), arguments); + + m_opaque_up->SetIncludeRecognizedArguments(arguments); } bool SBVariablesOptions::GetIncludeLocals() const { - return m_opaque_ap->GetIncludeLocals(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBVariablesOptions, GetIncludeLocals); + + return m_opaque_up->GetIncludeLocals(); } void SBVariablesOptions::SetIncludeLocals(bool locals) { - m_opaque_ap->SetIncludeLocals(locals); + LLDB_RECORD_METHOD(void, SBVariablesOptions, SetIncludeLocals, (bool), + locals); + + m_opaque_up->SetIncludeLocals(locals); } bool SBVariablesOptions::GetIncludeStatics() const { - return m_opaque_ap->GetIncludeStatics(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBVariablesOptions, GetIncludeStatics); + + return m_opaque_up->GetIncludeStatics(); } void SBVariablesOptions::SetIncludeStatics(bool statics) { - m_opaque_ap->SetIncludeStatics(statics); + LLDB_RECORD_METHOD(void, SBVariablesOptions, SetIncludeStatics, (bool), + statics); + + m_opaque_up->SetIncludeStatics(statics); } bool SBVariablesOptions::GetInScopeOnly() const { - return m_opaque_ap->GetInScopeOnly(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBVariablesOptions, GetInScopeOnly); + + return m_opaque_up->GetInScopeOnly(); } void SBVariablesOptions::SetInScopeOnly(bool in_scope_only) { - m_opaque_ap->SetInScopeOnly(in_scope_only); + LLDB_RECORD_METHOD(void, SBVariablesOptions, SetInScopeOnly, (bool), + in_scope_only); + + m_opaque_up->SetInScopeOnly(in_scope_only); } bool SBVariablesOptions::GetIncludeRuntimeSupportValues() const { - return m_opaque_ap->GetIncludeRuntimeSupportValues(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBVariablesOptions, + GetIncludeRuntimeSupportValues); + + return m_opaque_up->GetIncludeRuntimeSupportValues(); } void SBVariablesOptions::SetIncludeRuntimeSupportValues( bool runtime_support_values) { - m_opaque_ap->SetIncludeRuntimeSupportValues(runtime_support_values); + LLDB_RECORD_METHOD(void, SBVariablesOptions, SetIncludeRuntimeSupportValues, + (bool), runtime_support_values); + + m_opaque_up->SetIncludeRuntimeSupportValues(runtime_support_values); } lldb::DynamicValueType SBVariablesOptions::GetUseDynamic() const { - return m_opaque_ap->GetUseDynamic(); + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::DynamicValueType, SBVariablesOptions, + GetUseDynamic); + + return m_opaque_up->GetUseDynamic(); } void SBVariablesOptions::SetUseDynamic(lldb::DynamicValueType dynamic) { - m_opaque_ap->SetUseDynamic(dynamic); + LLDB_RECORD_METHOD(void, SBVariablesOptions, SetUseDynamic, + (lldb::DynamicValueType), dynamic); + + m_opaque_up->SetUseDynamic(dynamic); } VariablesOptionsImpl *SBVariablesOptions::operator->() { - return m_opaque_ap.operator->(); + return m_opaque_up.operator->(); } const VariablesOptionsImpl *SBVariablesOptions::operator->() const { - return m_opaque_ap.operator->(); + return m_opaque_up.operator->(); } -VariablesOptionsImpl *SBVariablesOptions::get() { return m_opaque_ap.get(); } +VariablesOptionsImpl *SBVariablesOptions::get() { return m_opaque_up.get(); } -VariablesOptionsImpl &SBVariablesOptions::ref() { return *m_opaque_ap; } +VariablesOptionsImpl &SBVariablesOptions::ref() { return *m_opaque_up; } const VariablesOptionsImpl &SBVariablesOptions::ref() const { - return *m_opaque_ap; + return *m_opaque_up; } SBVariablesOptions::SBVariablesOptions(VariablesOptionsImpl *lldb_object_ptr) - : m_opaque_ap(std::move(lldb_object_ptr)) {} + : m_opaque_up(std::move(lldb_object_ptr)) {} void SBVariablesOptions::SetOptions(VariablesOptionsImpl *lldb_object_ptr) { - m_opaque_ap.reset(std::move(lldb_object_ptr)); + m_opaque_up.reset(std::move(lldb_object_ptr)); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBVariablesOptions>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBVariablesOptions, ()); + LLDB_REGISTER_CONSTRUCTOR(SBVariablesOptions, + (const lldb::SBVariablesOptions &)); + LLDB_REGISTER_METHOD( + lldb::SBVariablesOptions &, + SBVariablesOptions, operator=,(const lldb::SBVariablesOptions &)); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, operator bool, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, GetIncludeArguments, + ()); + LLDB_REGISTER_METHOD(void, SBVariablesOptions, SetIncludeArguments, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, + GetIncludeRecognizedArguments, + (const lldb::SBTarget &)); + LLDB_REGISTER_METHOD(void, SBVariablesOptions, + SetIncludeRecognizedArguments, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, GetIncludeLocals, ()); + LLDB_REGISTER_METHOD(void, SBVariablesOptions, SetIncludeLocals, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, GetIncludeStatics, ()); + LLDB_REGISTER_METHOD(void, SBVariablesOptions, SetIncludeStatics, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, GetInScopeOnly, ()); + LLDB_REGISTER_METHOD(void, SBVariablesOptions, SetInScopeOnly, (bool)); + LLDB_REGISTER_METHOD_CONST(bool, SBVariablesOptions, + GetIncludeRuntimeSupportValues, ()); + LLDB_REGISTER_METHOD(void, SBVariablesOptions, + SetIncludeRuntimeSupportValues, (bool)); + LLDB_REGISTER_METHOD_CONST(lldb::DynamicValueType, SBVariablesOptions, + GetUseDynamic, ()); + LLDB_REGISTER_METHOD(void, SBVariablesOptions, SetUseDynamic, + (lldb::DynamicValueType)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SBWatchpoint.cpp b/src/llvm-project/lldb/source/API/SBWatchpoint.cpp index b775537..d0a36b7 100644 --- a/src/llvm-project/lldb/source/API/SBWatchpoint.cpp +++ b/src/llvm-project/lldb/source/API/SBWatchpoint.cpp
@@ -1,13 +1,13 @@ //===-- SBWatchpoint.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SBReproducerPrivate.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBDefines.h" @@ -19,7 +19,6 @@ #include "lldb/Core/StreamFile.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" @@ -27,61 +26,78 @@ using namespace lldb; using namespace lldb_private; -SBWatchpoint::SBWatchpoint() {} +SBWatchpoint::SBWatchpoint() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBWatchpoint); } SBWatchpoint::SBWatchpoint(const lldb::WatchpointSP &wp_sp) : m_opaque_wp(wp_sp) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - - if (log) { - SBStream sstr; - GetDescription(sstr, lldb::eDescriptionLevelBrief); - LLDB_LOG(log, "watchpoint = {0} ({1})", wp_sp.get(), sstr.GetData()); - } + LLDB_RECORD_CONSTRUCTOR(SBWatchpoint, (const lldb::WatchpointSP &), wp_sp); } SBWatchpoint::SBWatchpoint(const SBWatchpoint &rhs) - : m_opaque_wp(rhs.m_opaque_wp) {} + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_RECORD_CONSTRUCTOR(SBWatchpoint, (const lldb::SBWatchpoint &), rhs); +} const SBWatchpoint &SBWatchpoint::operator=(const SBWatchpoint &rhs) { + LLDB_RECORD_METHOD(const lldb::SBWatchpoint &, + SBWatchpoint, operator=,(const lldb::SBWatchpoint &), rhs); + m_opaque_wp = rhs.m_opaque_wp; - return *this; + return LLDB_RECORD_RESULT(*this); } SBWatchpoint::~SBWatchpoint() {} watch_id_t SBWatchpoint::GetID() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + LLDB_RECORD_METHOD_NO_ARGS(lldb::watch_id_t, SBWatchpoint, GetID); + watch_id_t watch_id = LLDB_INVALID_WATCH_ID; lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) watch_id = watchpoint_sp->GetID(); - if (log) { - if (watch_id == LLDB_INVALID_WATCH_ID) - log->Printf("SBWatchpoint(%p)::GetID () => LLDB_INVALID_WATCH_ID", - static_cast<void *>(watchpoint_sp.get())); - else - log->Printf("SBWatchpoint(%p)::GetID () => %u", - static_cast<void *>(watchpoint_sp.get()), watch_id); - } - return watch_id; } -bool SBWatchpoint::IsValid() const { return bool(m_opaque_wp.lock()); } +bool SBWatchpoint::IsValid() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBWatchpoint, IsValid); + return this->operator bool(); +} +SBWatchpoint::operator bool() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBWatchpoint, operator bool); + + return bool(m_opaque_wp.lock()); +} + +bool SBWatchpoint::operator==(const SBWatchpoint &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBWatchpoint, operator==,(const SBWatchpoint &), rhs); + + return GetSP() == rhs.GetSP(); +} + +bool SBWatchpoint::operator!=(const SBWatchpoint &rhs) const { + LLDB_RECORD_METHOD_CONST( + bool, SBWatchpoint, operator!=,(const SBWatchpoint &), rhs); + + return !(*this == rhs); +} SBError SBWatchpoint::GetError() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBWatchpoint, GetError); + SBError sb_error; lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { sb_error.SetError(watchpoint_sp->GetError()); } - return sb_error; + return LLDB_RECORD_RESULT(sb_error); } int32_t SBWatchpoint::GetHardwareIndex() { + LLDB_RECORD_METHOD_NO_ARGS(int32_t, SBWatchpoint, GetHardwareIndex); + int32_t hw_index = -1; lldb::WatchpointSP watchpoint_sp(GetSP()); @@ -95,6 +111,8 @@ } addr_t SBWatchpoint::GetWatchAddress() { + LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBWatchpoint, GetWatchAddress); + addr_t ret_addr = LLDB_INVALID_ADDRESS; lldb::WatchpointSP watchpoint_sp(GetSP()); @@ -108,6 +126,8 @@ } size_t SBWatchpoint::GetWatchSize() { + LLDB_RECORD_METHOD_NO_ARGS(size_t, SBWatchpoint, GetWatchSize); + size_t watch_size = 0; lldb::WatchpointSP watchpoint_sp(GetSP()); @@ -121,6 +141,8 @@ } void SBWatchpoint::SetEnabled(bool enabled) { + LLDB_RECORD_METHOD(void, SBWatchpoint, SetEnabled, (bool), enabled); + lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { Target &target = watchpoint_sp->GetTarget(); @@ -139,6 +161,8 @@ } bool SBWatchpoint::IsEnabled() { + LLDB_RECORD_METHOD_NO_ARGS(bool, SBWatchpoint, IsEnabled); + lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -149,6 +173,8 @@ } uint32_t SBWatchpoint::GetHitCount() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBWatchpoint, GetHitCount); + uint32_t count = 0; lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { @@ -157,15 +183,12 @@ count = watchpoint_sp->GetHitCount(); } - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf("SBWatchpoint(%p)::GetHitCount () => %u", - static_cast<void *>(watchpoint_sp.get()), count); - return count; } uint32_t SBWatchpoint::GetIgnoreCount() { + LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBWatchpoint, GetIgnoreCount); + lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -176,6 +199,8 @@ } void SBWatchpoint::SetIgnoreCount(uint32_t n) { + LLDB_RECORD_METHOD(void, SBWatchpoint, SetIgnoreCount, (uint32_t), n); + lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -185,16 +210,21 @@ } const char *SBWatchpoint::GetCondition() { + LLDB_RECORD_METHOD_NO_ARGS(const char *, SBWatchpoint, GetCondition); + lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { std::lock_guard<std::recursive_mutex> guard( watchpoint_sp->GetTarget().GetAPIMutex()); return watchpoint_sp->GetConditionText(); } - return NULL; + return nullptr; } void SBWatchpoint::SetCondition(const char *condition) { + LLDB_RECORD_METHOD(void, SBWatchpoint, SetCondition, (const char *), + condition); + lldb::WatchpointSP watchpoint_sp(GetSP()); if (watchpoint_sp) { std::lock_guard<std::recursive_mutex> guard( @@ -205,6 +235,10 @@ bool SBWatchpoint::GetDescription(SBStream &description, DescriptionLevel level) { + LLDB_RECORD_METHOD(bool, SBWatchpoint, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel), description, + level); + Stream &strm = description.ref(); lldb::WatchpointSP watchpoint_sp(GetSP()); @@ -219,19 +253,39 @@ return true; } -void SBWatchpoint::Clear() { m_opaque_wp.reset(); } +void SBWatchpoint::Clear() { + LLDB_RECORD_METHOD_NO_ARGS(void, SBWatchpoint, Clear); -lldb::WatchpointSP SBWatchpoint::GetSP() const { return m_opaque_wp.lock(); } + m_opaque_wp.reset(); +} -void SBWatchpoint::SetSP(const lldb::WatchpointSP &sp) { m_opaque_wp = sp; } +lldb::WatchpointSP SBWatchpoint::GetSP() const { + LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::WatchpointSP, SBWatchpoint, GetSP); + + return LLDB_RECORD_RESULT(m_opaque_wp.lock()); +} + +void SBWatchpoint::SetSP(const lldb::WatchpointSP &sp) { + LLDB_RECORD_METHOD(void, SBWatchpoint, SetSP, (const lldb::WatchpointSP &), + sp); + + m_opaque_wp = sp; +} bool SBWatchpoint::EventIsWatchpointEvent(const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(bool, SBWatchpoint, EventIsWatchpointEvent, + (const lldb::SBEvent &), event); + return Watchpoint::WatchpointEventData::GetEventDataFromEvent(event.get()) != - NULL; + nullptr; } WatchpointEventType SBWatchpoint::GetWatchpointEventTypeFromEvent(const SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(lldb::WatchpointEventType, SBWatchpoint, + GetWatchpointEventTypeFromEvent, + (const lldb::SBEvent &), event); + if (event.IsValid()) return Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent( event.GetSP()); @@ -239,9 +293,60 @@ } SBWatchpoint SBWatchpoint::GetWatchpointFromEvent(const lldb::SBEvent &event) { + LLDB_RECORD_STATIC_METHOD(lldb::SBWatchpoint, SBWatchpoint, + GetWatchpointFromEvent, (const lldb::SBEvent &), + event); + SBWatchpoint sb_watchpoint; if (event.IsValid()) sb_watchpoint = Watchpoint::WatchpointEventData::GetWatchpointFromEvent(event.GetSP()); - return sb_watchpoint; + return LLDB_RECORD_RESULT(sb_watchpoint); +} + +namespace lldb_private { +namespace repro { + +template <> +void RegisterMethods<SBWatchpoint>(Registry &R) { + LLDB_REGISTER_CONSTRUCTOR(SBWatchpoint, ()); + LLDB_REGISTER_CONSTRUCTOR(SBWatchpoint, (const lldb::WatchpointSP &)); + LLDB_REGISTER_CONSTRUCTOR(SBWatchpoint, (const lldb::SBWatchpoint &)); + LLDB_REGISTER_METHOD(const lldb::SBWatchpoint &, + SBWatchpoint, operator=,(const lldb::SBWatchpoint &)); + LLDB_REGISTER_METHOD(lldb::watch_id_t, SBWatchpoint, GetID, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBWatchpoint, IsValid, ()); + LLDB_REGISTER_METHOD_CONST(bool, SBWatchpoint, operator bool, ()); + LLDB_REGISTER_METHOD_CONST( + bool, SBWatchpoint, operator==,(const lldb::SBWatchpoint &)); + LLDB_REGISTER_METHOD_CONST( + bool, SBWatchpoint, operator!=,(const lldb::SBWatchpoint &)); + LLDB_REGISTER_METHOD(lldb::SBError, SBWatchpoint, GetError, ()); + LLDB_REGISTER_METHOD(int32_t, SBWatchpoint, GetHardwareIndex, ()); + LLDB_REGISTER_METHOD(lldb::addr_t, SBWatchpoint, GetWatchAddress, ()); + LLDB_REGISTER_METHOD(size_t, SBWatchpoint, GetWatchSize, ()); + LLDB_REGISTER_METHOD(void, SBWatchpoint, SetEnabled, (bool)); + LLDB_REGISTER_METHOD(bool, SBWatchpoint, IsEnabled, ()); + LLDB_REGISTER_METHOD(uint32_t, SBWatchpoint, GetHitCount, ()); + LLDB_REGISTER_METHOD(uint32_t, SBWatchpoint, GetIgnoreCount, ()); + LLDB_REGISTER_METHOD(void, SBWatchpoint, SetIgnoreCount, (uint32_t)); + LLDB_REGISTER_METHOD(const char *, SBWatchpoint, GetCondition, ()); + LLDB_REGISTER_METHOD(void, SBWatchpoint, SetCondition, (const char *)); + LLDB_REGISTER_METHOD(bool, SBWatchpoint, GetDescription, + (lldb::SBStream &, lldb::DescriptionLevel)); + LLDB_REGISTER_METHOD(void, SBWatchpoint, Clear, ()); + LLDB_REGISTER_METHOD_CONST(lldb::WatchpointSP, SBWatchpoint, GetSP, ()); + LLDB_REGISTER_METHOD(void, SBWatchpoint, SetSP, + (const lldb::WatchpointSP &)); + LLDB_REGISTER_STATIC_METHOD(bool, SBWatchpoint, EventIsWatchpointEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::WatchpointEventType, SBWatchpoint, + GetWatchpointEventTypeFromEvent, + (const lldb::SBEvent &)); + LLDB_REGISTER_STATIC_METHOD(lldb::SBWatchpoint, SBWatchpoint, + GetWatchpointFromEvent, + (const lldb::SBEvent &)); +} + +} }
diff --git a/src/llvm-project/lldb/source/API/SystemInitializerFull.cpp b/src/llvm-project/lldb/source/API/SystemInitializerFull.cpp index fa10d3f..e7f2206 100644 --- a/src/llvm-project/lldb/source/API/SystemInitializerFull.cpp +++ b/src/llvm-project/lldb/source/API/SystemInitializerFull.cpp
@@ -1,16 +1,11 @@ //===-- SystemInitializerFull.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// -#if !defined(LLDB_DISABLE_PYTHON) -#include "Plugins/ScriptInterpreter/Python/lldb-python.h" -#endif - #include "SystemInitializerFull.h" #include "lldb/API/SBCommandInterpreter.h" @@ -24,7 +19,6 @@ #include "lldb/Initialization/SystemInitializerCommon.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Symbol/ClangASTContext.h" -#include "lldb/Symbol/RustASTContext.h" #include "lldb/Utility/Timer.h" #include "Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h" @@ -40,6 +34,7 @@ #include "Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h" #include "Plugins/ABI/SysV-s390x/ABISysV_s390x.h" #include "Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h" +#include "Plugins/ABI/Windows-x86_64/ABIWindows_x86_64.h" #include "Plugins/Architecture/Arm/ArchitectureArm.h" #include "Plugins/Architecture/Mips/ArchitectureMips.h" #include "Plugins/Architecture/PPC64/ArchitecturePPC64.h" @@ -49,7 +44,10 @@ #include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h" #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h" #include "Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h" +#include "Plugins/Instruction/ARM/EmulateInstructionARM.h" #include "Plugins/Instruction/ARM64/EmulateInstructionARM64.h" +#include "Plugins/Instruction/MIPS/EmulateInstructionMIPS.h" +#include "Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h" #include "Plugins/Instruction/PPC64/EmulateInstructionPPC64.h" #include "Plugins/InstrumentationRuntime/ASan/ASanRuntime.h" #include "Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h" @@ -59,13 +57,13 @@ #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" #include "Plugins/Language/ObjC/ObjCLanguage.h" #include "Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.h" -#include "Plugins/Language/Rust/RustLanguage.h" #include "Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h" #include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h" #include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h" #include "Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h" -#include "Plugins/LanguageRuntime/Rust/RustLanguageRuntime.h" #include "Plugins/MemoryHistory/asan/MemoryHistoryASan.h" +#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h" +#include "Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h" #include "Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h" #include "Plugins/ObjectFile/ELF/ObjectFileELF.h" #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h" @@ -73,7 +71,6 @@ #include "Plugins/OperatingSystem/Python/OperatingSystemPython.h" #include "Plugins/Platform/Android/PlatformAndroid.h" #include "Plugins/Platform/FreeBSD/PlatformFreeBSD.h" -#include "Plugins/Platform/Kalimba/PlatformKalimba.h" #include "Plugins/Platform/Linux/PlatformLinux.h" #include "Plugins/Platform/MacOSX/PlatformMacOSX.h" #include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h" @@ -101,9 +98,9 @@ #include "Plugins/Platform/MacOSX/PlatformAppleTVSimulator.h" #include "Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.h" #include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h" +#include "Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.h" #include "Plugins/Platform/MacOSX/PlatformRemoteAppleTV.h" #include "Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.h" -#include "Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.h" #include "Plugins/Platform/MacOSX/PlatformiOSSimulator.h" #include "Plugins/Process/MacOSX-Kernel/ProcessKDP.h" #include "Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h" @@ -121,157 +118,21 @@ #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> using namespace lldb_private; -#ifndef LLDB_DISABLE_PYTHON - -// Defined in the SWIG source file -#if PY_MAJOR_VERSION >= 3 -extern "C" PyObject *PyInit__lldb(void); - -#define LLDBSwigPyInit PyInit__lldb - -#else -extern "C" void init_lldb(void); - -#define LLDBSwigPyInit init_lldb -#endif - -// these are the Pythonic implementations of the required callbacks these are -// scripting-language specific, which is why they belong here we still need to -// use function pointers to them instead of relying on linkage-time resolution -// because the SWIG stuff and this file get built at different times -extern "C" bool LLDBSwigPythonBreakpointCallbackFunction( - const char *python_function_name, const char *session_dictionary_name, - const lldb::StackFrameSP &sb_frame, - const lldb::BreakpointLocationSP &sb_bp_loc); - -extern "C" bool LLDBSwigPythonWatchpointCallbackFunction( - const char *python_function_name, const char *session_dictionary_name, - const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp); - -extern "C" bool LLDBSwigPythonCallTypeScript( - const char *python_function_name, void *session_dictionary, - const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, - const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval); - -extern "C" void * -LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, - const char *session_dictionary_name, - const lldb::ValueObjectSP &valobj_sp); - -extern "C" void * -LLDBSwigPythonCreateCommandObject(const char *python_class_name, - const char *session_dictionary_name, - const lldb::DebuggerSP debugger_sp); - -extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan( - const char *python_class_name, const char *session_dictionary_name, - const lldb::ThreadPlanSP &thread_plan_sp); - -extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor, - const char *method_name, - Event *event_sp, bool &got_error); - -extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver( - const char *python_class_name, - const char *session_dictionary_name, - lldb_private::StructuredDataImpl *args, - lldb::BreakpointSP &bkpt_sp); - -extern "C" unsigned int LLDBSwigPythonCallBreakpointResolver( - void *implementor, - const char *method_name, - lldb_private::SymbolContext *sym_ctx -); - -extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor, - uint32_t max); - -extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor, - uint32_t idx); - -extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor, - const char *child_name); - -extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data); - -extern lldb::ValueObjectSP -LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data); - -extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor); - -extern "C" bool -LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor); - -extern "C" void * -LLDBSwigPython_GetValueSynthProviderInstance(void *implementor); - -extern "C" bool -LLDBSwigPythonCallCommand(const char *python_function_name, - const char *session_dictionary_name, - lldb::DebuggerSP &debugger, const char *args, - lldb_private::CommandReturnObject &cmd_retobj, - lldb::ExecutionContextRefSP exe_ctx_ref_sp); - -extern "C" bool -LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger, - const char *args, - lldb_private::CommandReturnObject &cmd_retobj, - lldb::ExecutionContextRefSP exe_ctx_ref_sp); - -extern "C" bool -LLDBSwigPythonCallModuleInit(const char *python_module_name, - const char *session_dictionary_name, - lldb::DebuggerSP &debugger); - -extern "C" void * -LLDBSWIGPythonCreateOSPlugin(const char *python_class_name, - const char *session_dictionary_name, - const lldb::ProcessSP &process_sp); - -extern "C" void *LLDBSWIGPython_CreateFrameRecognizer( - const char *python_class_name, - const char *session_dictionary_name); - -extern "C" void *LLDBSwigPython_GetRecognizedArguments(void *implementor, - const lldb::StackFrameSP& frame_sp); - -extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess( - const char *python_function_name, const char *session_dictionary_name, - lldb::ProcessSP &process, std::string &output); - -extern "C" bool LLDBSWIGPythonRunScriptKeywordThread( - const char *python_function_name, const char *session_dictionary_name, - lldb::ThreadSP &thread, std::string &output); - -extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget( - const char *python_function_name, const char *session_dictionary_name, - lldb::TargetSP &target, std::string &output); - -extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame( - const char *python_function_name, const char *session_dictionary_name, - lldb::StackFrameSP &frame, std::string &output); - -extern "C" bool LLDBSWIGPythonRunScriptKeywordValue( - const char *python_function_name, const char *session_dictionary_name, - lldb::ValueObjectSP &value, std::string &output); - -extern "C" void * -LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, - const lldb::TargetSP &target_sp); - -#endif - SystemInitializerFull::SystemInitializerFull() {} SystemInitializerFull::~SystemInitializerFull() {} -llvm::Error -SystemInitializerFull::Initialize(const InitializerOptions &options) { - if (auto e = SystemInitializerCommon::Initialize(options)) +llvm::Error SystemInitializerFull::Initialize() { + if (auto e = SystemInitializerCommon::Initialize()) return e; breakpad::ObjectFileBreakpad::Initialize(); @@ -279,6 +140,9 @@ ObjectFileMachO::Initialize(); ObjectFilePECOFF::Initialize(); + ObjectContainerBSDArchive::Initialize(); + ObjectContainerUniversalMachO::Initialize(); + ScriptInterpreterNone::Initialize(); #ifndef LLDB_DISABLE_PYTHON @@ -286,11 +150,6 @@ #endif #if !defined(LLDB_DISABLE_PYTHON) - InitializeSWIG(); - - // ScriptInterpreterPython::Initialize() depends on things like HostInfo - // being initialized so it can compute the python directory etc, so we need - // to do this after SystemInitializerCommon::Initialize(). ScriptInterpreterPython::Initialize(); #endif @@ -299,7 +158,6 @@ platform_netbsd::PlatformNetBSD::Initialize(); platform_openbsd::PlatformOpenBSD::Initialize(); PlatformWindows::Initialize(); - PlatformKalimba::Initialize(); platform_android::PlatformAndroid::Initialize(); PlatformRemoteiOS::Initialize(); PlatformMacOSX::Initialize(); @@ -315,7 +173,6 @@ llvm::InitializeAllDisassemblers(); ClangASTContext::Initialize(); - RustASTContext::Initialize(); ABIMacOSX_i386::Initialize(); ABIMacOSX_arm::Initialize(); @@ -330,6 +187,7 @@ ABISysV_mips::Initialize(); ABISysV_mips64::Initialize(); ABISysV_s390x::Initialize(); + ABIWindows_x86_64::Initialize(); ArchitectureArm::Initialize(); ArchitectureMips::Initialize(); @@ -354,20 +212,23 @@ SymbolFileSymtab::Initialize(); UnwindAssemblyInstEmulation::Initialize(); UnwindAssembly_x86::Initialize(); + + EmulateInstructionARM::Initialize(); EmulateInstructionARM64::Initialize(); + EmulateInstructionMIPS::Initialize(); + EmulateInstructionMIPS64::Initialize(); EmulateInstructionPPC64::Initialize(); + SymbolFileDWARFDebugMap::Initialize(); ItaniumABILanguageRuntime::Initialize(); AppleObjCRuntimeV2::Initialize(); AppleObjCRuntimeV1::Initialize(); SystemRuntimeMacOSX::Initialize(); RenderScriptRuntime::Initialize(); - RustLanguageRuntime::Initialize(); CPlusPlusLanguage::Initialize(); ObjCLanguage::Initialize(); ObjCPlusPlusLanguage::Initialize(); - RustLanguage::Initialize(); #if defined(_WIN32) ProcessWindows::Initialize(); @@ -390,9 +251,7 @@ // shouldn't be limited to __APPLE__. StructuredDataDarwinLog::Initialize(); - //---------------------------------------------------------------------- // Platform agnostic plugins - //---------------------------------------------------------------------- platform_gdb_server::PlatformRemoteGDBServer::Initialize(); process_gdb_remote::ProcessGDBRemote::Initialize(); @@ -414,31 +273,6 @@ return llvm::Error::success(); } -void SystemInitializerFull::InitializeSWIG() { -#if !defined(LLDB_DISABLE_PYTHON) - ScriptInterpreterPython::InitializeInterpreter( - LLDBSwigPyInit, LLDBSwigPythonBreakpointCallbackFunction, - LLDBSwigPythonWatchpointCallbackFunction, LLDBSwigPythonCallTypeScript, - LLDBSwigPythonCreateSyntheticProvider, LLDBSwigPythonCreateCommandObject, - LLDBSwigPython_CalculateNumChildren, LLDBSwigPython_GetChildAtIndex, - LLDBSwigPython_GetIndexOfChildWithName, - LLDBSWIGPython_CastPyObjectToSBValue, - LLDBSWIGPython_GetValueObjectSPFromSBValue, - LLDBSwigPython_UpdateSynthProviderInstance, - LLDBSwigPython_MightHaveChildrenSynthProviderInstance, - LLDBSwigPython_GetValueSynthProviderInstance, LLDBSwigPythonCallCommand, - LLDBSwigPythonCallCommandObject, LLDBSwigPythonCallModuleInit, - LLDBSWIGPythonCreateOSPlugin, LLDBSWIGPython_CreateFrameRecognizer, - LLDBSwigPython_GetRecognizedArguments, - LLDBSWIGPythonRunScriptKeywordProcess, - LLDBSWIGPythonRunScriptKeywordThread, - LLDBSWIGPythonRunScriptKeywordTarget, LLDBSWIGPythonRunScriptKeywordFrame, - LLDBSWIGPythonRunScriptKeywordValue, LLDBSWIGPython_GetDynamicSetting, - LLDBSwigPythonCreateScriptedThreadPlan, LLDBSWIGPythonCallThreadPlan, - LLDBSwigPythonCreateScriptedBreakpointResolver, LLDBSwigPythonCallBreakpointResolver); -#endif -} - void SystemInitializerFull::Terminate() { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); @@ -449,7 +283,6 @@ PluginManager::Terminate(); ClangASTContext::Terminate(); - RustASTContext::Terminate(); ArchitectureArm::Terminate(); ArchitectureMips::Terminate(); @@ -468,6 +301,7 @@ ABISysV_mips::Terminate(); ABISysV_mips64::Terminate(); ABISysV_s390x::Terminate(); + ABIWindows_x86_64::Terminate(); DisassemblerLLVMC::Terminate(); JITLoaderGDB::Terminate(); @@ -486,20 +320,23 @@ SymbolFileSymtab::Terminate(); UnwindAssembly_x86::Terminate(); UnwindAssemblyInstEmulation::Terminate(); + + EmulateInstructionARM::Terminate(); EmulateInstructionARM64::Terminate(); + EmulateInstructionMIPS::Terminate(); + EmulateInstructionMIPS64::Terminate(); EmulateInstructionPPC64::Terminate(); + SymbolFileDWARFDebugMap::Terminate(); ItaniumABILanguageRuntime::Terminate(); AppleObjCRuntimeV2::Terminate(); AppleObjCRuntimeV1::Terminate(); SystemRuntimeMacOSX::Terminate(); RenderScriptRuntime::Terminate(); - RustLanguageRuntime::Terminate(); CPlusPlusLanguage::Terminate(); ObjCLanguage::Terminate(); ObjCPlusPlusLanguage::Terminate(); - RustLanguage::Terminate(); #if defined(__APPLE__) DynamicLoaderDarwinKernel::Terminate(); @@ -536,7 +373,6 @@ platform_netbsd::PlatformNetBSD::Terminate(); platform_openbsd::PlatformOpenBSD::Terminate(); PlatformWindows::Terminate(); - PlatformKalimba::Terminate(); platform_android::PlatformAndroid::Terminate(); PlatformMacOSX::Terminate(); PlatformRemoteiOS::Terminate(); @@ -550,6 +386,9 @@ ObjectFileMachO::Terminate(); ObjectFilePECOFF::Terminate(); + ObjectContainerBSDArchive::Terminate(); + ObjectContainerUniversalMachO::Terminate(); + // Now shutdown the common parts, in reverse order. SystemInitializerCommon::Terminate(); }
diff --git a/src/llvm-project/lldb/source/API/SystemInitializerFull.h b/src/llvm-project/lldb/source/API/SystemInitializerFull.h index b0cf476..cd88bae 100644 --- a/src/llvm-project/lldb/source/API/SystemInitializerFull.h +++ b/src/llvm-project/lldb/source/API/SystemInitializerFull.h
@@ -1,9 +1,8 @@ //===-- SystemInitializerFull.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,24 +12,19 @@ #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(const InitializerOptions &options) override; + llvm::Error Initialize() override; void Terminate() override; - -private: - void InitializeSWIG(); }; } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/API/Utils.h b/src/llvm-project/lldb/source/API/Utils.h new file mode 100644 index 0000000..b1975e5 --- /dev/null +++ b/src/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_API_UTILS_H +#define LLDB_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 llvm::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/src/llvm-project/lldb/source/Breakpoint/Breakpoint.cpp b/src/llvm-project/lldb/source/Breakpoint/Breakpoint.cpp index 131d2a7..3c38419 100644 --- a/src/llvm-project/lldb/source/Breakpoint/Breakpoint.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/Breakpoint.cpp
@@ -1,9 +1,8 @@ //===-- Breakpoint.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,6 +11,7 @@ #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/BreakpointLocationCollection.h" +#include "lldb/Breakpoint/BreakpointPrecondition.h" #include "lldb/Breakpoint/BreakpointResolver.h" #include "lldb/Breakpoint/BreakpointResolverFileLine.h" #include "lldb/Core/Address.h" @@ -30,11 +30,13 @@ #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" +#include <memory> + using namespace lldb; using namespace lldb_private; using namespace llvm; -const ConstString &Breakpoint::GetEventIdentifier() { +ConstString Breakpoint::GetEventIdentifier() { static ConstString g_identifier("event-identifier.breakpoint.changed"); return g_identifier; } @@ -42,9 +44,7 @@ const char *Breakpoint::g_option_names[static_cast<uint32_t>( Breakpoint::OptionNames::LastOptionName)]{"Names", "Hardware"}; -//---------------------------------------------------------------------- // Breakpoint constructor -//---------------------------------------------------------------------- Breakpoint::Breakpoint(Target &target, SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool hardware, bool resolve_indirect_symbols) @@ -58,7 +58,7 @@ Breakpoint::Breakpoint(Target &new_target, Breakpoint &source_bp) : m_being_created(true), m_hardware(source_bp.m_hardware), m_target(new_target), m_name_list(source_bp.m_name_list), - m_options_up(new BreakpointOptions(*source_bp.m_options_up.get())), + m_options_up(new BreakpointOptions(*source_bp.m_options_up)), m_locations(*this), m_resolve_indirect_symbols(source_bp.m_resolve_indirect_symbols), m_hit_count(0) { @@ -67,14 +67,10 @@ m_filter_sp = source_bp.m_filter_sp->CopyForBreakpoint(*this); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- Breakpoint::~Breakpoint() = default; -//---------------------------------------------------------------------- // Serialization -//---------------------------------------------------------------------- StructuredData::ObjectSP Breakpoint::SerializeToStructuredData() { // Serialize the resolver: StructuredData::DictionarySP breakpoint_dict_sp( @@ -159,8 +155,8 @@ SearchFilter::GetSerializationKey(), filter_dict); SearchFilterSP filter_sp; if (!success) - filter_sp.reset( - new SearchFilterForUnconstrainedSearches(target.shared_from_this())); + filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>( + target.shared_from_this()); else { filter_sp = SearchFilter::CreateFromStructuredData(target, *filter_dict, create_error); @@ -495,9 +491,7 @@ m_locations.ClearAllBreakpointSites(); } -//---------------------------------------------------------------------- // ModulesChanged: Pass in a list of new modules, and -//---------------------------------------------------------------------- void Breakpoint::ModulesChanged(ModuleList &module_list, bool load, bool delete_locations) { @@ -971,7 +965,7 @@ m_resolver_sp->GetDescription(s); } -bool Breakpoint::GetMatchingFileLine(const ConstString &filename, +bool Breakpoint::GetMatchingFileLine(ConstString filename, uint32_t line_number, BreakpointLocationCollection &loc_coll) { // TODO: To be correct, this method needs to fill the breakpoint location @@ -1002,21 +996,6 @@ return m_precondition_sp->EvaluatePrecondition(context); } -bool Breakpoint::BreakpointPrecondition::EvaluatePrecondition( - StoppointCallbackContext &context) { - return true; -} - -void Breakpoint::BreakpointPrecondition::GetDescription( - Stream &stream, lldb::DescriptionLevel level) {} - -Status -Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) { - Status error; - error.SetErrorString("Base breakpoint precondition has no options."); - return error; -} - void Breakpoint::SendBreakpointChangedEvent( lldb::BreakpointEventType eventKind) { if (!m_being_created && !IsInternal() && @@ -1047,12 +1026,12 @@ Breakpoint::BreakpointEventData::~BreakpointEventData() = default; -const ConstString &Breakpoint::BreakpointEventData::GetFlavorString() { +ConstString Breakpoint::BreakpointEventData::GetFlavorString() { static ConstString g_flavor("Breakpoint::BreakpointEventData"); return g_flavor; } -const ConstString &Breakpoint::BreakpointEventData::GetFlavor() const { +ConstString Breakpoint::BreakpointEventData::GetFlavor() const { return BreakpointEventData::GetFlavorString(); }
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointID.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointID.cpp index eb12e09..dc2e57c 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointID.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointID.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointID.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointIDList.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointIDList.cpp index b86f276..1e695fa 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointIDList.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointIDList.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointIDList.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // class BreakpointIDList -//---------------------------------------------------------------------- BreakpointIDList::BreakpointIDList() : m_invalid_id(LLDB_INVALID_BREAK_ID, LLDB_INVALID_BREAK_ID) {}
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointList.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointList.cpp index 370da10..c80fb91 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointList.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointList.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointList.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointLocation.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointLocation.cpp index 5d3763a..b718e2a 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointLocation.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointLocation.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointLocation.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,7 +35,7 @@ hardware), m_being_created(true), m_should_resolve_indirect_functions(false), m_is_reexported(false), m_is_indirect(false), m_address(addr), - m_owner(owner), m_options_ap(), m_bp_site_sp(), m_condition_mutex() { + m_owner(owner), m_options_up(), m_bp_site_sp(), m_condition_mutex() { if (check_for_resolver) { Symbol *symbol = m_address.CalculateSymbolContextSymbol(); if (symbol && symbol->IsIndirect()) { @@ -57,10 +56,10 @@ const BreakpointOptions * BreakpointLocation::GetOptionsSpecifyingKind(BreakpointOptions::OptionKind kind) const { - if (m_options_ap && m_options_ap->IsOptionSet(kind)) - return m_options_ap.get(); - else - return m_owner.GetOptions(); + if (m_options_up && m_options_up->IsOptionSet(kind)) + return m_options_up.get(); + else + return m_owner.GetOptions(); } Address &BreakpointLocation::GetAddress() { return m_address; } @@ -72,8 +71,8 @@ bool BreakpointLocation::IsEnabled() const { if (!m_owner.IsEnabled()) return false; - else if (m_options_ap.get() != nullptr) - return m_options_ap->IsEnabled(); + else if (m_options_up != nullptr) + return m_options_up->IsEnabled(); else return true; } @@ -90,9 +89,9 @@ } bool BreakpointLocation::IsAutoContinue() const { - if (m_options_ap - && m_options_ap->IsOptionSet(BreakpointOptions::eAutoContinue)) - return m_options_ap->IsAutoContinue(); + if (m_options_up && + m_options_up->IsOptionSet(BreakpointOptions::eAutoContinue)) + return m_options_up->IsAutoContinue(); else return m_owner.IsAutoContinue(); } @@ -108,8 +107,8 @@ else { // If we're resetting this to an invalid thread id, then don't make an // options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->SetThreadID(thread_id); + if (m_options_up != nullptr) + m_options_up->SetThreadID(thread_id); } SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } @@ -130,8 +129,8 @@ else { // If we're resetting this to an invalid thread id, then don't make an // options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->GetThreadSpec()->SetIndex(index); + if (m_options_up != nullptr) + m_options_up->GetThreadSpec()->SetIndex(index); } SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } @@ -152,8 +151,8 @@ else { // If we're resetting this to an invalid thread id, then don't make an // options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->GetThreadSpec()->SetName(thread_name); + if (m_options_up != nullptr) + m_options_up->GetThreadSpec()->SetName(thread_name); } SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } @@ -174,8 +173,8 @@ else { // If we're resetting this to an invalid thread id, then don't make an // options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->GetThreadSpec()->SetQueueName(queue_name); + if (m_options_up != nullptr) + m_options_up->GetThreadSpec()->SetQueueName(queue_name); } SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } @@ -191,8 +190,8 @@ } bool BreakpointLocation::InvokeCallback(StoppointCallbackContext *context) { - if (m_options_ap.get() != nullptr && m_options_ap->HasCallback()) - return m_options_ap->InvokeCallback(context, m_owner.GetID(), GetID()); + if (m_options_up != nullptr && m_options_up->HasCallback()) + return m_options_up->InvokeCallback(context, m_owner.GetID(), GetID()); else return m_owner.InvokeCallback(context, GetID()); } @@ -256,7 +255,7 @@ m_user_expression_sp.reset(GetTarget().GetUserExpressionForLanguage( condition_text, llvm::StringRef(), language, Expression::eResultTypeAny, - EvaluateExpressionOptions(), error)); + EvaluateExpressionOptions(), nullptr, error)); if (error.Fail()) { if (log) log->Printf("Error getting condition expression: %s.", @@ -345,16 +344,16 @@ } void BreakpointLocation::DecrementIgnoreCount() { - if (m_options_ap.get() != nullptr) { - uint32_t loc_ignore = m_options_ap->GetIgnoreCount(); + if (m_options_up != nullptr) { + uint32_t loc_ignore = m_options_up->GetIgnoreCount(); if (loc_ignore != 0) - m_options_ap->SetIgnoreCount(loc_ignore - 1); + m_options_up->SetIgnoreCount(loc_ignore - 1); } } bool BreakpointLocation::IgnoreCountShouldStop() { - if (m_options_ap.get() != nullptr) { - uint32_t loc_ignore = m_options_ap->GetIgnoreCount(); + if (m_options_up != nullptr) { + uint32_t loc_ignore = m_options_up->GetIgnoreCount(); if (loc_ignore != 0) { m_owner.DecrementIgnoreCount(); DecrementIgnoreCount(); // Have to decrement our owners' ignore count, @@ -370,11 +369,10 @@ // If we make the copy we don't copy the callbacks because that is // potentially expensive and we don't want to do that for the simple case // where someone is just disabling the location. - if (m_options_ap.get() == nullptr) - m_options_ap.reset( - new BreakpointOptions(false)); + if (m_options_up == nullptr) + m_options_up.reset(new BreakpointOptions(false)); - return m_options_ap.get(); + return m_options_up.get(); } bool BreakpointLocation::ValidForThisThread(Thread *thread) { @@ -455,13 +453,11 @@ if (new_id == LLDB_INVALID_BREAK_ID) { Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS); if (log) - log->Warning("Tried to add breakpoint site at 0x%" PRIx64 - " but it was already present.\n", + log->Warning("Failed to add breakpoint site at 0x%" PRIx64, m_address.GetOpcodeLoadAddress(&m_owner.GetTarget())); - return false; } - return true; + return IsResolved(); } bool BreakpointLocation::SetBreakpointSite(BreakpointSiteSP &bp_site_sp) { @@ -606,17 +602,17 @@ s->Indent(); s->Printf("hit count = %-4u\n", GetHitCount()); - if (m_options_ap.get()) { + if (m_options_up) { s->Indent(); - m_options_ap->GetDescription(s, level); + m_options_up->GetDescription(s, level); s->EOL(); } s->IndentLess(); } else if (level != eDescriptionLevelInitial) { s->Printf(", %sresolved, hit count = %u ", (IsResolved() ? "" : "un"), GetHitCount()); - if (m_options_ap.get()) { - m_options_ap->GetDescription(s, level); + if (m_options_up) { + m_options_up->GetDescription(s, level); } } } @@ -627,18 +623,18 @@ lldb::tid_t tid = GetOptionsSpecifyingKind(BreakpointOptions::eThreadSpec) ->GetThreadSpecNoCreate()->GetTID(); - s->Printf( - "BreakpointLocation %u: tid = %4.4" PRIx64 " load addr = 0x%8.8" PRIx64 - " state = %s type = %s breakpoint " - "hw_index = %i hit_count = %-4u ignore_count = %-4u", - GetID(), tid, - (uint64_t)m_address.GetOpcodeLoadAddress(&m_owner.GetTarget()), - (m_options_ap.get() ? m_options_ap->IsEnabled() : m_owner.IsEnabled()) - ? "enabled " - : "disabled", - IsHardware() ? "hardware" : "software", GetHardwareIndex(), GetHitCount(), - GetOptionsSpecifyingKind(BreakpointOptions::eIgnoreCount) - ->GetIgnoreCount()); + s->Printf("BreakpointLocation %u: tid = %4.4" PRIx64 + " load addr = 0x%8.8" PRIx64 " state = %s type = %s breakpoint " + "hw_index = %i hit_count = %-4u ignore_count = %-4u", + GetID(), tid, + (uint64_t)m_address.GetOpcodeLoadAddress(&m_owner.GetTarget()), + (m_options_up ? m_options_up->IsEnabled() : m_owner.IsEnabled()) + ? "enabled " + : "disabled", + IsHardware() ? "hardware" : "software", GetHardwareIndex(), + GetHitCount(), + GetOptionsSpecifyingKind(BreakpointOptions::eIgnoreCount) + ->GetIgnoreCount()); } void BreakpointLocation::SendBreakpointLocationChangedEvent(
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationCollection.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationCollection.cpp index 27957a5..76084ad 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationCollection.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationCollection.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointLocationCollection.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,15 +16,11 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // BreakpointLocationCollection constructor -//---------------------------------------------------------------------- BreakpointLocationCollection::BreakpointLocationCollection() : m_break_loc_collection(), m_collection_mutex() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- BreakpointLocationCollection::~BreakpointLocationCollection() {} void BreakpointLocationCollection::Add(const BreakpointLocationSP &bp_loc) { @@ -179,3 +174,14 @@ (*pos)->GetDescription(s, level); } } + +BreakpointLocationCollection &BreakpointLocationCollection::operator=( + const BreakpointLocationCollection &rhs) { + if (this != &rhs) { + std::lock(m_collection_mutex, rhs.m_collection_mutex); + std::lock_guard<std::mutex> lhs_guard(m_collection_mutex, std::adopt_lock); + std::lock_guard<std::mutex> rhs_guard(rhs.m_collection_mutex, std::adopt_lock); + m_break_loc_collection = rhs.m_break_loc_collection; + } + return *this; +}
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationList.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationList.cpp index 6a3280e..ee58612 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationList.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointLocationList.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointLocationList.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -130,7 +129,7 @@ s->IndentMore(); collection::const_iterator pos, end = m_locations.end(); for (pos = m_locations.begin(); pos != end; ++pos) - (*pos).get()->Dump(s); + (*pos)->Dump(s); s->IndentLess(); }
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointName.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointName.cpp index baf871e..749fa86 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointName.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointName.cpp
@@ -1,9 +1,8 @@ -//===-- Breakpoint.cpp ------------------------------------------*- C++ -*-===// +//===-- BreakpointName.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details-> +// 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 // //===----------------------------------------------------------------------===// @@ -29,7 +28,7 @@ (0x5u) }; -BreakpointName::BreakpointName(const ConstString &name, const Breakpoint &bkpt, +BreakpointName::BreakpointName(ConstString name, const Breakpoint &bkpt, const char *help) : m_name(name), m_options(bkpt.GetOptions()) {
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointOptions.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointOptions.cpp index ff497c5..f6f279d 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointOptions.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointOptions.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointOptions.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -120,18 +119,16 @@ return true; } -//---------------------------------------------------------------------- // BreakpointOptions constructor -//---------------------------------------------------------------------- BreakpointOptions::BreakpointOptions(bool all_flags_set) : m_callback(BreakpointOptions::NullCallback), m_callback_baton_sp(), m_baton_is_command_baton(false), m_callback_is_synchronous(false), - m_enabled(true), m_one_shot(false), m_ignore_count(0), m_thread_spec_ap(), + m_enabled(true), m_one_shot(false), m_ignore_count(0), m_thread_spec_up(), m_condition_text(), m_condition_text_hash(0), m_auto_continue(false), m_set_flags(0) { - if (all_flags_set) - m_set_flags.Set(~((Flags::ValueType) 0)); - } + if (all_flags_set) + m_set_flags.Set(~((Flags::ValueType)0)); +} BreakpointOptions::BreakpointOptions(const char *condition, bool enabled, int32_t ignore, bool one_shot, @@ -148,26 +145,21 @@ } } -//---------------------------------------------------------------------- // BreakpointOptions copy constructor -//---------------------------------------------------------------------- BreakpointOptions::BreakpointOptions(const BreakpointOptions &rhs) : m_callback(rhs.m_callback), m_callback_baton_sp(rhs.m_callback_baton_sp), m_baton_is_command_baton(rhs.m_baton_is_command_baton), m_callback_is_synchronous(rhs.m_callback_is_synchronous), m_enabled(rhs.m_enabled), m_one_shot(rhs.m_one_shot), - m_ignore_count(rhs.m_ignore_count), m_thread_spec_ap(), - m_auto_continue(rhs.m_auto_continue), - m_set_flags(rhs.m_set_flags) { - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + m_ignore_count(rhs.m_ignore_count), m_thread_spec_up(), + m_auto_continue(rhs.m_auto_continue), m_set_flags(rhs.m_set_flags) { + if (rhs.m_thread_spec_up != nullptr) + m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up)); m_condition_text = rhs.m_condition_text; m_condition_text_hash = rhs.m_condition_text_hash; } -//---------------------------------------------------------------------- // BreakpointOptions assignment operator -//---------------------------------------------------------------------- const BreakpointOptions &BreakpointOptions:: operator=(const BreakpointOptions &rhs) { m_callback = rhs.m_callback; @@ -177,8 +169,8 @@ m_enabled = rhs.m_enabled; m_one_shot = rhs.m_one_shot; m_ignore_count = rhs.m_ignore_count; - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + if (rhs.m_thread_spec_up != nullptr) + m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up)); m_condition_text = rhs.m_condition_text; m_condition_text_hash = rhs.m_condition_text_hash; m_auto_continue = rhs.m_auto_continue; @@ -229,19 +221,16 @@ m_auto_continue = incoming.m_auto_continue; m_set_flags.Set(eAutoContinue); } - if (incoming.m_set_flags.Test(eThreadSpec) && incoming.m_thread_spec_ap) - { - if (!m_thread_spec_ap) - m_thread_spec_ap.reset(new ThreadSpec(*incoming.m_thread_spec_ap.get())); + if (incoming.m_set_flags.Test(eThreadSpec) && incoming.m_thread_spec_up) { + if (!m_thread_spec_up) + m_thread_spec_up.reset(new ThreadSpec(*incoming.m_thread_spec_up)); else - *m_thread_spec_ap.get() = *incoming.m_thread_spec_ap.get(); + *m_thread_spec_up = *incoming.m_thread_spec_up; m_set_flags.Set(eThreadSpec); } } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- BreakpointOptions::~BreakpointOptions() = default; std::unique_ptr<BreakpointOptions> BreakpointOptions::CreateFromStructuredData( @@ -256,55 +245,50 @@ const char *key = GetKey(OptionNames::EnabledState); bool success; - if (key) { + if (key && options_dict.HasKey(key)) { success = options_dict.GetValueForKeyAsBoolean(key, enabled); if (!success) { - error.SetErrorStringWithFormat("%s key is not a boolean.", - GetKey(OptionNames::EnabledState)); + error.SetErrorStringWithFormat("%s key is not a boolean.", key); return nullptr; } set_options.Set(eEnabled); } key = GetKey(OptionNames::OneShotState); - if (key) { + if (key && options_dict.HasKey(key)) { success = options_dict.GetValueForKeyAsBoolean(key, one_shot); if (!success) { - error.SetErrorStringWithFormat("%s key is not a boolean.", - GetKey(OptionNames::OneShotState)); + error.SetErrorStringWithFormat("%s key is not a boolean.", key); return nullptr; } set_options.Set(eOneShot); } key = GetKey(OptionNames::AutoContinue); - if (key) { + if (key && options_dict.HasKey(key)) { success = options_dict.GetValueForKeyAsBoolean(key, auto_continue); if (!success) { - error.SetErrorStringWithFormat("%s key is not a boolean.", - GetKey(OptionNames::AutoContinue)); + error.SetErrorStringWithFormat("%s key is not a boolean.", key); return nullptr; } set_options.Set(eAutoContinue); } key = GetKey(OptionNames::IgnoreCount); - if (key) { + if (key && options_dict.HasKey(key)) { success = options_dict.GetValueForKeyAsInteger(key, ignore_count); if (!success) { - error.SetErrorStringWithFormat("%s key is not an integer.", - GetKey(OptionNames::IgnoreCount)); + error.SetErrorStringWithFormat("%s key is not an integer.", key); return nullptr; } set_options.Set(eIgnoreCount); } key = GetKey(OptionNames::ConditionText); - if (key) { + if (key && options_dict.HasKey(key)) { success = options_dict.GetValueForKeyAsString(key, condition_ref); if (!success) { - error.SetErrorStringWithFormat("%s key is not an string.", - GetKey(OptionNames::ConditionText)); + error.SetErrorStringWithFormat("%s key is not an string.", key); return nullptr; } set_options.Set(eCondition); @@ -328,12 +312,11 @@ auto bp_options = llvm::make_unique<BreakpointOptions>( condition_ref.str().c_str(), enabled, ignore_count, one_shot, auto_continue); - if (cmd_data_up.get()) { + if (cmd_data_up) { if (cmd_data_up->interpreter == eScriptLanguageNone) bp_options->SetCommandDataCallback(cmd_data_up); else { - ScriptInterpreter *interp = - target.GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); + ScriptInterpreter *interp = target.GetDebugger().GetScriptInterpreter(); if (!interp) { error.SetErrorStringWithFormat( "Can't set script commands - no script interpreter"); @@ -405,18 +388,16 @@ BreakpointOptions::CommandData::GetSerializationKey(), commands_sp); } } - if (m_set_flags.Test(eThreadSpec) && m_thread_spec_ap) { + if (m_set_flags.Test(eThreadSpec) && m_thread_spec_up) { StructuredData::ObjectSP thread_spec_sp = - m_thread_spec_ap->SerializeToStructuredData(); + m_thread_spec_up->SerializeToStructuredData(); options_dict_sp->AddItem(ThreadSpec::GetSerializationKey(), thread_spec_sp); } return options_dict_sp; } -//------------------------------------------------------------------ // Callbacks -//------------------------------------------------------------------ void BreakpointOptions::SetCallback(BreakpointHitCallback callback, const lldb::BatonSP &callback_baton_sp, bool callback_is_synchronous) { @@ -522,17 +503,16 @@ } const ThreadSpec *BreakpointOptions::GetThreadSpecNoCreate() const { - return m_thread_spec_ap.get(); + return m_thread_spec_up.get(); } ThreadSpec *BreakpointOptions::GetThreadSpec() { - if (m_thread_spec_ap.get() == nullptr) - { + if (m_thread_spec_up == nullptr) { m_set_flags.Set(eThreadSpec); - m_thread_spec_ap.reset(new ThreadSpec()); + m_thread_spec_up.reset(new ThreadSpec()); } - return m_thread_spec_ap.get(); + return m_thread_spec_up.get(); } void BreakpointOptions::SetThreadID(lldb::tid_t thread_id) { @@ -542,7 +522,7 @@ void BreakpointOptions::SetThreadSpec( std::unique_ptr<ThreadSpec> &thread_spec_up) { - m_thread_spec_ap = std::move(thread_spec_up); + m_thread_spec_up = std::move(thread_spec_up); m_set_flags.Set(eThreadSpec); } @@ -574,8 +554,8 @@ if (m_auto_continue) s->Printf("auto-continue "); - if (m_thread_spec_ap.get()) - m_thread_spec_ap->GetDescription(s, level); + if (m_thread_spec_up) + m_thread_spec_up->GetDescription(s, level); if (level == lldb::eDescriptionLevelFull) { s->IndentLess(); @@ -666,6 +646,7 @@ options.SetStopOnError(data->stop_on_error); options.SetEchoCommands(true); options.SetPrintResults(true); + options.SetPrintErrors(true); options.SetAddToHistory(false); debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx, @@ -680,7 +661,7 @@ void BreakpointOptions::Clear() { m_set_flags.Clear(); - m_thread_spec_ap.release(); + m_thread_spec_up.release(); m_one_shot = false; m_ignore_count = 0; m_auto_continue = false;
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointPrecondition.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointPrecondition.cpp new file mode 100644 index 0000000..a387c75 --- /dev/null +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointPrecondition.cpp
@@ -0,0 +1,26 @@ +//===-- BreakpointPrecondition.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/Breakpoint/BreakpointPrecondition.h" +#include "lldb/Utility/Status.h" + +using namespace lldb_private; + +bool BreakpointPrecondition::EvaluatePrecondition( + StoppointCallbackContext &context) { + return false; +} + +void BreakpointPrecondition::GetDescription(Stream &stream, + lldb::DescriptionLevel level) {} + +Status BreakpointPrecondition::ConfigurePrecondition(Args &args) { + Status error; + error.SetErrorString("Base breakpoint precondition has no options."); + return error; +}
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolver.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolver.cpp index 0a1eeed..b3224aa 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolver.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolver.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointResolver.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,9 +31,7 @@ using namespace lldb_private; using namespace lldb; -//---------------------------------------------------------------------- // BreakpointResolver: -//---------------------------------------------------------------------- const char *BreakpointResolver::g_ty_to_name[] = {"FileAndLine", "Address", "SymbolName", "SourceRegex", "Exception", "Unknown"};
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverAddress.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverAddress.cpp index 3084ce4..8a6fd6a 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverAddress.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverAddress.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointResolverAddress.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,9 +20,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // BreakpointResolverAddress: -//---------------------------------------------------------------------- BreakpointResolverAddress::BreakpointResolverAddress( Breakpoint *bkpt, const Address &addr, const FileSpec &module_spec) : BreakpointResolver(bkpt, BreakpointResolver::AddressResolver), @@ -127,7 +124,7 @@ BreakpointResolverAddress::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *addr, bool containing) { - assert(m_breakpoint != NULL); + assert(m_breakpoint != nullptr); if (filter.AddressPasses(m_addr)) { if (m_breakpoint->GetNumLocations() == 0) {
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp index 438f430..a6095be 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointResolverFileLine.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // BreakpointResolverFileLine: -//---------------------------------------------------------------------- BreakpointResolverFileLine::BreakpointResolverFileLine( Breakpoint *bkpt, const FileSpec &file_spec, uint32_t line_no, uint32_t column, lldb::addr_t offset, bool check_inlines, @@ -207,7 +204,7 @@ Address *addr, bool containing) { SymbolContextList sc_list; - assert(m_breakpoint != NULL); + assert(m_breakpoint != nullptr); // There is a tricky bit here. You can have two compilation units that // #include the same file, and in one of them the function at m_line_number
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp index 62cf955..0b24852 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointResolverFileRegex.cpp -------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // BreakpointResolverFileRegex: -//---------------------------------------------------------------------- BreakpointResolverFileRegex::BreakpointResolverFileRegex( Breakpoint *bkpt, RegularExpression ®ex, const std::unordered_set<std::string> &func_names, bool exact_match) @@ -101,7 +98,7 @@ SymbolContext &context, Address *addr, bool containing) { - assert(m_breakpoint != NULL); + assert(m_breakpoint != nullptr); if (!context.target_sp) return eCallbackReturnContinue; @@ -148,7 +145,7 @@ BreakpointResolver::SetSCMatchesByLine(filter, sc_list, skip_prologue, m_regex.GetText()); } - assert(m_breakpoint != NULL); + assert(m_breakpoint != nullptr); return Searcher::eCallbackReturnContinue; }
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverName.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverName.cpp index 43f7cb8..3ad2e88 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverName.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverName.cpp
@@ -1,16 +1,13 @@ //===-- BreakpointResolverName.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Breakpoint/BreakpointResolverName.h" -#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" -#include "Plugins/Language/ObjC/ObjCLanguage.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Architecture.h" #include "lldb/Core/Module.h" @@ -19,6 +16,7 @@ #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Target/Target.h" +#include "lldb/Target/Language.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" @@ -218,22 +216,29 @@ return WrapOptionsDict(options_dict_sp); } -void BreakpointResolverName::AddNameLookup(const ConstString &name, +void BreakpointResolverName::AddNameLookup(ConstString name, FunctionNameType name_type_mask) { - ObjCLanguage::MethodName objc_method(name.GetCString(), false); - if (objc_method.IsValid(false)) { - std::vector<ConstString> objc_names; - objc_method.GetFullNames(objc_names, true); - for (ConstString objc_name : objc_names) { - Module::LookupInfo lookup; - lookup.SetName(name); - lookup.SetLookupName(objc_name); - lookup.SetNameTypeMask(eFunctionNameTypeFull); - m_lookups.push_back(lookup); + + Module::LookupInfo lookup(name, name_type_mask, m_language); + m_lookups.emplace_back(lookup); + + auto add_variant_funcs = [&](Language *lang) { + for (ConstString variant_name : lang->GetMethodNameVariants(name)) { + Module::LookupInfo variant_lookup(name, name_type_mask, + lang->GetLanguageType()); + variant_lookup.SetLookupName(variant_name); + m_lookups.emplace_back(variant_lookup); } + return true; + }; + + if (Language *lang = Language::FindPlugin(m_language)) { + add_variant_funcs(lang); } else { - Module::LookupInfo lookup(name, name_type_mask, m_language); - m_lookups.push_back(lookup); + // Most likely m_language is eLanguageTypeUnknown. We check each language for + // possible variants or more qualified names and create lookups for those as + // well. + Language::ForEach(add_variant_funcs); } }
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverScripted.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverScripted.cpp index 47940ef..8363795 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverScripted.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointResolverScripted.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointResolverScripted.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // BreakpointResolverScripted: -//---------------------------------------------------------------------- BreakpointResolverScripted::BreakpointResolverScripted( Breakpoint *bkpt, const llvm::StringRef class_name, @@ -49,7 +46,6 @@ if (m_breakpoint) { TargetSP target_sp = m_breakpoint->GetTargetSP(); ScriptInterpreter *script_interp = target_sp->GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter(); if (!script_interp) return; @@ -108,7 +104,6 @@ } ScriptInterpreter *script_interp = bkpt->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter(); return new BreakpointResolverScripted(bkpt, class_name, depth, args_data_impl, *script_interp); @@ -125,15 +120,14 @@ } ScriptInterpreter *BreakpointResolverScripted::GetScriptInterpreter() { - return m_breakpoint->GetTarget().GetDebugger().GetCommandInterpreter() - .GetScriptInterpreter(); + return m_breakpoint->GetTarget().GetDebugger().GetScriptInterpreter(); } Searcher::CallbackReturn BreakpointResolverScripted::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *addr, bool containing) { - assert(m_breakpoint != NULL); + assert(m_breakpoint != nullptr); bool should_continue = true; if (!m_implementation_sp) return Searcher::eCallbackReturnStop; @@ -150,7 +144,7 @@ lldb::SearchDepth BreakpointResolverScripted::GetDepth() { - assert(m_breakpoint != NULL); + assert(m_breakpoint != nullptr); lldb::SearchDepth depth = lldb::eSearchDepthModule; if (m_implementation_sp) { ScriptInterpreter *interp = GetScriptInterpreter();
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointSite.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointSite.cpp index 73c1357..a757a01 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointSite.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointSite.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointSite.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -49,9 +48,17 @@ // should continue. bool BreakpointSite::ShouldStop(StoppointCallbackContext *context) { - std::lock_guard<std::recursive_mutex> guard(m_owners_mutex); IncrementHitCount(); - return m_owners.ShouldStop(context); + // ShouldStop can do a lot of work, and might even come come back and hit + // this breakpoint site again. So don't hold the m_owners_mutex the whole + // while. Instead make a local copy of the collection and call ShouldStop on + // the copy. + BreakpointLocationCollection owners_copy; + { + std::lock_guard<std::recursive_mutex> guard(m_owners_mutex); + owners_copy = m_owners; + } + return owners_copy.ShouldStop(context); } bool BreakpointSite::IsBreakpointAtThisSite(lldb::break_id_t bp_id) {
diff --git a/src/llvm-project/lldb/source/Breakpoint/BreakpointSiteList.cpp b/src/llvm-project/lldb/source/Breakpoint/BreakpointSiteList.cpp index 2fe107e..7a986fd 100644 --- a/src/llvm-project/lldb/source/Breakpoint/BreakpointSiteList.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/BreakpointSiteList.cpp
@@ -1,9 +1,8 @@ //===-- BreakpointSiteList.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -86,7 +85,7 @@ BreakpointSiteIDMatches(lldb::break_id_t break_id) : m_break_id(break_id) {} bool operator()(std::pair<lldb::addr_t, BreakpointSiteSP> val_pair) const { - return m_break_id == val_pair.second.get()->GetID(); + return m_break_id == val_pair.second->GetID(); } private: @@ -158,7 +157,7 @@ collection::const_iterator pos; collection::const_iterator end = m_bp_site_list.end(); for (pos = m_bp_site_list.begin(); pos != end; ++pos) - pos->second.get()->Dump(s); + pos->second->Dump(s); s->IndentLess(); }
diff --git a/src/llvm-project/lldb/source/Breakpoint/CMakeLists.txt b/src/llvm-project/lldb/source/Breakpoint/CMakeLists.txt index 9ce3a3b..a7c0baf 100644 --- a/src/llvm-project/lldb/source/Breakpoint/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Breakpoint/CMakeLists.txt
@@ -8,6 +8,7 @@ BreakpointLocationList.cpp BreakpointName.cpp BreakpointOptions.cpp + BreakpointPrecondition.cpp BreakpointResolver.cpp BreakpointResolverAddress.cpp BreakpointResolverFileLine.cpp @@ -30,8 +31,6 @@ lldbSymbol lldbTarget lldbUtility - lldbPluginCPlusPlusLanguage - lldbPluginObjCLanguage LINK_COMPONENTS Support
diff --git a/src/llvm-project/lldb/source/Breakpoint/Stoppoint.cpp b/src/llvm-project/lldb/source/Breakpoint/Stoppoint.cpp index 13a8b83..4cab975 100644 --- a/src/llvm-project/lldb/source/Breakpoint/Stoppoint.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/Stoppoint.cpp
@@ -1,9 +1,8 @@ //===-- Stoppoint.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,14 +13,10 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Stoppoint constructor -//---------------------------------------------------------------------- Stoppoint::Stoppoint() : m_bid(LLDB_INVALID_BREAK_ID) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- Stoppoint::~Stoppoint() {} break_id_t Stoppoint::GetID() const { return m_bid; }
diff --git a/src/llvm-project/lldb/source/Breakpoint/StoppointCallbackContext.cpp b/src/llvm-project/lldb/source/Breakpoint/StoppointCallbackContext.cpp index 828ff18..584bf00 100644 --- a/src/llvm-project/lldb/source/Breakpoint/StoppointCallbackContext.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/StoppointCallbackContext.cpp
@@ -1,9 +1,8 @@ //===-- StoppointCallbackContext.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Breakpoint/StoppointLocation.cpp b/src/llvm-project/lldb/source/Breakpoint/StoppointLocation.cpp index 7339466..8cc6791 100644 --- a/src/llvm-project/lldb/source/Breakpoint/StoppointLocation.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/StoppointLocation.cpp
@@ -1,9 +1,8 @@ //===-- StoppointLocation.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // StoppointLocation constructor -//---------------------------------------------------------------------- StoppointLocation::StoppointLocation(break_id_t bid, addr_t addr, bool hardware) : m_loc_id(bid), m_addr(addr), m_hardware(hardware), m_hardware_index(LLDB_INVALID_INDEX32), m_byte_size(0), m_hit_count(0) {} @@ -26,9 +23,7 @@ m_hardware_index(LLDB_INVALID_INDEX32), m_byte_size(byte_size), m_hit_count(0) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- StoppointLocation::~StoppointLocation() {} void StoppointLocation::DecrementHitCount() {
diff --git a/src/llvm-project/lldb/source/Breakpoint/Watchpoint.cpp b/src/llvm-project/lldb/source/Breakpoint/Watchpoint.cpp index 34daaee..e8a9265 100644 --- a/src/llvm-project/lldb/source/Breakpoint/Watchpoint.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/Watchpoint.cpp
@@ -1,9 +1,8 @@ //===-- Watchpoint.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -273,25 +272,26 @@ void Watchpoint::SetCondition(const char *condition) { if (condition == nullptr || condition[0] == '\0') { - if (m_condition_ap.get()) - m_condition_ap.reset(); + if (m_condition_up) + m_condition_up.reset(); } else { // Pass nullptr for expr_prefix (no translation-unit level definitions). Status error; - m_condition_ap.reset(m_target.GetUserExpressionForLanguage( + m_condition_up.reset(m_target.GetUserExpressionForLanguage( condition, llvm::StringRef(), lldb::eLanguageTypeUnknown, - UserExpression::eResultTypeAny, EvaluateExpressionOptions(), error)); + UserExpression::eResultTypeAny, EvaluateExpressionOptions(), nullptr, + error)); if (error.Fail()) { // FIXME: Log something... - m_condition_ap.reset(); + m_condition_up.reset(); } } SendWatchpointChangedEvent(eWatchpointEventTypeConditionChanged); } const char *Watchpoint::GetConditionText() const { - if (m_condition_ap.get()) - return m_condition_ap->GetUserText(); + if (m_condition_up) + return m_condition_up->GetUserText(); else return nullptr; } @@ -325,12 +325,12 @@ Watchpoint::WatchpointEventData::~WatchpointEventData() = default; -const ConstString &Watchpoint::WatchpointEventData::GetFlavorString() { +ConstString Watchpoint::WatchpointEventData::GetFlavorString() { static ConstString g_flavor("Watchpoint::WatchpointEventData"); return g_flavor; } -const ConstString &Watchpoint::WatchpointEventData::GetFlavor() const { +ConstString Watchpoint::WatchpointEventData::GetFlavor() const { return WatchpointEventData::GetFlavorString(); }
diff --git a/src/llvm-project/lldb/source/Breakpoint/WatchpointList.cpp b/src/llvm-project/lldb/source/Breakpoint/WatchpointList.cpp index e1e2864..b1c1e6f 100644 --- a/src/llvm-project/lldb/source/Breakpoint/WatchpointList.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/WatchpointList.cpp
@@ -1,9 +1,8 @@ //===-- WatchpointList.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Breakpoint/WatchpointOptions.cpp b/src/llvm-project/lldb/source/Breakpoint/WatchpointOptions.cpp index 033eb66..7dd130a 100644 --- a/src/llvm-project/lldb/source/Breakpoint/WatchpointOptions.cpp +++ b/src/llvm-project/lldb/source/Breakpoint/WatchpointOptions.cpp
@@ -1,9 +1,8 @@ //===-- WatchpointOptions.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,34 +25,28 @@ return true; } -//---------------------------------------------------------------------- // WatchpointOptions constructor -//---------------------------------------------------------------------- WatchpointOptions::WatchpointOptions() : m_callback(WatchpointOptions::NullCallback), m_callback_baton_sp(), - m_callback_is_synchronous(false), m_thread_spec_ap() {} + m_callback_is_synchronous(false), m_thread_spec_up() {} -//---------------------------------------------------------------------- // WatchpointOptions copy constructor -//---------------------------------------------------------------------- WatchpointOptions::WatchpointOptions(const WatchpointOptions &rhs) : m_callback(rhs.m_callback), m_callback_baton_sp(rhs.m_callback_baton_sp), m_callback_is_synchronous(rhs.m_callback_is_synchronous), - m_thread_spec_ap() { - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + m_thread_spec_up() { + if (rhs.m_thread_spec_up != nullptr) + m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up)); } -//---------------------------------------------------------------------- // WatchpointOptions assignment operator -//---------------------------------------------------------------------- const WatchpointOptions &WatchpointOptions:: operator=(const WatchpointOptions &rhs) { m_callback = rhs.m_callback; m_callback_baton_sp = rhs.m_callback_baton_sp; m_callback_is_synchronous = rhs.m_callback_is_synchronous; - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + if (rhs.m_thread_spec_up != nullptr) + m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up)); return *this; } @@ -71,14 +64,10 @@ return ret_val; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- WatchpointOptions::~WatchpointOptions() = default; -//------------------------------------------------------------------ // Callbacks -//------------------------------------------------------------------ void WatchpointOptions::SetCallback(WatchpointHitCallback callback, const BatonSP &callback_baton_sp, bool callback_is_synchronous) { @@ -114,14 +103,14 @@ } const ThreadSpec *WatchpointOptions::GetThreadSpecNoCreate() const { - return m_thread_spec_ap.get(); + return m_thread_spec_up.get(); } ThreadSpec *WatchpointOptions::GetThreadSpec() { - if (m_thread_spec_ap.get() == nullptr) - m_thread_spec_ap.reset(new ThreadSpec()); + if (m_thread_spec_up == nullptr) + m_thread_spec_up.reset(new ThreadSpec()); - return m_thread_spec_ap.get(); + return m_thread_spec_up.get(); } void WatchpointOptions::SetThreadID(lldb::tid_t thread_id) { @@ -153,8 +142,8 @@ } else s->PutCString(" Options: "); - if (m_thread_spec_ap.get()) - m_thread_spec_ap->GetDescription(s, level); + if (m_thread_spec_up) + m_thread_spec_up->GetDescription(s, level); else if (level == eDescriptionLevelBrief) s->PutCString("thread spec: no "); if (level == lldb::eDescriptionLevelFull) {
diff --git a/src/llvm-project/lldb/source/CMakeLists.txt b/src/llvm-project/lldb/source/CMakeLists.txt index e9d8e79..d229f74 100644 --- a/src/llvm-project/lldb/source/CMakeLists.txt +++ b/src/llvm-project/lldb/source/CMakeLists.txt
@@ -15,53 +15,31 @@ endif() endforeach() -if(DEFINED lldb_vc) - set(version_inc "${CMAKE_CURRENT_BINARY_DIR}/SVNVersion.inc") - set(get_svn_script "${LLVM_CMAKE_PATH}/GetSVN.cmake") +set(version_inc "${CMAKE_CURRENT_BINARY_DIR}/VCSVersion.inc") +set(generate_vcs_version_script "${LLVM_CMAKE_PATH}/GenerateVersionFromVCS.cmake") - # Create custom target to generate the VC revision include. - add_custom_command(OUTPUT "${version_inc}" - DEPENDS "${lldb_vc}" "${get_svn_script}" - COMMAND - ${CMAKE_COMMAND} "-DFIRST_SOURCE_DIR=${LLDB_SOURCE_DIR}" - "-DFIRST_NAME=LLDB" - "-DHEADER_FILE=${version_inc}" - -P "${get_svn_script}") - - # Mark the generated header as being generated. - set_source_files_properties("${version_inc}" - PROPERTIES GENERATED TRUE - HEADER_FILE_ONLY TRUE) - - # Tell Version.cpp that it needs to build with -DHAVE_SVN_VERSION_INC. - set_property(SOURCE lldb.cpp APPEND PROPERTY - COMPILE_DEFINITIONS "HAVE_SVN_VERSION_INC") - list(APPEND lldbBase_SOURCES ${version_inc}) +if(lldb_vc) + set(lldb_source_dir ${LLDB_SOURCE_DIR}) endif() -if(APPLE) - set(apple_version_inc "${CMAKE_CURRENT_BINARY_DIR}/AppleVersion.inc") - set(apple_version_script "${LLDB_SOURCE_DIR}/cmake/modules/EmbedAppleVersion.cmake") - set(info_plist ${LLDB_SOURCE_DIR}/resources/LLDB-Info.plist) +add_custom_command(OUTPUT "${version_inc}" + DEPENDS "${lldb_vc}" "${generate_vcs_version_script}" + COMMAND ${CMAKE_COMMAND} "-DNAMES=LLDB" + "-DLLDB_SOURCE_DIR=${LLDB_SOURCE_DIR}" + "-DHEADER_FILE=${version_inc}" + -P "${generate_vcs_version_script}") - # Create custom target to generate the VC revision include. - add_custom_command(OUTPUT "${apple_version_inc}" - DEPENDS "${apple_version_script}" "${info_plist}" - COMMAND - ${CMAKE_COMMAND} "-DLLDB_INFO_PLIST=${info_plist}" - "-DHEADER_FILE=${apple_version_inc}" - -P "${apple_version_script}") +# Mark the generated header as being generated. +set_source_files_properties("${version_inc}" + PROPERTIES GENERATED TRUE + HEADER_FILE_ONLY TRUE) - # Mark the generated header as being generated. - set_source_files_properties("${apple_version_inc}" - PROPERTIES GENERATED TRUE - HEADER_FILE_ONLY TRUE) +set_property(SOURCE lldb.cpp APPEND PROPERTY + COMPILE_DEFINITIONS "HAVE_VCS_VERSION_INC") - # Tell Version.cpp that it needs to build with -DHAVE_SVN_VERSION_INC. - set_property(SOURCE lldb.cpp APPEND PROPERTY - COMPILE_DEFINITIONS "HAVE_APPLE_VERSION_INC") - list(APPEND lldbBase_SOURCES ${apple_version_inc}) -elseif(LLDB_VERSION_STRING) +list(APPEND lldbBase_SOURCES ${version_inc}) + +if(LLDB_VERSION_STRING) set_property(SOURCE lldb.cpp APPEND PROPERTY COMPILE_DEFINITIONS "LLDB_VERSION_STRING=${LLDB_VERSION_STRING}") endif()
diff --git a/src/llvm-project/lldb/source/Commands/CMakeLists.txt b/src/llvm-project/lldb/source/Commands/CMakeLists.txt index 41c54ea..657da8c 100644 --- a/src/llvm-project/lldb/source/Commands/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Commands/CMakeLists.txt
@@ -1,3 +1,7 @@ +lldb_tablegen(CommandOptions.inc -gen-lldb-option-defs + SOURCE Options.td + TARGET LLDBOptionsGen) + add_lldb_library(lldbCommands CommandCompletions.cpp CommandObjectApropos.cpp @@ -41,8 +45,9 @@ lldbSymbol lldbTarget lldbUtility - lldbPluginExpressionParserClang LINK_COMPONENTS Support ) + +add_dependencies(lldbCommands LLDBOptionsGen)
diff --git a/src/llvm-project/lldb/source/Commands/CommandCompletions.cpp b/src/llvm-project/lldb/source/Commands/CommandCompletions.cpp index 705e876..5d2fb3d 100644 --- a/src/llvm-project/lldb/source/Commands/CommandCompletions.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandCompletions.cpp
@@ -1,9 +1,8 @@ //===-- CommandCompletions.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -350,9 +349,7 @@ CommandCompletions::Completer::~Completer() = default; -//---------------------------------------------------------------------- // SourceFileCompleter -//---------------------------------------------------------------------- CommandCompletions::SourceFileCompleter::SourceFileCompleter( CommandInterpreter &interpreter, bool include_support_files, @@ -425,9 +422,7 @@ return m_request.GetNumberOfMatches(); } -//---------------------------------------------------------------------- // SymbolCompleter -//---------------------------------------------------------------------- static bool regex_chars(const char comp) { return (comp == '[' || comp == ']' || comp == '(' || comp == ')' || @@ -493,9 +488,7 @@ return m_request.GetNumberOfMatches(); } -//---------------------------------------------------------------------- // ModuleCompleter -//---------------------------------------------------------------------- CommandCompletions::ModuleCompleter::ModuleCompleter( CommandInterpreter &interpreter, CompletionRequest &request) : CommandCompletions::Completer(interpreter, request) {
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectApropos.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectApropos.cpp index 69c2760..957de475 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectApropos.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectApropos.cpp
@@ -1,10 +1,9 @@ //===-- CommandObjectApropos.cpp ---------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,9 +17,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectApropos -//------------------------------------------------------------------------- CommandObjectApropos::CommandObjectApropos(CommandInterpreter &interpreter) : CommandObjectParsed( @@ -83,7 +80,7 @@ std::vector<const Property *> properties; const size_t num_properties = - m_interpreter.GetDebugger().Apropos(search_word, properties); + GetDebugger().Apropos(search_word, properties); if (num_properties) { const bool dump_qualified_name = true; result.AppendMessageWithFormatv(
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectApropos.h b/src/llvm-project/lldb/source/Commands/CommandObjectApropos.h index acd4ced..37d86b1 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectApropos.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectApropos.h
@@ -1,10 +1,9 @@ //===-- CommandObjectApropos.h -----------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectApropos -//------------------------------------------------------------------------- class CommandObjectApropos : public CommandObjectParsed { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.cpp index 8eb6a5f..c33f383 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.cpp
@@ -1,14 +1,11 @@ //===-- CommandObjectBreakpoint.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <vector> - #include "CommandObjectBreakpoint.h" #include "CommandObjectBreakpointCommand.h" #include "lldb/Breakpoint/Breakpoint.h" @@ -31,6 +28,9 @@ #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/StreamString.h" +#include <memory> +#include <vector> + using namespace lldb; using namespace lldb_private; @@ -42,9 +42,7 @@ s->EOL(); } -//------------------------------------------------------------------------- // Modifiable Breakpoint Options -//------------------------------------------------------------------------- #pragma mark Modify::CommandOptions static constexpr OptionDefinition g_breakpoint_modify_options[] = { // clang-format off @@ -322,13 +320,11 @@ // clang-format on }; -//------------------------------------------------------------------------- // CommandObjectBreakpointSet -//------------------------------------------------------------------------- class CommandObjectBreakpointSet : public CommandObjectParsed { public: - typedef enum BreakpointSetType { + enum BreakpointSetType { eSetTypeInvalid, eSetTypeFileAndLine, eSetTypeAddress, @@ -337,7 +333,7 @@ eSetTypeSourceRegexp, eSetTypeException, eSetTypeScripted, - } BreakpointSetType; + }; CommandObjectBreakpointSet(CommandInterpreter &interpreter) : CommandObjectParsed( @@ -616,7 +612,7 @@ m_move_to_nearest_code = eLazyBoolCalculate; m_source_regex_func_names.clear(); m_python_class.clear(); - m_extra_args_sp.reset(new StructuredData::Dictionary()); + m_extra_args_sp = std::make_shared<StructuredData::Dictionary>(); m_current_key.clear(); } @@ -901,7 +897,7 @@ const bool show_locations = false; bp_sp->GetDescription(&output_stream, lldb::eDescriptionLevelInitial, show_locations); - if (target == m_interpreter.GetDebugger().GetDummyTarget()) + if (target == GetDebugger().GetDummyTarget()) output_stream.Printf("Breakpoint set in dummy target, will get copied " "into future targets.\n"); else { @@ -962,9 +958,7 @@ OptionGroupOptions m_all_options; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointModify -//------------------------------------------------------------------------- #pragma mark Modify class CommandObjectBreakpointModify : public CommandObjectParsed { @@ -1046,9 +1040,7 @@ OptionGroupOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointEnable -//------------------------------------------------------------------------- #pragma mark Enable class CommandObjectBreakpointEnable : public CommandObjectParsed { @@ -1137,9 +1129,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectBreakpointDisable -//------------------------------------------------------------------------- #pragma mark Disable class CommandObjectBreakpointDisable : public CommandObjectParsed { @@ -1252,21 +1242,14 @@ } }; -//------------------------------------------------------------------------- // CommandObjectBreakpointList -//------------------------------------------------------------------------- #pragma mark List::CommandOptions static constexpr OptionDefinition g_breakpoint_list_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "internal", 'i', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Show debugger internal breakpoints" }, - { LLDB_OPT_SET_1, false, "brief", 'b', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Give a brief description of the breakpoint (no location info)." }, - // FIXME: We need to add an "internal" command, and then add this sort of thing to it. - // But I need to see it for now, and don't want to wait. - { LLDB_OPT_SET_2, false, "full", 'f', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Give a full description of the breakpoint and its locations." }, - { LLDB_OPT_SET_3, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Explain everything we know about the breakpoint (for debugging debugger bugs)." }, - { LLDB_OPT_SET_ALL, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "List Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets." }, - // clang-format on + // FIXME: We need to add an "internal" command, and then add this sort of + // thing to it. But I need to see it for now, and don't want to wait. +#define LLDB_OPTIONS_breakpoint_list +#include "CommandOptions.inc" }; #pragma mark List @@ -1418,9 +1401,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointClear -//------------------------------------------------------------------------- #pragma mark Clear::CommandOptions static constexpr OptionDefinition g_breakpoint_clear_options[] = { @@ -1434,10 +1415,7 @@ class CommandObjectBreakpointClear : public CommandObjectParsed { public: - typedef enum BreakpointClearType { - eClearTypeInvalid, - eClearTypeFileAndLine - } BreakpointClearType; + enum BreakpointClearType { eClearTypeInvalid, eClearTypeFileAndLine }; CommandObjectBreakpointClear(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "breakpoint clear", @@ -1578,9 +1556,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointDelete -//------------------------------------------------------------------------- static constexpr OptionDefinition g_breakpoint_delete_options[] = { // clang-format off { LLDB_OPT_SET_1, false, "force", 'f', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Delete all breakpoints without querying for confirmation." }, @@ -1734,9 +1710,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointName -//------------------------------------------------------------------------- static constexpr OptionDefinition g_breakpoint_name_options[] = { // clang-format off @@ -2245,9 +2219,7 @@ OptionGroupOptions m_option_group; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointName -//------------------------------------------------------------------------- class CommandObjectBreakpointName : public CommandObjectMultiword { public: CommandObjectBreakpointName(CommandInterpreter &interpreter) @@ -2272,9 +2244,7 @@ ~CommandObjectBreakpointName() override = default; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointRead -//------------------------------------------------------------------------- #pragma mark Read::CommandOptions static constexpr OptionDefinition g_breakpoint_read_options[] = { // clang-format off @@ -2403,9 +2373,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointWrite -//------------------------------------------------------------------------- #pragma mark Write::CommandOptions static constexpr OptionDefinition g_breakpoint_write_options[] = { // clang-format off @@ -2517,9 +2485,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectMultiwordBreakpoint -//------------------------------------------------------------------------- #pragma mark MultiwordBreakpoint CommandObjectMultiwordBreakpoint::CommandObjectMultiwordBreakpoint(
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.h b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.h index d0026f9..cba1f3f 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpoint.h
@@ -1,9 +1,8 @@ //===-- CommandObjectBreakpoint.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordBreakpoint -//------------------------------------------------------------------------- class CommandObjectMultiwordBreakpoint : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.cpp index 991b174..3f9d83c 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectBreakpointCommand.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -27,9 +26,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectBreakpointCommandAdd -//------------------------------------------------------------------------- // FIXME: "script-type" needs to have its contents determined dynamically, so // somebody can add a new scripting @@ -223,9 +220,9 @@ Options *GetOptions() override { return &m_options; } - void IOHandlerActivated(IOHandler &io_handler) override { + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { + if (output_sp && interactive) { output_sp->PutCString(g_reader_instructions); output_sp->Flush(); } @@ -425,7 +422,7 @@ // to set or collect command callback. Otherwise, call the methods // associated with this object. if (m_options.m_use_script_language) { - ScriptInterpreter *script_interp = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *script_interp = GetDebugger().GetScriptInterpreter(); // Special handling for one-liner specified inline. if (m_options.m_use_one_liner) { script_interp->SetBreakpointCommandCallback( @@ -470,9 +467,7 @@ const char *CommandObjectBreakpointCommandAdd::g_reader_instructions = "Enter your debugger command(s). Type 'DONE' to end.\n"; -//------------------------------------------------------------------------- // CommandObjectBreakpointCommandDelete -//------------------------------------------------------------------------- static constexpr OptionDefinition g_breakpoint_delete_options[] = { // clang-format off @@ -607,9 +602,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectBreakpointCommandList -//------------------------------------------------------------------------- class CommandObjectBreakpointCommandList : public CommandObjectParsed { public: @@ -637,7 +630,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("There is not a current executable; there are no " @@ -727,9 +720,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectBreakpointCommand -//------------------------------------------------------------------------- CommandObjectBreakpointCommand::CommandObjectBreakpointCommand( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.h b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.h index 96d2121..b18e003 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectBreakpointCommand.h
@@ -1,9 +1,8 @@ //===-- CommandObjectBreakpointCommand.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,9 +19,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordBreakpoint -//------------------------------------------------------------------------- class CommandObjectBreakpointCommand : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.cpp index dc4b9ef..515cc9a 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectBugreport.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,9 +19,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // "bugreport unwind" -//------------------------------------------------------------------------- class CommandObjectBugreportUnwind : public CommandObjectParsed { public: @@ -97,6 +94,7 @@ options.SetStopOnError(false); options.SetEchoCommands(true); options.SetPrintResults(true); + options.SetPrintErrors(true); options.SetAddToHistory(false); m_interpreter.HandleCommands(commands, &m_exe_ctx, options, result); @@ -110,9 +108,7 @@ #pragma mark CommandObjectMultiwordBugreport -//------------------------------------------------------------------------- // CommandObjectMultiwordBugreport -//------------------------------------------------------------------------- CommandObjectMultiwordBugreport::CommandObjectMultiwordBugreport( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.h b/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.h index 1d9aea5..24ce6d2 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectBugreport.h
@@ -1,9 +1,8 @@ //===-- CommandObjectBugreport.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordBugreport -//------------------------------------------------------------------------- class CommandObjectMultiwordBugreport : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectCommands.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectCommands.cpp index 01e1c42..4092e76 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectCommands.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectCommands.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectCommands.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,9 +29,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectCommandsSource -//------------------------------------------------------------------------- static constexpr OptionDefinition g_history_options[] = { // clang-format off @@ -189,9 +186,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectCommandsSource -//------------------------------------------------------------------------- static constexpr OptionDefinition g_source_options[] = { // clang-format off @@ -314,14 +309,20 @@ m_options.m_stop_on_continue.OptionWasSet()) { // Use user set settings CommandInterpreterRunOptions options; - options.SetStopOnContinue(m_options.m_stop_on_continue.GetCurrentValue()); - options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue()); + + if (m_options.m_stop_on_continue.OptionWasSet()) + options.SetStopOnContinue( + m_options.m_stop_on_continue.GetCurrentValue()); + + if (m_options.m_stop_on_error.OptionWasSet()) + options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue()); // Individual silent setting is override for global command echo settings. if (m_options.m_silent_run.GetCurrentValue()) { options.SetSilent(true); } else { options.SetPrintResults(true); + options.SetPrintErrors(true); options.SetEchoCommands(m_interpreter.GetEchoCommands()); options.SetEchoCommentCommands(m_interpreter.GetEchoCommentCommands()); } @@ -340,9 +341,7 @@ }; #pragma mark CommandObjectCommandsAlias -//------------------------------------------------------------------------- // CommandObjectCommandsAlias -//------------------------------------------------------------------------- static constexpr OptionDefinition g_alias_options[] = { // clang-format off @@ -766,9 +765,7 @@ }; #pragma mark CommandObjectCommandsUnalias -//------------------------------------------------------------------------- // CommandObjectCommandsUnalias -//------------------------------------------------------------------------- class CommandObjectCommandsUnalias : public CommandObjectParsed { public: @@ -849,9 +846,7 @@ }; #pragma mark CommandObjectCommandsDelete -//------------------------------------------------------------------------- // CommandObjectCommandsDelete -//------------------------------------------------------------------------- class CommandObjectCommandsDelete : public CommandObjectParsed { public: @@ -891,11 +886,11 @@ auto command_name = args[0].ref; if (!m_interpreter.CommandExists(command_name)) { StreamString error_msg_stream; - const bool generate_apropos = true; + const bool generate_upropos = true; const bool generate_type_lookup = false; CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage( &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(), - generate_apropos, generate_type_lookup); + generate_upropos, generate_type_lookup); result.AppendError(error_msg_stream.GetString()); result.SetStatus(eReturnStatusFailed); return false; @@ -914,9 +909,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectCommandsAddRegex -//------------------------------------------------------------------------- static constexpr OptionDefinition g_regex_options[] = { // clang-format off @@ -976,10 +969,10 @@ ~CommandObjectCommandsAddRegex() override = default; protected: - void IOHandlerActivated(IOHandler &io_handler) override { + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { - output_sp->PutCString("Enter one of more sed substitution commands in " + if (output_sp && interactive) { + output_sp->PutCString("Enter one or more sed substitution commands in " "the form: 's/<regex>/<subst>/'.\nTerminate the " "substitution list with an empty line.\n"); output_sp->Flush(); @@ -989,7 +982,7 @@ void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override { io_handler.SetIsDone(true); - if (m_regex_cmd_ap) { + if (m_regex_cmd_up) { StringList lines; if (lines.SplitIntoLines(data)) { const size_t num_lines = lines.GetSize(); @@ -998,18 +991,15 @@ llvm::StringRef bytes_strref(lines[i]); Status error = AppendRegexSubstitution(bytes_strref, check_only); if (error.Fail()) { - if (!m_interpreter.GetDebugger() - .GetCommandInterpreter() - .GetBatchCommandMode()) { - StreamSP out_stream = - m_interpreter.GetDebugger().GetAsyncOutputStream(); + if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode()) { + StreamSP out_stream = GetDebugger().GetAsyncOutputStream(); out_stream->Printf("error: %s\n", error.AsCString()); } } } } - if (m_regex_cmd_ap->HasRegexEntries()) { - CommandObjectSP cmd_sp(m_regex_cmd_ap.release()); + if (m_regex_cmd_up->HasRegexEntries()) { + CommandObjectSP cmd_sp(m_regex_cmd_up.release()); m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true); } } @@ -1026,12 +1016,12 @@ Status error; auto name = command[0].ref; - m_regex_cmd_ap = llvm::make_unique<CommandObjectRegexCommand>( + m_regex_cmd_up = llvm::make_unique<CommandObjectRegexCommand>( m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, 0, true); if (argc == 1) { - Debugger &debugger = m_interpreter.GetDebugger(); + Debugger &debugger = GetDebugger(); bool color_prompt = debugger.GetUseColor(); const bool multiple_lines = true; // Get multiple lines IOHandlerSP io_handler_sp(new IOHandlerEditline( @@ -1041,7 +1031,7 @@ llvm::StringRef(), // Continuation prompt multiple_lines, color_prompt, 0, // Don't show line numbers - *this)); + *this, nullptr)); if (io_handler_sp) { debugger.PushIOHandler(io_handler_sp); @@ -1071,7 +1061,7 @@ bool check_only) { Status error; - if (!m_regex_cmd_ap) { + if (!m_regex_cmd_up) { error.SetErrorStringWithFormat( "invalid regular expression command object for: '%.*s'", (int)regex_sed.size(), regex_sed.data()); @@ -1157,22 +1147,22 @@ std::string subst(regex_sed.substr(second_separator_char_pos + 1, third_separator_char_pos - second_separator_char_pos - 1)); - m_regex_cmd_ap->AddRegexCommand(regex.c_str(), subst.c_str()); + m_regex_cmd_up->AddRegexCommand(regex.c_str(), subst.c_str()); } return error; } void AddRegexCommandToInterpreter() { - if (m_regex_cmd_ap) { - if (m_regex_cmd_ap->HasRegexEntries()) { - CommandObjectSP cmd_sp(m_regex_cmd_ap.release()); + if (m_regex_cmd_up) { + if (m_regex_cmd_up->HasRegexEntries()) { + CommandObjectSP cmd_sp(m_regex_cmd_up.release()); m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true); } } } private: - std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_ap; + std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_up; class CommandOptions : public Options { public: @@ -1259,7 +1249,7 @@ if (m_fetched_help_long) return CommandObjectRaw::GetHelpLong(); - ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter(); if (!scripter) return CommandObjectRaw::GetHelpLong(); @@ -1274,7 +1264,7 @@ protected: bool DoExecute(llvm::StringRef raw_command_line, CommandReturnObject &result) override { - ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter(); Status error; @@ -1317,7 +1307,7 @@ StreamString stream; stream.Printf("For more information run 'help %s'", name.c_str()); SetHelp(stream.GetString()); - if (ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter()) + if (ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter()) GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp)); } @@ -1332,7 +1322,7 @@ llvm::StringRef GetHelp() override { if (m_fetched_help_short) return CommandObjectRaw::GetHelp(); - ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter(); if (!scripter) return CommandObjectRaw::GetHelp(); std::string docstring; @@ -1348,7 +1338,7 @@ if (m_fetched_help_long) return CommandObjectRaw::GetHelpLong(); - ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter(); if (!scripter) return CommandObjectRaw::GetHelpLong(); @@ -1363,7 +1353,7 @@ protected: bool DoExecute(llvm::StringRef raw_command_line, CommandReturnObject &result) override { - ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter(); Status error; @@ -1394,9 +1384,7 @@ bool m_fetched_help_long : 1; }; -//------------------------------------------------------------------------- // CommandObjectCommandsScriptImport -//------------------------------------------------------------------------- static constexpr OptionDefinition g_script_import_options[] = { // clang-format off @@ -1477,8 +1465,7 @@ }; bool DoExecute(Args &command, CommandReturnObject &result) override { - if (m_interpreter.GetDebugger().GetScriptLanguage() != - lldb::eScriptLanguagePython) { + if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) { result.AppendError("only scripting language supported for module " "importing is currently Python"); result.SetStatus(eReturnStatusFailed); @@ -1504,7 +1491,7 @@ // won't stomp on each other (wrt to execution contents, options, and // more) m_exe_ctx.Clear(); - if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule( + if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule( entry.c_str(), m_options.m_allow_reload, init_session, error)) { result.SetStatus(eReturnStatusSuccessFinishNoResult); } else { @@ -1520,9 +1507,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectCommandsScriptAdd -//------------------------------------------------------------------------- static constexpr OptionEnumValueElement g_script_synchro_type[] = { {eScriptedCommandSynchronicitySynchronous, "synchronous", "Run synchronous"}, @@ -1635,9 +1620,9 @@ ScriptedCommandSynchronicity m_synchronicity; }; - void IOHandlerActivated(IOHandler &io_handler) override { + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { + if (output_sp && interactive) { output_sp->PutCString(g_python_command_instructions); output_sp->Flush(); } @@ -1647,7 +1632,7 @@ std::string &data) override { StreamFileSP error_sp = io_handler.GetErrorStreamFile(); - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter) { StringList lines; @@ -1693,8 +1678,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - if (m_interpreter.GetDebugger().GetScriptLanguage() != - lldb::eScriptLanguagePython) { + if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) { result.AppendError("only scripting language supported for scripted " "commands is currently Python"); result.SetStatus(eReturnStatusFailed); @@ -1732,8 +1716,7 @@ } } } else { - ScriptInterpreter *interpreter = - GetCommandInterpreter().GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (!interpreter) { result.AppendError("cannot find ScriptInterpreter"); result.SetStatus(eReturnStatusFailed); @@ -1767,9 +1750,7 @@ ScriptedCommandSynchronicity m_synchronicity; }; -//------------------------------------------------------------------------- // CommandObjectCommandsScriptList -//------------------------------------------------------------------------- class CommandObjectCommandsScriptList : public CommandObjectParsed { public: @@ -1788,9 +1769,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectCommandsScriptClear -//------------------------------------------------------------------------- class CommandObjectCommandsScriptClear : public CommandObjectParsed { public: @@ -1810,9 +1789,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectCommandsScriptDelete -//------------------------------------------------------------------------- class CommandObjectCommandsScriptDelete : public CommandObjectParsed { public: @@ -1862,9 +1839,7 @@ #pragma mark CommandObjectMultiwordCommandsScript -//------------------------------------------------------------------------- // CommandObjectMultiwordCommandsScript -//------------------------------------------------------------------------- class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword { public: @@ -1894,9 +1869,7 @@ #pragma mark CommandObjectMultiwordCommands -//------------------------------------------------------------------------- // CommandObjectMultiwordCommands -//------------------------------------------------------------------------- CommandObjectMultiwordCommands::CommandObjectMultiwordCommands( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectCommands.h b/src/llvm-project/lldb/source/Commands/CommandObjectCommands.h index 57ae8f2..468ee53 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectCommands.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectCommands.h
@@ -1,10 +1,9 @@ //===-- CommandObjectCommands.h -----------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,9 +16,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordCommands -//------------------------------------------------------------------------- class CommandObjectMultiwordCommands : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.cpp index f8ee461..5972555b 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -230,9 +229,7 @@ return llvm::makeArrayRef(g_disassemble_options); } -//------------------------------------------------------------------------- // CommandObjectDisassemble -//------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble( CommandInterpreter &interpreter) @@ -248,7 +245,7 @@ bool CommandObjectDisassemble::DoExecute(Args &command, CommandReturnObject &result) { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -323,8 +320,8 @@ ConstString name(m_options.func_name.c_str()); if (Disassembler::Disassemble( - m_interpreter.GetDebugger(), m_options.arch, plugin_name, - flavor_string, m_exe_ctx, name, + GetDebugger(), m_options.arch, plugin_name, flavor_string, + m_exe_ctx, name, nullptr, // Module * m_options.num_instructions, m_options.show_mixed, m_options.show_mixed ? m_options.num_lines_context : 0, options, @@ -487,8 +484,8 @@ bool print_sc_header = ranges.size() > 1; for (AddressRange cur_range : ranges) { if (Disassembler::Disassemble( - m_interpreter.GetDebugger(), m_options.arch, plugin_name, - flavor_string, m_exe_ctx, cur_range.GetBaseAddress(), + GetDebugger(), m_options.arch, plugin_name, flavor_string, + m_exe_ctx, cur_range.GetBaseAddress(), m_options.num_instructions, m_options.show_mixed, m_options.show_mixed ? m_options.num_lines_context : 0, options, result.GetOutputStream())) { @@ -535,8 +532,8 @@ cur_range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); if (Disassembler::Disassemble( - m_interpreter.GetDebugger(), m_options.arch, plugin_name, - flavor_string, m_exe_ctx, cur_range, m_options.num_instructions, + GetDebugger(), m_options.arch, plugin_name, flavor_string, + m_exe_ctx, cur_range, m_options.num_instructions, m_options.show_mixed, m_options.show_mixed ? m_options.num_lines_context : 0, options, result.GetOutputStream())) {
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.h b/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.h index 04c4cc2..70193e9 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectDisassemble.h
@@ -1,9 +1,8 @@ //===-- CommandObjectDisassemble.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectDisassemble -//------------------------------------------------------------------------- class CommandObjectDisassemble : public CommandObjectParsed { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectExpression.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectExpression.cpp index e87d68a..29e4ab6 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectExpression.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectExpression.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,7 +10,6 @@ #include "llvm/ADT/StringRef.h" #include "CommandObjectExpression.h" -#include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Value.h" #include "lldb/Core/ValueObjectVariable.h" @@ -235,7 +233,7 @@ with no newlines. To evaluate a multi-line expression, \ hit a return after an empty expression, and lldb will enter the multi-line expression editor. \ Hit return on an empty line to end the multi-line expression." - + R"( Timeouts: @@ -364,7 +362,7 @@ Status error; lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage( code, llvm::StringRef(), language, UserExpression::eResultTypeAny, - options, error)); + options, nullptr, error)); if (error.Fail()) return 0; @@ -483,8 +481,7 @@ } else { if (result_valobj_sp->GetError().GetError() == UserExpression::kNoResult) { - if (format != eFormatVoid && - m_interpreter.GetDebugger().GetNotifyVoid()) { + if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) { error_stream->PutCString("(void)\n"); } @@ -561,7 +558,7 @@ llvm::StringRef(), // Continuation prompt multiple_lines, color_prompt, 1, // Show line numbers starting at 1 - *this)); + *this, nullptr)); StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); if (output_sp) { @@ -572,6 +569,29 @@ debugger.PushIOHandler(io_handler_sp); } +static EvaluateExpressionOptions +GetExprOptions(ExecutionContext &ctx, + CommandObjectExpression::CommandOptions command_options) { + command_options.OptionParsingStarting(&ctx); + + // Default certain settings for REPL regardless of the global settings. + command_options.unwind_on_error = false; + command_options.ignore_breakpoints = false; + command_options.debug = false; + + EvaluateExpressionOptions expr_options; + expr_options.SetUnwindOnError(command_options.unwind_on_error); + expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints); + expr_options.SetTryAllThreads(command_options.try_all_threads); + + if (command_options.timeout > 0) + expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout)); + else + expr_options.SetTimeout(llvm::None); + + return expr_options; +} + bool CommandObjectExpression::DoExecute(llvm::StringRef command, CommandReturnObject &result) { m_fixed_expression.clear(); @@ -627,7 +647,8 @@ if (repl_sp) { if (initialize) { - repl_sp->SetCommandOptions(m_command_options); + repl_sp->SetEvaluateOptions( + GetExprOptions(exe_ctx, m_command_options)); repl_sp->SetFormatOptions(m_format_options); repl_sp->SetValueObjectDisplayOptions(m_varobj_options); }
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectExpression.h b/src/llvm-project/lldb/source/Commands/CommandObjectExpression.h index 2eeca0d..89c8e1d 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectExpression.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectExpression.h
@@ -1,9 +1,8 @@ //===-- CommandObjectExpression.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -58,9 +57,7 @@ int HandleCompletion(CompletionRequest &request) override; protected: - //------------------------------------------------------------------ // IOHandler::Delegate functions - //------------------------------------------------------------------ void IOHandlerInputComplete(IOHandler &io_handler, std::string &line) override; @@ -71,7 +68,7 @@ bool EvaluateExpression(llvm::StringRef expr, Stream *output_stream, Stream *error_stream, - CommandReturnObject *result = NULL); + CommandReturnObject *result = nullptr); void GetMultilineExpression();
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectFrame.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectFrame.cpp index f8318a3..ab6a079 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectFrame.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectFrame.cpp
@@ -1,14 +1,10 @@ //===-- CommandObjectFrame.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <string> - #include "CommandObjectFrame.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" @@ -46,18 +42,17 @@ #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" +#include <memory> +#include <string> + using namespace lldb; using namespace lldb_private; #pragma mark CommandObjectFrameDiagnose -//------------------------------------------------------------------------- // CommandObjectFrameInfo -//------------------------------------------------------------------------- -//------------------------------------------------------------------------- // CommandObjectFrameDiagnose -//------------------------------------------------------------------------- static constexpr OptionDefinition g_frame_diag_options[] = { // clang-format off @@ -217,9 +212,7 @@ #pragma mark CommandObjectFrameInfo -//------------------------------------------------------------------------- // CommandObjectFrameInfo -//------------------------------------------------------------------------- class CommandObjectFrameInfo : public CommandObjectParsed { public: @@ -243,9 +236,7 @@ #pragma mark CommandObjectFrameSelect -//------------------------------------------------------------------------- // CommandObjectFrameSelect -//------------------------------------------------------------------------- static OptionDefinition g_frame_select_options[] = { // clang-format off @@ -413,9 +404,7 @@ }; #pragma mark CommandObjectFrameVariable -//---------------------------------------------------------------------- // List images with associated information -//---------------------------------------------------------------------- class CommandObjectFrameVariable : public CommandObjectParsed { public: CommandObjectFrameVariable(CommandInterpreter &interpreter) @@ -527,9 +516,9 @@ ConstString(m_option_variable.summary.GetCurrentValue()), summary_format_sp); else if (!m_option_variable.summary_string.IsCurrentValueEmpty()) - summary_format_sp.reset(new StringSummaryFormat( + summary_format_sp = std::make_shared<StringSummaryFormat>( TypeSummaryImpl::Flags(), - m_option_variable.summary_string.GetCurrentValue())); + m_option_variable.summary_string.GetCurrentValue()); DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( eLanguageRuntimeDescriptionDisplayVerbosityFull, eFormatDefault, @@ -901,7 +890,7 @@ return false; } - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter && !interpreter->CheckObjectExists(m_options.m_class_name.c_str())) { @@ -1119,9 +1108,7 @@ #pragma mark CommandObjectMultiwordFrame -//------------------------------------------------------------------------- // CommandObjectMultiwordFrame -//------------------------------------------------------------------------- CommandObjectMultiwordFrame::CommandObjectMultiwordFrame( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectFrame.h b/src/llvm-project/lldb/source/Commands/CommandObjectFrame.h index 3199399..46a59f7 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectFrame.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectFrame.h
@@ -1,9 +1,8 @@ //===-- CommandObjectFrame.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordFrame -//------------------------------------------------------------------------- class CommandObjectMultiwordFrame : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectGUI.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectGUI.cpp index ed834dc..21ed510 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectGUI.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectGUI.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectGUI.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectGUI -//------------------------------------------------------------------------- CommandObjectGUI::CommandObjectGUI(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "gui", @@ -29,7 +26,7 @@ bool CommandObjectGUI::DoExecute(Args &args, CommandReturnObject &result) { #ifndef LLDB_DISABLE_CURSES if (args.GetArgumentCount() == 0) { - Debugger &debugger = m_interpreter.GetDebugger(); + Debugger &debugger = GetDebugger(); lldb::StreamFileSP input_sp = debugger.GetInputFile(); if (input_sp && input_sp->GetFile().GetIsRealTerminal() &&
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectGUI.h b/src/llvm-project/lldb/source/Commands/CommandObjectGUI.h index b20c3a7..a19aad1 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectGUI.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectGUI.h
@@ -1,9 +1,8 @@ //===-- CommandObjectGUI.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectGUI -//------------------------------------------------------------------------- class CommandObjectGUI : public CommandObjectParsed { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectHelp.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectHelp.cpp index 1f1d63d..ab55791 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectHelp.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectHelp.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectHelp.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,13 +15,12 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectHelp -//------------------------------------------------------------------------- void CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage( - Stream *s, llvm::StringRef command, llvm::StringRef prefix, llvm::StringRef subcommand, - bool include_apropos, bool include_type_lookup) { + Stream *s, llvm::StringRef command, llvm::StringRef prefix, + llvm::StringRef subcommand, bool include_upropos, + bool include_type_lookup) { if (!s || command.empty()) return; @@ -33,7 +31,7 @@ s->Printf("'%s' is not a known command.\n", command_str.c_str()); s->Printf("Try '%shelp' to see a current list of commands.\n", prefix.str().c_str()); - if (include_apropos) { + if (include_upropos) { s->Printf("Try '%sapropos %s' for a list of related commands.\n", prefix_str.c_str(), lookup_str.c_str()); } @@ -68,11 +66,8 @@ CommandObjectHelp::~CommandObjectHelp() = default; static constexpr OptionDefinition g_help_options[] = { - // clang-format off - {LLDB_OPT_SET_ALL, false, "hide-aliases", 'a', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Hide aliases in the command list."}, - {LLDB_OPT_SET_ALL, false, "hide-user-commands", 'u', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Hide user-defined commands from the list."}, - {LLDB_OPT_SET_ALL, false, "show-hidden-commands", 'h', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Include commands prefixed with an underscore."}, - // clang-format on +#define LLDB_OPTIONS_help +#include "CommandOptions.inc" }; llvm::ArrayRef<OptionDefinition>
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectHelp.h b/src/llvm-project/lldb/source/Commands/CommandObjectHelp.h index 5d5b672..a641b19 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectHelp.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectHelp.h
@@ -1,9 +1,8 @@ //===-- CommandObjectHelp.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectHelp -//------------------------------------------------------------------------- class CommandObjectHelp : public CommandObjectParsed { public: @@ -30,7 +27,7 @@ static void GenerateAdditionalHelpAvenuesMessage( Stream *s, llvm::StringRef command, llvm::StringRef prefix, - llvm::StringRef subcommand, bool include_apropos = true, + llvm::StringRef subcommand, bool include_upropos = true, bool include_type_lookup = true); class CommandOptions : public Options {
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.cpp index f0028d6..47c9e2a 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectLanguage.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.h b/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.h index ef8e118..b86457c 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectLanguage.h
@@ -1,9 +1,8 @@ //===-- CommandObjectLanguage.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectLog.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectLog.cpp index b019336b..2ad61de 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectLog.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectLog.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectLog.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -49,9 +48,7 @@ class CommandObjectLogEnable : public CommandObjectParsed { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectLogEnable(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "log enable", "Enable logging for a single log channel.", @@ -171,9 +168,9 @@ std::string error; llvm::raw_string_ostream error_stream(error); - bool success = m_interpreter.GetDebugger().EnableLog( - channel, args.GetArgumentArrayRef(), log_file, m_options.log_options, - error_stream); + bool success = + GetDebugger().EnableLog(channel, args.GetArgumentArrayRef(), log_file, + m_options.log_options, error_stream); result.GetErrorStream() << error_stream.str(); if (success) @@ -188,9 +185,7 @@ class CommandObjectLogDisable : public CommandObjectParsed { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectLogDisable(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "log disable", "Disable one or more log channel categories.", @@ -248,9 +243,7 @@ class CommandObjectLogList : public CommandObjectParsed { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectLogList(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "log list", "List the log categories for one or more log " @@ -295,9 +288,7 @@ class CommandObjectLogTimer : public CommandObjectParsed { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectLogTimer(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "log timers", "Enable, disable, dump, and reset LLDB internal "
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectLog.h b/src/llvm-project/lldb/source/Commands/CommandObjectLog.h index f02a7be..b2da900 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectLog.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectLog.h
@@ -1,9 +1,8 @@ //===-- CommandObjectLog.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,23 +16,17 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectLog -//------------------------------------------------------------------------- class CommandObjectLog : public CommandObjectMultiword { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectLog(CommandInterpreter &interpreter); ~CommandObjectLog() override; private: - //------------------------------------------------------------------ // For CommandObjectLog only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(CommandObjectLog); };
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectMemory.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectMemory.cpp index b1edb1a..1afcac7 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectMemory.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectMemory.cpp
@@ -1,24 +1,19 @@ //===-- CommandObjectMemory.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <inttypes.h> - -#include "clang/AST/Decl.h" - #include "CommandObjectMemory.h" -#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/DumpDataExtractor.h" #include "lldb/Core/Module.h" #include "lldb/Core/Section.h" #include "lldb/Core/ValueObjectMemory.h" #include "lldb/DataFormatters/ValueObjectPrinter.h" +#include "lldb/Expression/ExpressionVariable.h" #include "lldb/Host/OptionParser.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" @@ -26,15 +21,17 @@ #include "lldb/Interpreter/OptionGroupFormat.h" #include "lldb/Interpreter/OptionGroupOutputFile.h" #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h" +#include "lldb/Interpreter/OptionValueLanguage.h" #include "lldb/Interpreter/OptionValueString.h" #include "lldb/Interpreter/Options.h" -#include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/TypeList.h" +#include "lldb/Target/Language.h" #include "lldb/Target/MemoryHistory.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/StackFrame.h" +#include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/DataBufferHeap.h" @@ -43,6 +40,9 @@ #include "lldb/lldb-private.h" +#include <cinttypes> +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -51,7 +51,9 @@ {LLDB_OPT_SET_1, false, "num-per-line", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNumberPerLine, "The number of items per line to display." }, {LLDB_OPT_SET_2, false, "binary", 'b', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "If true, memory will be saved as binary. If false, the memory is saved save as an ASCII dump that " "uses the format, size, count and number per line settings." }, - {LLDB_OPT_SET_3, true , "type", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, "The name of a type to view memory as." }, + {LLDB_OPT_SET_3 | + LLDB_OPT_SET_4, true , "type", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "The name of a type to view memory as." }, + {LLDB_OPT_SET_4, false, "language", 'x', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "The language of the type to view memory as."}, {LLDB_OPT_SET_3, false, "offset", 'E', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many elements of the specified type to skip before starting to display data." }, {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | @@ -63,7 +65,7 @@ public: OptionGroupReadMemory() : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(), - m_offset(0, 0) {} + m_offset(0, 0), m_language_for_type(eLanguageTypeUnknown) {} ~OptionGroupReadMemory() override = default; @@ -97,6 +99,10 @@ m_force = true; break; + case 'x': + error = m_language_for_type.SetValueFromString(option_value); + break; + case 'E': error = m_offset.SetValueFromString(option_value); break; @@ -115,6 +121,7 @@ m_view_as_type.Clear(); m_force = false; m_offset.Clear(); + m_language_for_type.Clear(); } Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) { @@ -277,7 +284,8 @@ bool AnyOptionWasSet() const { return m_num_per_line.OptionWasSet() || m_output_as_binary || - m_view_as_type.OptionWasSet() || m_offset.OptionWasSet(); + m_view_as_type.OptionWasSet() || m_offset.OptionWasSet() || + m_language_for_type.OptionWasSet(); } OptionValueUInt64 m_num_per_line; @@ -285,11 +293,10 @@ OptionValueString m_view_as_type; bool m_force; OptionValueUInt64 m_offset; + OptionValueLanguage m_language_for_type; }; -//---------------------------------------------------------------------- // Read memory from the inferior process -//---------------------------------------------------------------------- class CommandObjectMemoryRead : public CommandObjectParsed { public: CommandObjectMemoryRead(CommandInterpreter &interpreter) @@ -374,7 +381,7 @@ return false; } - CompilerType clang_ast_type; + CompilerType compiler_type; Status error; const char *view_as_type_cstr = @@ -474,26 +481,43 @@ exact_match, 1, searched_symbol_files, type_list); - if (type_list.GetSize() == 0 && lookup_type_name.GetCString() && - *lookup_type_name.GetCString() == '$') { - if (ClangPersistentVariables *persistent_vars = - llvm::dyn_cast_or_null<ClangPersistentVariables>( - target->GetPersistentExpressionStateForLanguage( - lldb::eLanguageTypeC))) { - clang::TypeDecl *tdecl = llvm::dyn_cast_or_null<clang::TypeDecl>( - persistent_vars->GetPersistentDecl( - ConstString(lookup_type_name))); + if (type_list.GetSize() == 0 && lookup_type_name.GetCString()) { + LanguageType language_for_type = + m_memory_options.m_language_for_type.GetCurrentValue(); + std::set<LanguageType> languages_to_check; + if (language_for_type != eLanguageTypeUnknown) { + languages_to_check.insert(language_for_type); + } else { + languages_to_check = Language::GetSupportedLanguages(); + } - if (tdecl) { - clang_ast_type.SetCompilerType( - ClangASTContext::GetASTContext(&tdecl->getASTContext()), - reinterpret_cast<lldb::opaque_compiler_type_t>( - const_cast<clang::Type *>(tdecl->getTypeForDecl()))); + std::set<CompilerType> user_defined_types; + for (auto lang : languages_to_check) { + if (auto *persistent_vars = + target->GetPersistentExpressionStateForLanguage(lang)) { + if (llvm::Optional<CompilerType> type = + persistent_vars->GetCompilerTypeFromPersistentDecl( + lookup_type_name)) { + user_defined_types.emplace(*type); + } } } + + if (user_defined_types.size() > 1) { + result.AppendErrorWithFormat( + "Mutiple types found matching raw type '%s', please disambiguate " + "by specifying the language with -x", + lookup_type_name.GetCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (user_defined_types.size() == 1) { + compiler_type = *user_defined_types.begin(); + } } - if (!clang_ast_type.IsValid()) { + if (!compiler_type.IsValid()) { if (type_list.GetSize() == 0) { result.AppendErrorWithFormat("unable to find any types that match " "the raw type '%s' for full type '%s'\n", @@ -503,14 +527,14 @@ return false; } else { TypeSP type_sp(type_list.GetTypeAtIndex(0)); - clang_ast_type = type_sp->GetFullCompilerType(); + compiler_type = type_sp->GetFullCompilerType(); } } while (pointer_count > 0) { - CompilerType pointer_type = clang_ast_type.GetPointerType(); + CompilerType pointer_type = compiler_type.GetPointerType(); if (pointer_type.IsValid()) - clang_ast_type = pointer_type; + compiler_type = pointer_type; else { result.AppendError("unable make a pointer type\n"); result.SetStatus(eReturnStatusFailed); @@ -519,7 +543,7 @@ --pointer_count; } - llvm::Optional<uint64_t> size = clang_ast_type.GetByteSize(nullptr); + llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr); if (!size) { result.AppendErrorWithFormat( "unable to get the byte size of the type '%s'\n", @@ -549,7 +573,7 @@ // options have been set addr = m_next_addr; total_byte_size = m_prev_byte_size; - clang_ast_type = m_prev_clang_ast_type; + compiler_type = m_prev_compiler_type; if (!m_format_options.AnyOptionWasSet() && !m_memory_options.AnyOptionWasSet() && !m_outfile_options.AnyOptionWasSet() && @@ -636,13 +660,13 @@ DataBufferSP data_sp; size_t bytes_read = 0; - if (clang_ast_type.GetOpaqueQualType()) { + if (compiler_type.GetOpaqueQualType()) { // Make sure we don't display our type as ASCII bytes like the default // memory read if (!m_format_options.GetFormatValue().OptionWasSet()) m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault); - llvm::Optional<uint64_t> size = clang_ast_type.GetByteSize(nullptr); + llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr); if (!size) { result.AppendError("can't get size of type"); return false; @@ -653,7 +677,7 @@ addr = addr + (*size * m_memory_options.m_offset.GetCurrentValue()); } else if (m_format_options.GetFormatValue().GetCurrentValue() != eFormatCString) { - data_sp.reset(new DataBufferHeap(total_byte_size, '\0')); + data_sp = std::make_shared<DataBufferHeap>(total_byte_size, '\0'); if (data_sp->GetBytes() == nullptr) { result.AppendErrorWithFormat( "can't allocate 0x%" PRIx32 @@ -693,8 +717,9 @@ item_byte_size = target->GetMaximumSizeOfStringSummary(); if (!m_format_options.GetCountValue().OptionWasSet()) item_count = 1; - data_sp.reset(new DataBufferHeap((item_byte_size + 1) * item_count, - '\0')); // account for NULLs as necessary + data_sp = std::make_shared<DataBufferHeap>( + (item_byte_size + 1) * item_count, + '\0'); // account for NULLs as necessary if (data_sp->GetBytes() == nullptr) { result.AppendErrorWithFormat( "can't allocate 0x%" PRIx64 @@ -741,7 +766,8 @@ if (break_on_no_NULL) break; } - data_sp.reset(new DataBufferHeap(data_sp->GetBytes(), bytes_read + 1)); + data_sp = + std::make_shared<DataBufferHeap>(data_sp->GetBytes(), bytes_read + 1); } m_next_addr = addr + bytes_read; @@ -750,7 +776,7 @@ m_prev_memory_options = m_memory_options; m_prev_outfile_options = m_outfile_options; m_prev_varobj_options = m_varobj_options; - m_prev_clang_ast_type = clang_ast_type; + m_prev_compiler_type = compiler_type; StreamFile outfile_stream; Stream *output_stream = nullptr; @@ -800,14 +826,14 @@ } ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope(); - if (clang_ast_type.GetOpaqueQualType()) { + if (compiler_type.GetOpaqueQualType()) { for (uint32_t i = 0; i < item_count; ++i) { addr_t item_addr = addr + (i * item_byte_size); Address address(item_addr); StreamString name_strm; name_strm.Printf("0x%" PRIx64, item_addr); ValueObjectSP valobj_sp(ValueObjectMemory::Create( - exe_scope, name_strm.GetString(), address, clang_ast_type)); + exe_scope, name_strm.GetString(), address, compiler_type)); if (valobj_sp) { Format format = m_format_options.GetFormat(); if (format != eFormatDefault) @@ -877,7 +903,7 @@ OptionGroupReadMemory m_prev_memory_options; OptionGroupOutputFile m_prev_outfile_options; OptionGroupValueObjectDisplay m_prev_varobj_options; - CompilerType m_prev_clang_ast_type; + CompilerType m_prev_compiler_type; }; static constexpr OptionDefinition g_memory_find_option_table[] = { @@ -889,9 +915,7 @@ // clang-format on }; -//---------------------------------------------------------------------- // Find the specified data in memory -//---------------------------------------------------------------------- class CommandObjectMemoryFind : public CommandObjectParsed { public: class OptionGroupFindMemory : public OptionGroup { @@ -1186,9 +1210,7 @@ // clang-format on }; -//---------------------------------------------------------------------- // Write memory to the inferior process -//---------------------------------------------------------------------- class CommandObjectMemoryWrite : public CommandObjectParsed { public: class OptionGroupWriteMemory : public OptionGroup { @@ -1595,9 +1617,7 @@ OptionGroupWriteMemory m_memory_options; }; -//---------------------------------------------------------------------- // Get malloc/free history of a memory address. -//---------------------------------------------------------------------- class CommandObjectMemoryHistory : public CommandObjectParsed { public: CommandObjectMemoryHistory(CommandInterpreter &interpreter) @@ -1677,9 +1697,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectMemoryRegion -//------------------------------------------------------------------------- #pragma mark CommandObjectMemoryRegion class CommandObjectMemoryRegion : public CommandObjectParsed { @@ -1770,9 +1788,7 @@ lldb::addr_t m_prev_end_addr; }; -//------------------------------------------------------------------------- // CommandObjectMemory -//------------------------------------------------------------------------- CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter) : CommandObjectMultiword(
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectMemory.h b/src/llvm-project/lldb/source/Commands/CommandObjectMemory.h index 0fa5251..f94cdf3 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectMemory.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectMemory.h
@@ -1,9 +1,8 @@ //===-- CommandObjectMemory.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectMultiword.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectMultiword.cpp index 64c4f66..4011cce 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectMultiword.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectMultiword.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectMultiword.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectMultiword -//------------------------------------------------------------------------- CommandObjectMultiword::CommandObjectMultiword(CommandInterpreter &interpreter, const char *name,
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.cpp index fc442f5..53549cd 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectPlatform.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -154,9 +153,7 @@ DISALLOW_COPY_AND_ASSIGN(OptionPermissions); }; -//---------------------------------------------------------------------- // "platform select <platform-name>" -//---------------------------------------------------------------------- class CommandObjectPlatformSelect : public CommandObjectParsed { public: CommandObjectPlatformSelect(CommandInterpreter &interpreter) @@ -194,8 +191,7 @@ PlatformSP platform_sp(m_platform_options.CreatePlatformWithOptions( m_interpreter, ArchSpec(), select, error, platform_arch)); if (platform_sp) { - m_interpreter.GetDebugger().GetPlatformList().SetSelectedPlatform( - platform_sp); + GetDebugger().GetPlatformList().SetSelectedPlatform(platform_sp); platform_sp->GetStatus(result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); @@ -219,9 +215,7 @@ OptionGroupPlatform m_platform_options; }; -//---------------------------------------------------------------------- // "platform list" -//---------------------------------------------------------------------- class CommandObjectPlatformList : public CommandObjectParsed { public: CommandObjectPlatformList(CommandInterpreter &interpreter) @@ -241,7 +235,7 @@ host_platform_sp->GetDescription()); uint32_t idx; - for (idx = 0; 1; ++idx) { + for (idx = 0; true; ++idx) { const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex(idx); if (plugin_name == nullptr) @@ -262,9 +256,7 @@ } }; -//---------------------------------------------------------------------- // "platform status" -//---------------------------------------------------------------------- class CommandObjectPlatformStatus : public CommandObjectParsed { public: CommandObjectPlatformStatus(CommandInterpreter &interpreter) @@ -278,14 +270,13 @@ bool DoExecute(Args &args, CommandReturnObject &result) override { Stream &ostrm = result.GetOutputStream(); - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); PlatformSP platform_sp; if (target) { platform_sp = target->GetPlatform(); } if (!platform_sp) { - platform_sp = - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform(); } if (platform_sp) { platform_sp->GetStatus(ostrm); @@ -298,9 +289,7 @@ } }; -//---------------------------------------------------------------------- // "platform connect <connect-url>" -//---------------------------------------------------------------------- class CommandObjectPlatformConnect : public CommandObjectParsed { public: CommandObjectPlatformConnect(CommandInterpreter &interpreter) @@ -316,15 +305,14 @@ Stream &ostrm = result.GetOutputStream(); PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { Status error(platform_sp->ConnectRemote(args)); if (error.Success()) { platform_sp->GetStatus(ostrm); result.SetStatus(eReturnStatusSuccessFinishResult); - platform_sp->ConnectToWaitingProcesses(m_interpreter.GetDebugger(), - error); + platform_sp->ConnectToWaitingProcesses(GetDebugger(), error); if (error.Fail()) { result.AppendError(error.AsCString()); result.SetStatus(eReturnStatusFailed); @@ -342,7 +330,7 @@ Options *GetOptions() override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); OptionGroupOptions *m_platform_options = nullptr; if (platform_sp) { m_platform_options = platform_sp->GetConnectionOptions(m_interpreter); @@ -353,9 +341,7 @@ } }; -//---------------------------------------------------------------------- // "platform disconnect" -//---------------------------------------------------------------------- class CommandObjectPlatformDisconnect : public CommandObjectParsed { public: CommandObjectPlatformDisconnect(CommandInterpreter &interpreter) @@ -368,7 +354,7 @@ protected: bool DoExecute(Args &args, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { if (args.GetArgumentCount() == 0) { Status error; @@ -415,9 +401,7 @@ } }; -//---------------------------------------------------------------------- // "platform settings" -//---------------------------------------------------------------------- class CommandObjectPlatformSettings : public CommandObjectParsed { public: CommandObjectPlatformSettings(CommandInterpreter &interpreter) @@ -437,7 +421,7 @@ protected: bool DoExecute(Args &args, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { if (m_option_working_dir.GetOptionValue().OptionWasSet()) platform_sp->SetWorkingDirectory( @@ -460,9 +444,7 @@ OptionGroupFile m_option_working_dir; }; -//---------------------------------------------------------------------- // "platform mkdir" -//---------------------------------------------------------------------- class CommandObjectPlatformMkDir : public CommandObjectParsed { public: CommandObjectPlatformMkDir(CommandInterpreter &interpreter) @@ -475,7 +457,7 @@ bool DoExecute(Args &args, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { std::string cmd_line; args.GetCommandString(cmd_line); @@ -512,9 +494,7 @@ OptionGroupOptions m_options; }; -//---------------------------------------------------------------------- // "platform fopen" -//---------------------------------------------------------------------- class CommandObjectPlatformFOpen : public CommandObjectParsed { public: CommandObjectPlatformFOpen(CommandInterpreter &interpreter) @@ -526,7 +506,7 @@ bool DoExecute(Args &args, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { Status error; std::string cmd_line; @@ -569,9 +549,7 @@ OptionGroupOptions m_options; }; -//---------------------------------------------------------------------- // "platform fclose" -//---------------------------------------------------------------------- class CommandObjectPlatformFClose : public CommandObjectParsed { public: CommandObjectPlatformFClose(CommandInterpreter &interpreter) @@ -582,7 +560,7 @@ bool DoExecute(Args &args, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { std::string cmd_line; args.GetCommandString(cmd_line); @@ -605,9 +583,7 @@ } }; -//---------------------------------------------------------------------- // "platform fread" -//---------------------------------------------------------------------- static constexpr OptionDefinition g_platform_fread_options[] = { // clang-format off @@ -628,7 +604,7 @@ bool DoExecute(Args &args, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { std::string cmd_line; args.GetCommandString(cmd_line); @@ -700,9 +676,7 @@ CommandOptions m_options; }; -//---------------------------------------------------------------------- // "platform fwrite" -//---------------------------------------------------------------------- static constexpr OptionDefinition g_platform_fwrite_options[] = { // clang-format off @@ -723,7 +697,7 @@ bool DoExecute(Args &args, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { std::string cmd_line; args.GetCommandString(cmd_line); @@ -794,9 +768,7 @@ class CommandObjectPlatformFile : public CommandObjectMultiword { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectPlatformFile(CommandInterpreter &interpreter) : CommandObjectMultiword( interpreter, "platform file", @@ -815,15 +787,11 @@ ~CommandObjectPlatformFile() override = default; private: - //------------------------------------------------------------------ // For CommandObjectPlatform only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformFile); }; -//---------------------------------------------------------------------- // "platform get-file remote-file-path host-file-path" -//---------------------------------------------------------------------- class CommandObjectPlatformGetFile : public CommandObjectParsed { public: CommandObjectPlatformGetFile(CommandInterpreter &interpreter) @@ -874,7 +842,7 @@ } PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { const char *remote_file_path = args.GetArgumentAtIndex(0); const char *local_file_path = args.GetArgumentAtIndex(1); @@ -898,9 +866,7 @@ } }; -//---------------------------------------------------------------------- // "platform get-size remote-file-path" -//---------------------------------------------------------------------- class CommandObjectPlatformGetSize : public CommandObjectParsed { public: CommandObjectPlatformGetSize(CommandInterpreter &interpreter) @@ -941,7 +907,7 @@ } PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { std::string remote_file_path(args.GetArgumentAtIndex(0)); user_id_t size = platform_sp->GetFileSize(FileSpec(remote_file_path)); @@ -964,9 +930,7 @@ } }; -//---------------------------------------------------------------------- // "platform put-file" -//---------------------------------------------------------------------- class CommandObjectPlatformPutFile : public CommandObjectParsed { public: CommandObjectPlatformPutFile(CommandInterpreter &interpreter) @@ -986,7 +950,7 @@ FileSpec dst_fs(dst ? dst : src_fs.GetFilename().GetCString()); PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { Status error(platform_sp->PutFile(src_fs, dst_fs)); if (error.Success()) { @@ -1003,9 +967,7 @@ } }; -//---------------------------------------------------------------------- // "platform process launch" -//---------------------------------------------------------------------- class CommandObjectPlatformProcessLaunch : public CommandObjectParsed { public: CommandObjectPlatformProcessLaunch(CommandInterpreter &interpreter) @@ -1021,14 +983,13 @@ protected: bool DoExecute(Args &args, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); PlatformSP platform_sp; if (target) { platform_sp = target->GetPlatform(); } if (!platform_sp) { - platform_sp = - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform(); } if (platform_sp) { @@ -1059,7 +1020,7 @@ } if (m_options.launch_info.GetExecutableFile()) { - Debugger &debugger = m_interpreter.GetDebugger(); + Debugger &debugger = GetDebugger(); if (argc == 0) target->GetRunArguments(m_options.launch_info.GetArguments()); @@ -1093,9 +1054,7 @@ ProcessLaunchCommandOptions m_options; }; -//---------------------------------------------------------------------- // "platform process list" -//---------------------------------------------------------------------- static OptionDefinition g_platform_process_list_options[] = { // clang-format off @@ -1131,14 +1090,13 @@ protected: bool DoExecute(Args &args, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); PlatformSP platform_sp; if (target) { platform_sp = target->GetPlatform(); } if (!platform_sp) { - platform_sp = - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform(); } if (platform_sp) { @@ -1152,10 +1110,9 @@ if (pid != LLDB_INVALID_PROCESS_ID) { ProcessInstanceInfo proc_info; if (platform_sp->GetProcessInfo(pid, proc_info)) { - ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(), - m_options.show_args, + ProcessInstanceInfo::DumpTableHeader(ostrm, m_options.show_args, m_options.verbose); - proc_info.DumpAsTableRow(ostrm, platform_sp.get(), + proc_info.DumpAsTableRow(ostrm, platform_sp->GetUserIDResolver(), m_options.show_args, m_options.verbose); result.SetStatus(eReturnStatusSuccessFinishResult); } else { @@ -1213,13 +1170,12 @@ result.AppendMessageWithFormat(" whose name %s \"%s\"", match_desc, match_name); result.AppendMessageWithFormat("\n"); - ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(), - m_options.show_args, + ProcessInstanceInfo::DumpTableHeader(ostrm, m_options.show_args, m_options.verbose); for (uint32_t i = 0; i < matches; ++i) { proc_infos.GetProcessInfoAtIndex(i).DumpAsTableRow( - ostrm, platform_sp.get(), m_options.show_args, - m_options.verbose); + ostrm, platform_sp->GetUserIDResolver(), + m_options.show_args, m_options.verbose); } } } @@ -1396,9 +1352,7 @@ CommandOptions m_options; }; -//---------------------------------------------------------------------- // "platform process info" -//---------------------------------------------------------------------- class CommandObjectPlatformProcessInfo : public CommandObjectParsed { public: CommandObjectPlatformProcessInfo(CommandInterpreter &interpreter) @@ -1425,14 +1379,13 @@ protected: bool DoExecute(Args &args, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); PlatformSP platform_sp; if (target) { platform_sp = target->GetPlatform(); } if (!platform_sp) { - platform_sp = - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform(); } if (platform_sp) { @@ -1454,7 +1407,7 @@ if (platform_sp->GetProcessInfo(pid, proc_info)) { ostrm.Printf("Process information for process %" PRIu64 ":\n", pid); - proc_info.Dump(ostrm, platform_sp.get()); + proc_info.Dump(ostrm, platform_sp->GetUserIDResolver()); } else { ostrm.Printf("error: no process information is available for " "process %" PRIu64 "\n", @@ -1608,11 +1561,11 @@ bool DoExecute(Args &command, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { Status err; ProcessSP remote_process_sp = platform_sp->Attach( - m_options.attach_info, m_interpreter.GetDebugger(), nullptr, err); + m_options.attach_info, GetDebugger(), nullptr, err); if (err.Fail()) { result.AppendError(err.AsCString()); result.SetStatus(eReturnStatusFailed); @@ -1636,9 +1589,7 @@ class CommandObjectPlatformProcess : public CommandObjectMultiword { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectPlatformProcess(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "platform process", "Commands to query, launch and attach to " @@ -1659,15 +1610,11 @@ ~CommandObjectPlatformProcess() override = default; private: - //------------------------------------------------------------------ // For CommandObjectPlatform only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformProcess); }; -//---------------------------------------------------------------------- // "platform shell" -//---------------------------------------------------------------------- static constexpr OptionDefinition g_platform_shell_options[] = { // clang-format off { LLDB_OPT_SET_ALL, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeValue, "Seconds to wait for the remote host to finish running the command." }, @@ -1746,7 +1693,7 @@ return false; PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); Status error; if (platform_sp) { FileSpec working_dir{}; @@ -1791,9 +1738,7 @@ CommandOptions m_options; }; -//---------------------------------------------------------------------- // "platform install" - install a target to a remote end -//---------------------------------------------------------------------- class CommandObjectPlatformInstall : public CommandObjectParsed { public: CommandObjectPlatformInstall(CommandInterpreter &interpreter) @@ -1820,7 +1765,7 @@ return false; } PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); if (!platform_sp) { result.AppendError("no platform currently selected"); result.SetStatus(eReturnStatusFailed);
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.h b/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.h index e15df5a..c94d2ea2 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectPlatform.h
@@ -1,9 +1,8 @@ //===-- CommandObjectPlatform.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectPlatform -//------------------------------------------------------------------------- class CommandObjectPlatform : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.cpp index 2e805ba..89e01ba 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectPlugin.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -62,7 +61,7 @@ FileSpec dylib_fspec(command[0].ref); FileSystem::Instance().Resolve(dylib_fspec); - if (m_interpreter.GetDebugger().LoadPlugin(dylib_fspec, error)) + if (GetDebugger().LoadPlugin(dylib_fspec, error)) result.SetStatus(eReturnStatusSuccessFinishResult); else { result.AppendError(error.AsCString());
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.h b/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.h index cd39eb1..0aabb13 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectPlugin.h
@@ -1,9 +1,8 @@ //===-- CommandObjectPlugin.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectProcess.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectProcess.cpp index 5b0e6d7..b20a2d5 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectProcess.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectProcess.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectProcess.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -101,9 +100,7 @@ std::string m_new_process_action; }; -//------------------------------------------------------------------------- // CommandObjectProcessLaunch -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessLaunch class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach { public: @@ -150,7 +147,7 @@ protected: bool DoExecute(Args &launch_args, CommandReturnObject &result) override { - Debugger &debugger = m_interpreter.GetDebugger(); + Debugger &debugger = GetDebugger(); Target *target = debugger.GetSelectedTarget().get(); // If our listener is nullptr, users aren't allows to launch ModuleSP exe_module_sp = target->GetExecutableModule(); @@ -196,7 +193,10 @@ if (target->GetDisableSTDIO()) m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO); - m_options.launch_info.GetEnvironment() = target->GetEnvironment(); + // Merge the launch info environment with the target environment. + Environment target_env = target->GetEnvironment(); + m_options.launch_info.GetEnvironment().insert(target_env.begin(), + target_env.end()); if (!target_settings_argv0.empty()) { m_options.launch_info.GetArguments().AppendArgument( @@ -255,51 +255,6 @@ ProcessLaunchCommandOptions m_options; }; -//#define SET1 LLDB_OPT_SET_1 -//#define SET2 LLDB_OPT_SET_2 -//#define SET3 LLDB_OPT_SET_3 -// -// OptionDefinition -// CommandObjectProcessLaunch::CommandOptions::g_option_table[] = -//{ -// // clang-format off -// {SET1 | SET2 | SET3, false, "stop-at-entry", 's', OptionParser::eNoArgument, -// nullptr, 0, eArgTypeNone, "Stop at the entry point of the program -// when launching a process."}, -// {SET1, false, "stdin", 'i', -// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, -// "Redirect stdin for the process to <path>."}, -// {SET1, false, "stdout", 'o', -// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, -// "Redirect stdout for the process to <path>."}, -// {SET1, false, "stderr", 'e', -// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, -// "Redirect stderr for the process to <path>."}, -// {SET1 | SET2 | SET3, false, "plugin", 'p', -// OptionParser::eRequiredArgument, nullptr, 0, eArgTypePlugin, "Name of -// the process plugin you want to use."}, -// { SET2, false, "tty", 't', -// OptionParser::eOptionalArgument, nullptr, 0, eArgTypeDirectoryName, "Start -// the process in a terminal. If <path> is specified, look for a terminal whose -// name contains <path>, else start the process in a new terminal."}, -// { SET3, false, "no-stdio", 'n', OptionParser::eNoArgument, -// nullptr, 0, eArgTypeNone, "Do not set up for terminal I/O to go to -// running process."}, -// {SET1 | SET2 | SET3, false, "working-dir", 'w', -// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, "Set the -// current working directory to <path> when running the inferior."}, -// {0, false, nullptr, 0, 0, nullptr, 0, eArgTypeNone, nullptr} -// // clang-format on -//}; -// -//#undef SET1 -//#undef SET2 -//#undef SET3 - -//------------------------------------------------------------------------- -// CommandObjectProcessAttach -//------------------------------------------------------------------------- - static constexpr OptionDefinition g_process_attach_options[] = { // clang-format off { LLDB_OPT_SET_ALL, false, "continue", 'c', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Immediately continue the process once attached." }, @@ -435,9 +390,9 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { PlatformSP platform_sp( - m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + GetDebugger().GetPlatformList().GetSelectedPlatform()); - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); // N.B. The attach should be synchronous. It doesn't help much to get the // prompt back between initiating the attach and the target actually // stopping. So even if the interpreter is set to be asynchronous, we wait @@ -454,8 +409,8 @@ TargetSP new_target_sp; Status error; - error = m_interpreter.GetDebugger().GetTargetList().CreateTarget( - m_interpreter.GetDebugger(), "", "", eLoadDependentsNo, + error = GetDebugger().GetTargetList().CreateTarget( + GetDebugger(), "", "", eLoadDependentsNo, nullptr, // No platform options new_target_sp); target = new_target_sp.get(); @@ -463,7 +418,7 @@ result.AppendError(error.AsCString("Error creating target")); return false; } - m_interpreter.GetDebugger().GetTargetList().SetSelectedTarget(target); + GetDebugger().GetTargetList().SetSelectedTarget(target); } // Record the old executable module, we want to issue a warning if the @@ -548,9 +503,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectProcessContinue -//------------------------------------------------------------------------- static constexpr OptionDefinition g_process_continue_options[] = { // clang-format off @@ -712,9 +665,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectProcessDetach -//------------------------------------------------------------------------- static constexpr OptionDefinition g_process_detach_options[] = { // clang-format off { LLDB_OPT_SET_1, false, "keep-stopped", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Whether or not the process should be kept stopped on detach (if possible)." }, @@ -810,9 +761,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectProcessConnect -//------------------------------------------------------------------------- static constexpr OptionDefinition g_process_connect_options[] = { // clang-format off @@ -900,7 +849,7 @@ plugin_name = m_options.plugin_name.c_str(); Status error; - Debugger &debugger = m_interpreter.GetDebugger(); + Debugger &debugger = GetDebugger(); PlatformSP platform_sp = m_interpreter.GetPlatform(true); ProcessSP process_sp = platform_sp->ConnectProcess( command.GetArgumentAtIndex(0), plugin_name, debugger, @@ -916,9 +865,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectProcessPlugin -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessPlugin class CommandObjectProcessPlugin : public CommandObjectProxy { @@ -939,9 +886,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectProcessLoad -//------------------------------------------------------------------------- static constexpr OptionDefinition g_process_load_options[] = { // clang-format off @@ -1055,9 +1000,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectProcessUnload -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessUnload class CommandObjectProcessUnload : public CommandObjectParsed { @@ -1103,9 +1046,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectProcessSignal -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessSignal class CommandObjectProcessSignal : public CommandObjectParsed { @@ -1170,9 +1111,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectProcessInterrupt -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessInterrupt class CommandObjectProcessInterrupt : public CommandObjectParsed { @@ -1214,9 +1153,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectProcessKill -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessKill class CommandObjectProcessKill : public CommandObjectParsed { @@ -1257,9 +1194,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectProcessSaveCore -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessSaveCore class CommandObjectProcessSaveCore : public CommandObjectParsed { @@ -1303,9 +1238,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectProcessStatus -//------------------------------------------------------------------------- #pragma mark CommandObjectProcessStatus class CommandObjectProcessStatus : public CommandObjectParsed { @@ -1337,9 +1270,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectProcessHandle -//------------------------------------------------------------------------- static constexpr OptionDefinition g_process_handle_options[] = { // clang-format off @@ -1489,7 +1420,7 @@ protected: bool DoExecute(Args &signal_args, CommandReturnObject &result) override { - TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); + TargetSP target_sp = GetDebugger().GetSelectedTarget(); if (!target_sp) { result.AppendError("No current target;" @@ -1596,9 +1527,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectMultiwordProcess -//------------------------------------------------------------------------- CommandObjectMultiwordProcess::CommandObjectMultiwordProcess( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectProcess.h b/src/llvm-project/lldb/source/Commands/CommandObjectProcess.h index 7325dce..3b1ff26 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectProcess.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectProcess.h
@@ -1,9 +1,8 @@ //===-- CommandObjectProcess.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordProcess -//------------------------------------------------------------------------- class CommandObjectMultiwordProcess : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectQuit.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectQuit.cpp index 2c5b20b..70ee336 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectQuit.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectQuit.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectQuit.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,9 +16,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectQuit -//------------------------------------------------------------------------- CommandObjectQuit::CommandObjectQuit(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "quit", "Quit the LLDB debugger.",
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectQuit.h b/src/llvm-project/lldb/source/Commands/CommandObjectQuit.h index 0f9da62..458ef24 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectQuit.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectQuit.h
@@ -1,9 +1,8 @@ //===-- CommandObjectQuit.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectQuit -//------------------------------------------------------------------------- class CommandObjectQuit : public CommandObjectParsed { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectRegister.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectRegister.cpp index ae8b5d0..34482a8 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectRegister.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectRegister.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectRegister.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,9 +31,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // "register read" -//---------------------------------------------------------------------- static constexpr OptionDefinition g_register_read_options[] = { // clang-format off @@ -299,9 +296,7 @@ CommandOptions m_command_options; }; -//---------------------------------------------------------------------- // "register write" -//---------------------------------------------------------------------- class CommandObjectRegisterWrite : public CommandObjectParsed { public: CommandObjectRegisterWrite(CommandInterpreter &interpreter) @@ -394,9 +389,7 @@ } }; -//---------------------------------------------------------------------- // CommandObjectRegister constructor -//---------------------------------------------------------------------- CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "register", "Commands to access registers for the current "
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectRegister.h b/src/llvm-project/lldb/source/Commands/CommandObjectRegister.h index 96fc47a..6fc47cf 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectRegister.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectRegister.h
@@ -1,9 +1,8 @@ //===-- CommandObjectRegister.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,23 +13,17 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectRegister -//------------------------------------------------------------------------- class CommandObjectRegister : public CommandObjectMultiword { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectRegister(CommandInterpreter &interpreter); ~CommandObjectRegister() override; private: - //------------------------------------------------------------------ // For CommandObjectRegister only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(CommandObjectRegister); };
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.cpp index f393f17..4b0e9e3 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectReproducer.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,8 +21,12 @@ class CommandObjectReproducerGenerate : public CommandObjectParsed { public: CommandObjectReproducerGenerate(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "reproducer generate", - "Generate reproducer on disk.", nullptr) {} + : CommandObjectParsed( + interpreter, "reproducer generate", + "Generate reproducer on disk. When the debugger is in capture " + "mode, this command will output the reproducer to a directory on " + "disk. In replay mode this command in a no-op.", + nullptr) {} ~CommandObjectReproducerGenerate() override = default; @@ -38,13 +41,21 @@ auto &r = repro::Reproducer::Instance(); if (auto generator = r.GetGenerator()) { generator->Keep(); + } else if (r.GetLoader()) { + // Make this operation a NOP in replay mode. + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); } else { result.AppendErrorWithFormat("Unable to get the reproducer generator"); + result.SetStatus(eReturnStatusFailed); return false; } result.GetOutputStream() << "Reproducer written to '" << r.GetReproducerPath() << "'\n"; + result.GetOutputStream() + << "Please have a look at the directory to assess if you're willing to " + "share the contained information.\n"; result.SetStatus(eReturnStatusSuccessFinishResult); return result.Succeeded(); @@ -54,8 +65,14 @@ class CommandObjectReproducerStatus : public CommandObjectParsed { public: CommandObjectReproducerStatus(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "reproducer status", - "Show the current reproducer status.", nullptr) {} + : CommandObjectParsed( + interpreter, "reproducer status", + "Show the current reproducer status. In capture mode the debugger " + "is collecting all the information it needs to create a " + "reproducer. In replay mode the reproducer is replaying a " + "reproducer. When the reproducers are off, no data is collected " + "and no reproducer can be generated.", + nullptr) {} ~CommandObjectReproducerStatus() override = default; @@ -68,12 +85,11 @@ } auto &r = repro::Reproducer::Instance(); - if (auto generator = r.GetGenerator()) { + if (r.GetGenerator()) { result.GetOutputStream() << "Reproducer is in capture mode.\n"; - } else if (auto generator = r.GetLoader()) { + } else if (r.GetLoader()) { result.GetOutputStream() << "Reproducer is in replay mode.\n"; } else { - result.GetOutputStream() << "Reproducer is off.\n"; } @@ -84,9 +100,10 @@ CommandObjectReproducer::CommandObjectReproducer( CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "reproducer", - "Commands controlling LLDB reproducers.", - "log <subcommand> [<command-options>]") { + : CommandObjectMultiword( + interpreter, "reproducer", + "Commands to inspect and manipulate the reproducer functionality.", + "log <subcommand> [<command-options>]") { LoadSubCommand( "generate", CommandObjectSP(new CommandObjectReproducerGenerate(interpreter)));
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.h b/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.h index 6691e8a..ad37724 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectReproducer.h
@@ -1,9 +1,8 @@ //===-- CommandObjectReproducer.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectReproducer -//------------------------------------------------------------------------- class CommandObjectReproducer : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectSettings.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectSettings.cpp index 967a009..55a0002 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectSettings.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectSettings.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectSettings.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,15 +19,11 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectSettingsSet -//------------------------------------------------------------------------- static constexpr OptionDefinition g_settings_set_options[] = { - // clang-format off - { LLDB_OPT_SET_2, false, "global", 'g', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Apply the new value to the global default value." }, - { LLDB_OPT_SET_2, false, "force", 'f', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Force an empty value to be accepted as the default." } - // clang-format on +#define LLDB_OPTIONS_settings_set +#include "CommandOptions.inc" }; class CommandObjectSettingsSet : public CommandObjectRaw { @@ -164,9 +159,8 @@ const char *setting_var_name = request.GetParsedLine().GetArgumentAtIndex(setting_var_idx); Status error; - lldb::OptionValueSP value_sp( - m_interpreter.GetDebugger().GetPropertyValue( - &m_exe_ctx, setting_var_name, false, error)); + lldb::OptionValueSP value_sp(GetDebugger().GetPropertyValue( + &m_exe_ctx, setting_var_name, false, error)); if (value_sp) { value_sp->AutoComplete(m_interpreter, request); } @@ -205,7 +199,7 @@ // A missing value corresponds to clearing the setting when "force" is // specified. if (argc == 1 && m_options.m_force) { - Status error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationClear, var_name, llvm::StringRef())); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -223,8 +217,8 @@ Status error; if (m_options.m_global) { - error = m_interpreter.GetDebugger().SetPropertyValue( - nullptr, eVarSetOperationAssign, var_name, var_value_cstr); + error = GetDebugger().SetPropertyValue(nullptr, eVarSetOperationAssign, + var_name, var_value_cstr); } if (error.Success()) { @@ -235,8 +229,8 @@ // if we did not clear the command's exe_ctx first ExecutionContext exe_ctx(m_exe_ctx); m_exe_ctx.Clear(); - error = m_interpreter.GetDebugger().SetPropertyValue( - &exe_ctx, eVarSetOperationAssign, var_name, var_value_cstr); + error = GetDebugger().SetPropertyValue(&exe_ctx, eVarSetOperationAssign, + var_name, var_value_cstr); } if (error.Fail()) { @@ -254,9 +248,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectSettingsShow -- Show current values -//------------------------------------------------------------------------- class CommandObjectSettingsShow : public CommandObjectParsed { public: @@ -297,7 +289,7 @@ if (!args.empty()) { for (const auto &arg : args) { - Status error(m_interpreter.GetDebugger().DumpPropertyValue( + Status error(GetDebugger().DumpPropertyValue( &m_exe_ctx, result.GetOutputStream(), arg.ref, OptionValue::eDumpGroupValue)); if (error.Success()) { @@ -308,23 +300,19 @@ } } } else { - m_interpreter.GetDebugger().DumpAllPropertyValues( - &m_exe_ctx, result.GetOutputStream(), OptionValue::eDumpGroupValue); + GetDebugger().DumpAllPropertyValues(&m_exe_ctx, result.GetOutputStream(), + OptionValue::eDumpGroupValue); } return result.Succeeded(); } }; -//------------------------------------------------------------------------- // CommandObjectSettingsWrite -- Write settings to file -//------------------------------------------------------------------------- static constexpr OptionDefinition g_settings_write_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, true, "file", 'f', OptionParser::eRequiredArgument, nullptr, {}, CommandCompletions::eDiskFileCompletion, eArgTypeFilename, "The file into which to write the settings." }, - { LLDB_OPT_SET_ALL, false, "append",'a', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Append to saved settings file if it exists."}, - // clang-format on +#define LLDB_OPTIONS_settings_write +#include "CommandOptions.inc" }; class CommandObjectSettingsWrite : public CommandObjectParsed { @@ -422,13 +410,13 @@ ExecutionContext clean_ctx; if (args.empty()) { - m_interpreter.GetDebugger().DumpAllPropertyValues( - &clean_ctx, out_file, OptionValue::eDumpGroupExport); + GetDebugger().DumpAllPropertyValues(&clean_ctx, out_file, + OptionValue::eDumpGroupExport); return result.Succeeded(); } for (const auto &arg : args) { - Status error(m_interpreter.GetDebugger().DumpPropertyValue( + Status error(GetDebugger().DumpPropertyValue( &clean_ctx, out_file, arg.ref, OptionValue::eDumpGroupExport)); if (!error.Success()) { result.AppendError(error.AsCString()); @@ -443,14 +431,11 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectSettingsRead -- Read settings from file -//------------------------------------------------------------------------- static constexpr OptionDefinition g_settings_read_options[] = { - // clang-format off - {LLDB_OPT_SET_ALL, true, "file",'f', OptionParser::eRequiredArgument, nullptr, {}, CommandCompletions::eDiskFileCompletion, eArgTypeFilename, "The file from which to read the breakpoints." }, - // clang-format on +#define LLDB_OPTIONS_settings_read +#include "CommandOptions.inc" }; class CommandObjectSettingsRead : public CommandObjectParsed { @@ -511,6 +496,7 @@ options.SetAddToHistory(false); options.SetEchoCommands(false); options.SetPrintResults(true); + options.SetPrintErrors(true); options.SetStopOnError(false); m_interpreter.HandleCommandsFromFile(file, &clean_ctx, options, result); return result.Succeeded(); @@ -520,9 +506,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectSettingsList -- List settable variables -//------------------------------------------------------------------------- class CommandObjectSettingsList : public CommandObjectParsed { public: @@ -576,7 +560,7 @@ const char *property_path = args.GetArgumentAtIndex(i); const Property *property = - m_interpreter.GetDebugger().GetValueProperties()->GetPropertyAtPath( + GetDebugger().GetValueProperties()->GetPropertyAtPath( &m_exe_ctx, will_modify, property_path); if (property) { @@ -589,17 +573,15 @@ } } } else { - m_interpreter.GetDebugger().DumpAllDescriptions(m_interpreter, - result.GetOutputStream()); + GetDebugger().DumpAllDescriptions(m_interpreter, + result.GetOutputStream()); } return result.Succeeded(); } }; -//------------------------------------------------------------------------- // CommandObjectSettingsRemove -//------------------------------------------------------------------------- class CommandObjectSettingsRemove : public CommandObjectRaw { public: @@ -685,7 +667,7 @@ const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Status error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationRemove, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -697,9 +679,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectSettingsReplace -//------------------------------------------------------------------------- class CommandObjectSettingsReplace : public CommandObjectRaw { public: @@ -787,7 +767,7 @@ const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Status error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationReplace, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -801,9 +781,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectSettingsInsertBefore -//------------------------------------------------------------------------- class CommandObjectSettingsInsertBefore : public CommandObjectRaw { public: @@ -895,7 +873,7 @@ const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Status error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationInsertBefore, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -907,9 +885,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectSettingInsertAfter -//------------------------------------------------------------------------- class CommandObjectSettingsInsertAfter : public CommandObjectRaw { public: @@ -1000,7 +976,7 @@ const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Status error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationInsertAfter, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -1012,9 +988,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectSettingsAppend -//------------------------------------------------------------------------- class CommandObjectSettingsAppend : public CommandObjectRaw { public: @@ -1096,7 +1070,7 @@ const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Status error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationAppend, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -1108,9 +1082,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectSettingsClear -//------------------------------------------------------------------------- class CommandObjectSettingsClear : public CommandObjectParsed { public: @@ -1166,7 +1138,7 @@ return false; } - Status error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationClear, var_name, llvm::StringRef())); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -1178,9 +1150,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectMultiwordSettings -//------------------------------------------------------------------------- CommandObjectMultiwordSettings::CommandObjectMultiwordSettings( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectSettings.h b/src/llvm-project/lldb/source/Commands/CommandObjectSettings.h index df13386..7304259 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectSettings.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectSettings.h
@@ -1,9 +1,8 @@ //===-- CommandObjectSettings.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordSettings -//------------------------------------------------------------------------- class CommandObjectMultiwordSettings : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectSource.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectSource.cpp index 2fce34f..1b515d0 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectSource.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectSource.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectSource.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,9 +32,7 @@ using namespace lldb_private; #pragma mark CommandObjectSourceInfo -//---------------------------------------------------------------------- // CommandObjectSourceInfo - debug line entries dumping command -//---------------------------------------------------------------------- static constexpr OptionDefinition g_source_info_options[] = { // clang-format off @@ -195,7 +192,7 @@ continue; // Print a new header if the module changed. - const ConstString &module_file_name = + ConstString module_file_name = module->GetFileSpec().GetFilename(); assert(module_file_name); if (module_file_name != last_module_file_name) { @@ -241,8 +238,8 @@ // Dump all matching lines at or above start_line for the file in the // CU. - const ConstString &file_spec_name = file_spec.GetFilename(); - const ConstString &module_file_name = + ConstString file_spec_name = file_spec.GetFilename(); + ConstString module_file_name = module->GetFileSpec().GetFilename(); bool cu_header_printed = false; uint32_t line = start_line; @@ -575,7 +572,7 @@ Target *target = m_exe_ctx.GetTargetPtr(); if (target == nullptr) { - target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command."); @@ -645,9 +642,7 @@ }; #pragma mark CommandObjectSourceList -//------------------------------------------------------------------------- // CommandObjectSourceList -//------------------------------------------------------------------------- static constexpr OptionDefinition g_source_list_options[] = { // clang-format off @@ -781,7 +776,7 @@ ConstString function; LineEntry line_entry; - SourceInfo(const ConstString &name, const LineEntry &line_entry) + SourceInfo(ConstString name, const LineEntry &line_entry) : function(name), line_entry(line_entry) {} SourceInfo() : function(), line_entry() {} @@ -902,7 +897,7 @@ // these somewhere, there should probably be a module-filter-list that can be // passed to the various ModuleList::Find* calls, which would either be a // vector of string names or a ModuleSpecList. - size_t FindMatchingFunctions(Target *target, const ConstString &name, + size_t FindMatchingFunctions(Target *target, ConstString name, SymbolContextList &sc_list) { // Displaying the source for a symbol: bool include_inlines = true; @@ -935,7 +930,7 @@ return num_matches; } - size_t FindMatchingFunctionSymbols(Target *target, const ConstString &name, + size_t FindMatchingFunctionSymbols(Target *target, ConstString name, SymbolContextList &sc_list) { size_t num_matches = 0; const size_t num_modules = m_options.modules.size(); @@ -1137,8 +1132,7 @@ m_options.num_lines >= 10 ? 5 : m_options.num_lines / 2; const uint32_t column = - (m_interpreter.GetDebugger().GetStopShowColumn() != - eStopShowColumnNone) + (GetDebugger().GetStopShowColumn() != eStopShowColumnNone) ? sc.line_entry.column : 0; target->GetSourceManager().DisplaySourceLinesWithLineNumbers( @@ -1293,9 +1287,7 @@ }; #pragma mark CommandObjectMultiwordSource -//------------------------------------------------------------------------- // CommandObjectMultiwordSource -//------------------------------------------------------------------------- CommandObjectMultiwordSource::CommandObjectMultiwordSource( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectSource.h b/src/llvm-project/lldb/source/Commands/CommandObjectSource.h index b255383..d72122d 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectSource.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectSource.h
@@ -1,10 +1,9 @@ //===-- CommandObjectSource.h.h -----------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,9 +16,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordSource -//------------------------------------------------------------------------- class CommandObjectMultiwordSource : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectStats.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectStats.cpp index 9225a94..a73c2a8 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectStats.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectStats.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectStats.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectStats.h b/src/llvm-project/lldb/source/Commands/CommandObjectStats.h index 3c5c2c0..27e9a6f 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectStats.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectStats.h
@@ -1,9 +1,8 @@ //===-- CommandObjectStats.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectTarget.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectTarget.cpp index ee55b22..e913a28 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectTarget.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectTarget.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectTarget.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,7 +17,6 @@ #include "lldb/DataFormatters/ValueObjectPrinter.h" #include "lldb/Host/OptionParser.h" #include "lldb/Host/StringConvert.h" -#include "lldb/Host/Symbols.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/OptionArgParser.h" @@ -36,6 +34,7 @@ #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/FuncUnwinders.h" #include "lldb/Symbol/LineTable.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/SymbolVendor.h" @@ -202,9 +201,7 @@ #pragma mark CommandObjectTargetCreate -//------------------------------------------------------------------------- // "target create" -//------------------------------------------------------------------------- class CommandObjectTargetCreate : public CommandObjectParsed { public: @@ -317,7 +314,7 @@ bool must_set_platform_path = false; - Debugger &debugger = m_interpreter.GetDebugger(); + Debugger &debugger = GetDebugger(); TargetSP target_sp; llvm::StringRef arch_cstr = m_arch_option.GetArchitectureName(); @@ -396,7 +393,8 @@ debugger.GetTargetList().SetSelectedTarget(target_sp.get()); if (must_set_platform_path) { ModuleSpec main_module_spec(file_spec); - ModuleSP module_sp = target_sp->GetSharedModule(main_module_spec); + ModuleSP module_sp = target_sp->GetOrCreateModule(main_module_spec, + true /* notify */); if (module_sp) module_sp->SetPlatformFileSpec(remote_file); } @@ -412,11 +410,10 @@ } FileSpec core_file_dir; core_file_dir.GetDirectory() = core_file.GetDirectory(); - target_sp->GetExecutableSearchPaths().Append(core_file_dir); + target_sp->AppendExecutableSearchPaths(core_file_dir); ProcessSP process_sp(target_sp->CreateProcess( - m_interpreter.GetDebugger().GetListener(), llvm::StringRef(), - &core_file)); + GetDebugger().GetListener(), llvm::StringRef(), &core_file)); if (process_sp) { // Seems weird that we Launch a core file, but that is what we @@ -476,9 +473,7 @@ #pragma mark CommandObjectTargetList -//---------------------------------------------------------------------- // "target list" -//---------------------------------------------------------------------- class CommandObjectTargetList : public CommandObjectParsed { public: @@ -496,7 +491,7 @@ Stream &strm = result.GetOutputStream(); bool show_stopped_process_status = false; - if (DumpTargetList(m_interpreter.GetDebugger().GetTargetList(), + if (DumpTargetList(GetDebugger().GetTargetList(), show_stopped_process_status, strm) == 0) { strm.PutCString("No targets.\n"); } @@ -511,9 +506,7 @@ #pragma mark CommandObjectTargetSelect -//---------------------------------------------------------------------- // "target select" -//---------------------------------------------------------------------- class CommandObjectTargetSelect : public CommandObjectParsed { public: @@ -533,7 +526,7 @@ uint32_t target_idx = StringConvert::ToUInt32(target_idx_arg, UINT32_MAX, 0, &success); if (success) { - TargetList &target_list = m_interpreter.GetDebugger().GetTargetList(); + TargetList &target_list = GetDebugger().GetTargetList(); const uint32_t num_targets = target_list.GetNumTargets(); if (target_idx < num_targets) { TargetSP target_sp(target_list.GetTargetAtIndex(target_idx)); @@ -576,9 +569,7 @@ #pragma mark CommandObjectTargetSelect -//---------------------------------------------------------------------- // "target delete" -//---------------------------------------------------------------------- class CommandObjectTargetDelete : public CommandObjectParsed { public: @@ -611,7 +602,7 @@ bool DoExecute(Args &args, CommandReturnObject &result) override { const size_t argc = args.GetArgumentCount(); std::vector<TargetSP> delete_target_list; - TargetList &target_list = m_interpreter.GetDebugger().GetTargetList(); + TargetList &target_list = GetDebugger().GetTargetList(); TargetSP target_sp; if (m_all_option.GetOptionValue()) { @@ -689,9 +680,7 @@ #pragma mark CommandObjectTargetVariable -//---------------------------------------------------------------------- // "target variable" -//---------------------------------------------------------------------- class CommandObjectTargetVariable : public CommandObjectParsed { static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file' @@ -1064,7 +1053,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target) { const size_t argc = command.GetArgumentCount(); if (argc & 1) { @@ -1118,7 +1107,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target) { bool notify = true; target->GetImageSearchPathList().Clear(notify); @@ -1179,7 +1168,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target) { size_t argc = command.GetArgumentCount(); // check for at least 3 arguments and an odd number of parameters @@ -1247,7 +1236,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target) { if (command.GetArgumentCount() != 0) { result.AppendError("list takes no arguments\n"); @@ -1293,7 +1282,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target) { if (command.GetArgumentCount() != 1) { result.AppendError("query requires one argument\n"); @@ -1317,9 +1306,7 @@ } }; -//---------------------------------------------------------------------- // Static Helper functions -//---------------------------------------------------------------------- static void DumpModuleArchitecture(Stream &strm, Module *module, bool full_triple, uint32_t width) { if (module) { @@ -1348,7 +1335,7 @@ static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter, Stream &strm, Module *module, const FileSpec &file_spec, - bool load_addresses) { + lldb::DescriptionLevel desc_level) { uint32_t num_matches = 0; if (module) { SymbolContextList sc_list; @@ -1367,7 +1354,7 @@ if (line_table) line_table->GetDescription( &strm, interpreter.GetExecutionContext().GetTargetPtr(), - lldb::eDescriptionLevelBrief); + desc_level); else strm << "No line table"; } @@ -1829,10 +1816,8 @@ #pragma mark CommandObjectTargetModulesModuleAutoComplete -//---------------------------------------------------------------------- // A base command object class that can auto complete with module file // paths -//---------------------------------------------------------------------- class CommandObjectTargetModulesModuleAutoComplete : public CommandObjectParsed { @@ -1871,10 +1856,8 @@ #pragma mark CommandObjectTargetModulesSourceFileAutoComplete -//---------------------------------------------------------------------- // A base command object class that can auto complete with module source // file paths -//---------------------------------------------------------------------- class CommandObjectTargetModulesSourceFileAutoComplete : public CommandObjectParsed { @@ -1925,7 +1908,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -1984,9 +1967,8 @@ {eSortOrderByName, "name", "Sort output by symbol name."} }; static constexpr OptionDefinition g_target_modules_dump_symtab_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "sort", 's', OptionParser::eRequiredArgument, nullptr, OptionEnumValues(g_sort_option_enumeration), 0, eArgTypeSortOrder, "Supply a sort order when dumping the symbol table." } - // clang-format on +#define LLDB_OPTIONS_target_modules_dump_symtab +#include "CommandOptions.inc" }; class CommandObjectTargetModulesDumpSymtab @@ -2041,7 +2023,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -2126,9 +2108,7 @@ #pragma mark CommandObjectTargetModulesDumpSections -//---------------------------------------------------------------------- // Image section dumping command -//---------------------------------------------------------------------- class CommandObjectTargetModulesDumpSections : public CommandObjectTargetModulesModuleAutoComplete { @@ -2144,7 +2124,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -2221,9 +2201,7 @@ #pragma mark CommandObjectTargetModulesDumpSections -//---------------------------------------------------------------------- // Clang AST dumping command -//---------------------------------------------------------------------- class CommandObjectTargetModulesDumpClangAST : public CommandObjectTargetModulesModuleAutoComplete { @@ -2239,7 +2217,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -2300,9 +2278,7 @@ #pragma mark CommandObjectTargetModulesDumpSymfile -//---------------------------------------------------------------------- // Image debug symbol dumping command -//---------------------------------------------------------------------- class CommandObjectTargetModulesDumpSymfile : public CommandObjectTargetModulesModuleAutoComplete { @@ -2318,7 +2294,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -2391,9 +2367,7 @@ #pragma mark CommandObjectTargetModulesDumpLineTable -//---------------------------------------------------------------------- // Image debug line table dumping command -//---------------------------------------------------------------------- class CommandObjectTargetModulesDumpLineTable : public CommandObjectTargetModulesSourceFileAutoComplete { @@ -2406,6 +2380,8 @@ ~CommandObjectTargetModulesDumpLineTable() override = default; + Options *GetOptions() override { return &m_options; } + protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Target *target = m_exe_ctx.GetTargetPtr(); @@ -2438,8 +2414,9 @@ if (DumpCompileUnitLineTable( m_interpreter, result.GetOutputStream(), target_modules.GetModulePointerAtIndexUnlocked(i), - file_spec, m_exe_ctx.GetProcessPtr() && - m_exe_ctx.GetProcessRef().IsAlive())) + file_spec, + m_options.m_verbose ? eDescriptionLevelFull + : eDescriptionLevelBrief)) num_dumped++; } if (num_dumped == 0) @@ -2459,19 +2436,52 @@ } return result.Succeeded(); } + + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } + + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + assert(option_idx == 0 && "We only have one option."); + m_verbose = true; + + return Status(); + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_verbose = false; + } + + llvm::ArrayRef<OptionDefinition> GetDefinitions() override { + static constexpr OptionDefinition g_options[] = { + {LLDB_OPT_SET_ALL, + false, + "verbose", + 'v', + OptionParser::eNoArgument, + nullptr, + {}, + 0, + eArgTypeNone, + "Enable verbose dump."}, + }; + return llvm::makeArrayRef(g_options); + } + + bool m_verbose; + }; + + CommandOptions m_options; }; #pragma mark CommandObjectTargetModulesDump -//---------------------------------------------------------------------- // Dump multi-word command for target modules -//---------------------------------------------------------------------- class CommandObjectTargetModulesDump : public CommandObjectMultiword { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectTargetModulesDump(CommandInterpreter &interpreter) : CommandObjectMultiword( interpreter, "target modules dump", @@ -2539,7 +2549,7 @@ OptionGroupFile m_symbol_file; bool DoExecute(Args &args, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -2559,7 +2569,8 @@ module_spec.GetSymbolFileSpec() = m_symbol_file.GetOptionValue().GetCurrentValue(); if (Symbols::DownloadObjectAndSymbolFile(module_spec)) { - ModuleSP module_sp(target->GetSharedModule(module_spec)); + ModuleSP module_sp(target->GetOrCreateModule(module_spec, + true /* notify */)); if (module_sp) { result.SetStatus(eReturnStatusSuccessFinishResult); return true; @@ -2621,7 +2632,8 @@ if (!module_spec.GetArchitecture().IsValid()) module_spec.GetArchitecture() = target->GetArchitecture(); Status error; - ModuleSP module_sp(target->GetSharedModule(module_spec, &error)); + ModuleSP module_sp(target->GetOrCreateModule(module_spec, + true /* notify */, &error)); if (!module_sp) { const char *error_cstr = error.AsCString(); if (error_cstr) @@ -2700,7 +2712,7 @@ protected: bool DoExecute(Args &args, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); const bool load = m_load_option.GetOptionValue().GetCurrentValue(); const bool set_pc = m_pc_option.GetOptionValue().GetCurrentValue(); if (target == nullptr) { @@ -2955,9 +2967,7 @@ OptionGroupUInt64 m_slide_option; }; -//---------------------------------------------------------------------- // List images with associated information -//---------------------------------------------------------------------- static constexpr OptionDefinition g_target_modules_list_options[] = { // clang-format off @@ -3037,7 +3047,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); const bool use_global_module_list = m_options.m_use_global_module_list; // Define a local module list here to ensure it lives longer than any // "locker" object which might lock its contents below (through the @@ -3321,9 +3331,7 @@ #pragma mark CommandObjectTargetModulesShowUnwind -//---------------------------------------------------------------------- // Lookup unwind information in images -//---------------------------------------------------------------------- static constexpr OptionDefinition g_target_modules_show_unwind_options[] = { // clang-format off @@ -3494,8 +3502,7 @@ start_addr = abi->FixCodeAddress(start_addr); FuncUnwindersSP func_unwinders_sp( - sc.module_sp->GetObjectFile() - ->GetUnwindTable() + sc.module_sp->GetUnwindTable() .GetUncachedFuncUnwindersContainingAddress(start_addr, sc)); if (!func_unwinders_sp) continue; @@ -3506,14 +3513,14 @@ funcname.AsCString(), start_addr); UnwindPlanSP non_callsite_unwind_plan = - func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread, -1); + func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread); if (non_callsite_unwind_plan) { result.GetOutputStream().Printf( "Asynchronous (not restricted to call-sites) UnwindPlan is '%s'\n", non_callsite_unwind_plan->GetSourceName().AsCString()); } UnwindPlanSP callsite_unwind_plan = - func_unwinders_sp->GetUnwindPlanAtCallSite(*target, -1); + func_unwinders_sp->GetUnwindPlanAtCallSite(*target, *thread); if (callsite_unwind_plan) { result.GetOutputStream().Printf( "Synchronous (restricted to call-sites) UnwindPlan is '%s'\n", @@ -3530,7 +3537,7 @@ result.GetOutputStream().Printf("\n"); UnwindPlanSP assembly_sp = - func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread, 0); + func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread); if (assembly_sp) { result.GetOutputStream().Printf( "Assembly language inspection UnwindPlan:\n"); @@ -3540,7 +3547,7 @@ } UnwindPlanSP ehframe_sp = - func_unwinders_sp->GetEHFrameUnwindPlan(*target, 0); + func_unwinders_sp->GetEHFrameUnwindPlan(*target); if (ehframe_sp) { result.GetOutputStream().Printf("eh_frame UnwindPlan:\n"); ehframe_sp->Dump(result.GetOutputStream(), thread.get(), @@ -3549,7 +3556,7 @@ } UnwindPlanSP ehframe_augmented_sp = - func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread, 0); + func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread); if (ehframe_augmented_sp) { result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n"); ehframe_augmented_sp->Dump(result.GetOutputStream(), thread.get(), @@ -3558,7 +3565,7 @@ } if (UnwindPlanSP plan_sp = - func_unwinders_sp->GetDebugFrameUnwindPlan(*target, 0)) { + func_unwinders_sp->GetDebugFrameUnwindPlan(*target)) { result.GetOutputStream().Printf("debug_frame UnwindPlan:\n"); plan_sp->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); @@ -3567,7 +3574,7 @@ if (UnwindPlanSP plan_sp = func_unwinders_sp->GetDebugFrameAugmentedUnwindPlan(*target, - *thread, 0)) { + *thread)) { result.GetOutputStream().Printf("debug_frame augmented UnwindPlan:\n"); plan_sp->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); @@ -3575,7 +3582,7 @@ } UnwindPlanSP arm_unwind_sp = - func_unwinders_sp->GetArmUnwindUnwindPlan(*target, 0); + func_unwinders_sp->GetArmUnwindUnwindPlan(*target); if (arm_unwind_sp) { result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n"); arm_unwind_sp->Dump(result.GetOutputStream(), thread.get(), @@ -3583,8 +3590,16 @@ result.GetOutputStream().Printf("\n"); } + if (UnwindPlanSP symfile_plan_sp = + func_unwinders_sp->GetSymbolFileUnwindPlan(*thread)) { + result.GetOutputStream().Printf("Symbol file UnwindPlan:\n"); + symfile_plan_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + UnwindPlanSP compact_unwind_sp = - func_unwinders_sp->GetCompactUnwindUnwindPlan(*target, 0); + func_unwinders_sp->GetCompactUnwindUnwindPlan(*target); if (compact_unwind_sp) { result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n"); compact_unwind_sp->Dump(result.GetOutputStream(), thread.get(), @@ -3627,9 +3642,7 @@ CommandOptions m_options; }; -//---------------------------------------------------------------------- // Lookup information in images -//---------------------------------------------------------------------- static constexpr OptionDefinition g_target_modules_lookup_options[] = { // clang-format off @@ -3726,7 +3739,7 @@ break; case 'v': - m_verbose = 1; + m_verbose = true; break; case 'A': @@ -3922,7 +3935,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -4015,9 +4028,7 @@ #pragma mark CommandObjectMultiwordImageSearchPaths -//------------------------------------------------------------------------- // CommandObjectMultiwordImageSearchPaths -//------------------------------------------------------------------------- class CommandObjectTargetModulesImageSearchPaths : public CommandObjectMultiword { @@ -4050,15 +4061,11 @@ #pragma mark CommandObjectTargetModules -//------------------------------------------------------------------------- // CommandObjectTargetModules -//------------------------------------------------------------------------- class CommandObjectTargetModules : public CommandObjectMultiword { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectTargetModules(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "target modules", "Commands for accessing information for one or " @@ -4087,9 +4094,7 @@ ~CommandObjectTargetModules() override = default; private: - //------------------------------------------------------------------ // For CommandObjectTargetModules only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetModules); }; @@ -4482,15 +4487,11 @@ #pragma mark CommandObjectTargetSymbols -//------------------------------------------------------------------------- // CommandObjectTargetSymbols -//------------------------------------------------------------------------- class CommandObjectTargetSymbols : public CommandObjectMultiword { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CommandObjectTargetSymbols(CommandInterpreter &interpreter) : CommandObjectMultiword( interpreter, "target symbols", @@ -4503,21 +4504,17 @@ ~CommandObjectTargetSymbols() override = default; private: - //------------------------------------------------------------------ // For CommandObjectTargetModules only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetSymbols); }; #pragma mark CommandObjectTargetStopHookAdd -//------------------------------------------------------------------------- // CommandObjectTargetStopHookAdd -//------------------------------------------------------------------------- static constexpr OptionDefinition g_target_stop_hook_add_options[] = { // clang-format off - { LLDB_OPT_SET_ALL, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner, "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." }, + { LLDB_OPT_SET_ALL, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner, "Add a command for the stop hook. Can be specified more than once, and commands will be run in the order they appear." }, { LLDB_OPT_SET_ALL, false, "shlib", 's', OptionParser::eRequiredArgument, nullptr, {}, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Set the module within which the stop-hook is to be run." }, { LLDB_OPT_SET_ALL, false, "thread-index", 'x', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeThreadIndex, "The stop hook is run only for the thread whose index matches this argument." }, { LLDB_OPT_SET_ALL, false, "thread-id", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeThreadID, "The stop hook is run only for the thread whose TID matches this argument." }, @@ -4528,6 +4525,7 @@ { LLDB_OPT_SET_1, false, "end-line", 'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLineNum, "Set the end of the line range for which the stop-hook is to be run." }, { LLDB_OPT_SET_2, false, "classname", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeClassName, "Specify the class within which the stop-hook is to be run." }, { LLDB_OPT_SET_3, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, {}, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Set the function name within which the stop hook will be run." }, + { LLDB_OPT_SET_ALL, false, "auto-continue",'G', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "The breakpoint will auto-continue after running its commands." }, // clang-format on }; @@ -4568,6 +4566,17 @@ m_sym_ctx_specified = true; break; + case 'G': { + bool value, success; + value = OptionArgParser::ToBoolean(option_arg, false, &success); + if (success) { + m_auto_continue = value; + } else + error.SetErrorStringWithFormat( + "invalid boolean value '%s' passed for -G option", + option_arg.str().c_str()); + } + break; case 'l': if (option_arg.getAsInteger(0, m_line_start)) { error.SetErrorStringWithFormat("invalid start line number: \"%s\"", @@ -4623,7 +4632,7 @@ case 'o': m_use_one_liner = true; - m_one_liner = option_arg; + m_one_liner.push_back(option_arg); break; default: @@ -4652,6 +4661,7 @@ m_use_one_liner = false; m_one_liner.clear(); + m_auto_continue = false; } std::string m_class_name; @@ -4670,7 +4680,8 @@ bool m_thread_specified; // Instance variables to hold the values for one_liner options. bool m_use_one_liner; - std::string m_one_liner; + std::vector<std::string> m_one_liner; + bool m_auto_continue; }; CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter) @@ -4686,9 +4697,9 @@ Options *GetOptions() override { return &m_options; } protected: - void IOHandlerActivated(IOHandler &io_handler) override { + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { + if (output_sp && interactive) { output_sp->PutCString( "Enter your stop hook command(s). Type 'DONE' to end.\n"); output_sp->Flush(); @@ -4706,7 +4717,7 @@ m_stop_hook_sp->GetID()); error_sp->Flush(); } - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target) target->RemoveStopHookByID(m_stop_hook_sp->GetID()); } else { @@ -4731,49 +4742,49 @@ Target::StopHookSP new_hook_sp = target->CreateStopHook(); // First step, make the specifier. - std::unique_ptr<SymbolContextSpecifier> specifier_ap; + std::unique_ptr<SymbolContextSpecifier> specifier_up; if (m_options.m_sym_ctx_specified) { - specifier_ap.reset(new SymbolContextSpecifier( - m_interpreter.GetDebugger().GetSelectedTarget())); + specifier_up.reset( + new SymbolContextSpecifier(GetDebugger().GetSelectedTarget())); if (!m_options.m_module_name.empty()) { - specifier_ap->AddSpecification( + specifier_up->AddSpecification( m_options.m_module_name.c_str(), SymbolContextSpecifier::eModuleSpecified); } if (!m_options.m_class_name.empty()) { - specifier_ap->AddSpecification( + specifier_up->AddSpecification( m_options.m_class_name.c_str(), SymbolContextSpecifier::eClassOrNamespaceSpecified); } if (!m_options.m_file_name.empty()) { - specifier_ap->AddSpecification( + specifier_up->AddSpecification( m_options.m_file_name.c_str(), SymbolContextSpecifier::eFileSpecified); } if (m_options.m_line_start != 0) { - specifier_ap->AddLineSpecification( + specifier_up->AddLineSpecification( m_options.m_line_start, SymbolContextSpecifier::eLineStartSpecified); } if (m_options.m_line_end != UINT_MAX) { - specifier_ap->AddLineSpecification( + specifier_up->AddLineSpecification( m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified); } if (!m_options.m_function_name.empty()) { - specifier_ap->AddSpecification( + specifier_up->AddSpecification( m_options.m_function_name.c_str(), SymbolContextSpecifier::eFunctionSpecified); } } - if (specifier_ap) - new_hook_sp->SetSpecifier(specifier_ap.release()); + if (specifier_up) + new_hook_sp->SetSpecifier(specifier_up.release()); // Next see if any of the thread options have been entered: @@ -4795,10 +4806,13 @@ new_hook_sp->SetThreadSpecifier(thread_spec); } + + new_hook_sp->SetAutoContinue(m_options.m_auto_continue); if (m_options.m_use_one_liner) { - // Use one-liner. - new_hook_sp->GetCommandPointer()->AppendString( - m_options.m_one_liner.c_str()); + // Use one-liners. + for (auto cmd : m_options.m_one_liner) + new_hook_sp->GetCommandPointer()->AppendString( + cmd.c_str()); result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n", new_hook_sp->GetID()); } else { @@ -4826,9 +4840,7 @@ #pragma mark CommandObjectTargetStopHookDelete -//------------------------------------------------------------------------- // CommandObjectTargetStopHookDelete -//------------------------------------------------------------------------- class CommandObjectTargetStopHookDelete : public CommandObjectParsed { public: @@ -4884,9 +4896,7 @@ #pragma mark CommandObjectTargetStopHookEnableDisable -//------------------------------------------------------------------------- // CommandObjectTargetStopHookEnableDisable -//------------------------------------------------------------------------- class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed { public: @@ -4941,9 +4951,7 @@ #pragma mark CommandObjectTargetStopHookList -//------------------------------------------------------------------------- // CommandObjectTargetStopHookList -//------------------------------------------------------------------------- class CommandObjectTargetStopHookList : public CommandObjectParsed { public: @@ -4982,9 +4990,7 @@ #pragma mark CommandObjectMultiwordTargetStopHooks -//------------------------------------------------------------------------- // CommandObjectMultiwordTargetStopHooks -//------------------------------------------------------------------------- class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword { public: @@ -5015,9 +5021,7 @@ #pragma mark CommandObjectMultiwordTarget -//------------------------------------------------------------------------- // CommandObjectMultiwordTarget -//------------------------------------------------------------------------- CommandObjectMultiwordTarget::CommandObjectMultiwordTarget( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectTarget.h b/src/llvm-project/lldb/source/Commands/CommandObjectTarget.h index 643ce54..86d554c 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectTarget.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectTarget.h
@@ -1,9 +1,8 @@ //===-- CommandObjectTarget.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordTarget -//------------------------------------------------------------------------- class CommandObjectMultiwordTarget : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectThread.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectThread.cpp index e792887..ed7cf0a 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectThread.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectThread.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectThread.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -38,9 +37,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectIterateOverThreads -//------------------------------------------------------------------------- class CommandObjectIterateOverThreads : public CommandObjectParsed { @@ -239,16 +236,11 @@ bool m_add_return = true; }; -//------------------------------------------------------------------------- // CommandObjectThreadBacktrace -//------------------------------------------------------------------------- static constexpr OptionDefinition g_thread_backtrace_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many frames to display (-1 for all)" }, - { LLDB_OPT_SET_1, false, "start", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeFrameIndex, "Frame in which to start the backtrace" }, - { LLDB_OPT_SET_1, false, "extended", 'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Show the extended backtrace, if available" } - // clang-format on +#define LLDB_OPTIONS_thread_backtrace +#include "CommandOptions.inc" }; class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads { @@ -322,7 +314,10 @@ "indexes can be specified as arguments.\n" "Use the thread-index \"all\" to see all threads.\n" "Use the thread-index \"unique\" to see threads grouped by unique " - "call stacks.", + "call stacks.\n" + "Use 'settings set frame-format' to customize the printing of " + "frames in the backtrace and 'settings set thread-format' to " + "customize the thread header.", nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | @@ -409,16 +404,8 @@ } static constexpr OptionDefinition g_thread_step_scope_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "step-in-avoids-no-debug", 'a', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "A boolean value that sets whether stepping into functions will step over functions with no debug information." }, - { LLDB_OPT_SET_1, false, "step-out-avoids-no-debug", 'A', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "A boolean value, if true stepping out of functions will continue to step out till it hits a function with debug information." }, - { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, {}, 1, eArgTypeCount, "How many times to perform the stepping operation - currently only supported for step-inst and next-inst." }, - { LLDB_OPT_SET_1, false, "end-linenumber", 'e', OptionParser::eRequiredArgument, nullptr, {}, 1, eArgTypeLineNum, "The line at which to stop stepping - defaults to the next line and only supported for step-in and step-over. You can also pass the string 'block' to step to the end of the current block. This is particularly useful in conjunction with --step-target to step through a complex calling sequence." }, - { LLDB_OPT_SET_1, false, "run-mode", 'm', OptionParser::eRequiredArgument, nullptr, TriRunningModes(), 0, eArgTypeRunMode, "Determine how to run other threads while stepping the current thread." }, - { LLDB_OPT_SET_1, false, "step-over-regexp", 'r', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeRegularExpression, "A regular expression that defines function names to not to stop at when stepping in." }, - { LLDB_OPT_SET_1, false, "step-in-target", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeFunctionName, "The name of the directly called function step in should stop at when stepping into." }, - { LLDB_OPT_SET_2, false, "python-class", 'C', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePythonClass, "The name of the class that will manage this step - only supported for Scripted Step." } - // clang-format on +#define LLDB_OPTIONS_thread_step_scope +#include "CommandOptions.inc" }; class CommandObjectThreadStepWithTypeAndScope : public CommandObjectParsed { @@ -484,7 +471,7 @@ case 'e': if (option_arg == "block") { - m_end_line_is_block_end = 1; + m_end_line_is_block_end = true; break; } if (option_arg.getAsInteger(0, m_end_line)) @@ -617,7 +604,7 @@ result.AppendErrorWithFormat("empty class name for scripted step."); result.SetStatus(eReturnStatusFailed); return false; - } else if (!m_interpreter.GetScriptInterpreter()->CheckObjectExists( + } else if (!GetDebugger().GetScriptInterpreter()->CheckObjectExists( m_options.m_class_name.c_str())) { result.AppendErrorWithFormat( "class for scripted step: \"%s\" does not exist.", @@ -808,9 +795,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectThreadContinue -//------------------------------------------------------------------------- class CommandObjectThreadContinue : public CommandObjectParsed { public: @@ -843,7 +828,7 @@ bool DoExecute(Args &command, CommandReturnObject &result) override { bool synchronous_execution = m_interpreter.GetSynchronous(); - if (!m_interpreter.GetDebugger().GetSelectedTarget()) { + if (!GetDebugger().GetSelectedTarget()) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); result.SetStatus(eReturnStatusFailed); @@ -988,9 +973,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectThreadUntil -//------------------------------------------------------------------------- static constexpr OptionEnumValueElement g_duo_running_mode[] = { {eOnlyThisThread, "this-thread", "Run only this thread"}, @@ -1001,12 +984,8 @@ } static constexpr OptionDefinition g_thread_until_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "frame", 'f', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeFrameIndex, "Frame index for until operation - defaults to 0" }, - { LLDB_OPT_SET_1, false, "thread", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeThreadIndex, "Thread index for the thread for until operation" }, - { LLDB_OPT_SET_1, false, "run-mode",'m', OptionParser::eRequiredArgument, nullptr, DuoRunningModes(), 0, eArgTypeRunMode, "Determine how to run other threads while stepping this one" }, - { LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeAddressOrExpression, "Run until we reach the specified address, or leave the function - can be specified multiple times." } - // clang-format on +#define LLDB_OPTIONS_thread_until +#include "CommandOptions.inc" }; class CommandObjectThreadUntil : public CommandObjectParsed { @@ -1125,7 +1104,7 @@ bool DoExecute(Args &command, CommandReturnObject &result) override { bool synchronous_execution = m_interpreter.GetSynchronous(); - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("invalid target, create a debug target using the " "'target create' command"); @@ -1329,9 +1308,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectThreadSelect -//------------------------------------------------------------------------- class CommandObjectThreadSelect : public CommandObjectParsed { public: @@ -1392,16 +1369,16 @@ } }; -//------------------------------------------------------------------------- // CommandObjectThreadList -//------------------------------------------------------------------------- class CommandObjectThreadList : public CommandObjectParsed { public: CommandObjectThreadList(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "thread list", - "Show a summary of each thread in the current target process.", + "Show a summary of each thread in the current target process. " + "Use 'settings set thread-format' to customize the individual " + "thread listings.", "thread list", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {} @@ -1424,15 +1401,11 @@ } }; -//------------------------------------------------------------------------- // CommandObjectThreadInfo -//------------------------------------------------------------------------- static constexpr OptionDefinition g_thread_info_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "json", 'j', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Display the thread info in JSON format." }, - { LLDB_OPT_SET_ALL, false, "stop-info", 's', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Display the extended stop info in JSON format." } - // clang-format on +#define LLDB_OPTIONS_thread_info +#include "CommandOptions.inc" }; class CommandObjectThreadInfo : public CommandObjectIterateOverThreads { @@ -1519,9 +1492,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectThreadException -//------------------------------------------------------------------------- class CommandObjectThreadException : public CommandObjectIterateOverThreads { public: @@ -1564,14 +1535,11 @@ } }; -//------------------------------------------------------------------------- // CommandObjectThreadReturn -//------------------------------------------------------------------------- static constexpr OptionDefinition g_thread_return_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "from-expression", 'x', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Return from the innermost expression evaluation." } - // clang-format on +#define LLDB_OPTIONS_thread_return +#include "CommandOptions.inc" }; class CommandObjectThreadReturn : public CommandObjectRaw { @@ -1742,18 +1710,11 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectThreadJump -//------------------------------------------------------------------------- static constexpr OptionDefinition g_thread_jump_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, {}, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "Specifies the source file to jump to." }, - { LLDB_OPT_SET_1, true, "line", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLineNum, "Specifies the line number to jump to." }, - { LLDB_OPT_SET_2, true, "by", 'b', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOffset, "Jumps by a relative line offset from the current line." }, - { LLDB_OPT_SET_3, true, "address", 'a', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeAddressOrExpression, "Jumps to a specific address." }, - { LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Allows the PC to leave the current function." } - // clang-format on +#define LLDB_OPTIONS_thread_jump +#include "CommandOptions.inc" }; class CommandObjectThreadJump : public CommandObjectParsed { @@ -1890,19 +1851,13 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // Next are the subcommands of CommandObjectMultiwordThreadPlan -//------------------------------------------------------------------------- -//------------------------------------------------------------------------- // CommandObjectThreadPlanList -//------------------------------------------------------------------------- static constexpr OptionDefinition g_thread_plan_list_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Display more information about the thread plans" }, - { LLDB_OPT_SET_1, false, "internal", 'i', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Display internal as well as user thread plans" } - // clang-format on +#define LLDB_OPTIONS_thread_plan_list +#include "CommandOptions.inc" }; class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads { @@ -2062,9 +2017,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectMultiwordThreadPlan -//------------------------------------------------------------------------- class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword { public: @@ -2083,9 +2036,7 @@ ~CommandObjectMultiwordThreadPlan() override = default; }; -//------------------------------------------------------------------------- // CommandObjectMultiwordThread -//------------------------------------------------------------------------- CommandObjectMultiwordThread::CommandObjectMultiwordThread( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectThread.h b/src/llvm-project/lldb/source/Commands/CommandObjectThread.h index 5da31cec..77729ce 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectThread.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectThread.h
@@ -1,9 +1,8 @@ //===-- CommandObjectThread.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectType.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectType.cpp index 815e563..98a43f5 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectType.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectType.cpp
@@ -1,18 +1,13 @@ //===-- CommandObjectType.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "CommandObjectType.h" -#include <algorithm> -#include <cctype> -#include <functional> - #include "lldb/Core/Debugger.h" #include "lldb/Core/IOHandler.h" #include "lldb/DataFormatters/DataVisualization.h" @@ -40,6 +35,11 @@ #include "llvm/ADT/STLExtras.h" +#include <algorithm> +#include <cctype> +#include <functional> +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -52,7 +52,7 @@ std::string m_category; ScriptAddOptions(const TypeSummaryImpl::Flags &flags, bool regx, - const ConstString &name, std::string catg) + ConstString name, std::string catg) : m_flags(flags), m_regex(regx), m_name(name), m_category(catg) {} typedef std::shared_ptr<ScriptAddOptions> SharedPointer; @@ -96,23 +96,8 @@ } static constexpr OptionDefinition g_type_summary_add_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Add this to the given category instead of the default one." }, - { LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "If true, cascade through typedef chains." }, - { LLDB_OPT_SET_ALL, false, "no-value", 'v', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't show the value, just show the summary, for this type." }, - { LLDB_OPT_SET_ALL, false, "skip-pointers", 'p', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for pointers-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "skip-references", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for references-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "regex", 'x', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Type names are actually regular expressions." }, - { LLDB_OPT_SET_1, true, "inline-children", 'c', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "If true, inline all child values into summary string." }, - { LLDB_OPT_SET_1, false, "omit-names", 'O', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "If true, omit value names in the summary display." }, - { LLDB_OPT_SET_2, true, "summary-string", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeSummaryString, "Summary string used to display text and object contents." }, - { LLDB_OPT_SET_3, false, "python-script", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePythonScript, "Give a one-liner Python script as part of the command." }, - { LLDB_OPT_SET_3, false, "python-function", 'F', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePythonFunction, "Give the name of a Python function to use for this type." }, - { LLDB_OPT_SET_3, false, "input-python", 'P', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Input Python code to use for this type manually." }, - { LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "expand", 'e', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Expand aggregate data types to show children on separate lines." }, - { LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "hide-empty", 'h', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Do not expand aggregate data types with no children." }, - { LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "A name for this summary string." } - // clang-format on +#define LLDB_OPTIONS_type_summary_add +#include "CommandOptions.inc" }; class CommandObjectTypeSummaryAdd : public CommandObjectParsed, @@ -160,7 +145,7 @@ ~CommandObjectTypeSummaryAdd() override = default; - void IOHandlerActivated(IOHandler &io_handler) override { + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { static const char *g_summary_addreader_instructions = "Enter your Python command(s). Type 'DONE' to end.\n" "def function (valobj,internal_dict):\n" @@ -169,7 +154,7 @@ " internal_dict: an LLDB support object not to be used\"\"\"\n"; StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { + if (output_sp && interactive) { output_sp->PutCString(g_summary_addreader_instructions); output_sp->Flush(); } @@ -180,7 +165,7 @@ StreamFileSP error_sp = io_handler.GetErrorStreamFile(); #ifndef LLDB_DISABLE_PYTHON - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter) { StringList lines; lines.SplitIntoLines(data); @@ -192,7 +177,7 @@ options_ptr); // this will ensure that we get rid of the pointer // when going out of scope - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter) { std::string funct_name_str; if (interpreter->GenerateTypeScriptFunction(lines, @@ -206,9 +191,9 @@ // for every type in the list TypeSummaryImplSP script_format; - script_format.reset(new ScriptSummaryFormat( + script_format = std::make_shared<ScriptSummaryFormat>( options->m_flags, funct_name_str.c_str(), - lines.CopyList(" ").c_str())); + lines.CopyList(" ").c_str()); Status error; @@ -298,15 +283,8 @@ "class synthProvider:\n"; static constexpr OptionDefinition g_type_synth_add_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "If true, cascade through typedef chains." }, - { LLDB_OPT_SET_ALL, false, "skip-pointers", 'p', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for pointers-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "skip-references", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for references-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Add this to the given category instead of the default one." }, - { LLDB_OPT_SET_2, false, "python-class", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePythonClass, "Use this Python class to produce synthetic children." }, - { LLDB_OPT_SET_3, false, "input-python", 'P', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Type Python code to generate a class that provides synthetic children." }, - { LLDB_OPT_SET_ALL, false, "regex", 'x', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Type names are actually regular expressions." } - // clang-format on +#define LLDB_OPTIONS_type_synth_add +#include "CommandOptions.inc" }; class CommandObjectTypeSynthAdd : public CommandObjectParsed, @@ -412,9 +390,9 @@ } } - void IOHandlerActivated(IOHandler &io_handler) override { + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { + if (output_sp && interactive) { output_sp->PutCString(g_synth_addreader_instructions); output_sp->Flush(); } @@ -425,7 +403,7 @@ StreamFileSP error_sp = io_handler.GetErrorStreamFile(); #ifndef LLDB_DISABLE_PYTHON - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter) { StringList lines; lines.SplitIntoLines(data); @@ -437,7 +415,7 @@ options_ptr); // this will ensure that we get rid of the pointer // when going out of scope - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter) { std::string class_name_str; if (interpreter->GenerateTypeSynthClass(lines, class_name_str)) { @@ -450,12 +428,12 @@ // class SyntheticChildrenSP synth_provider; - synth_provider.reset(new ScriptedSyntheticChildren( + synth_provider = std::make_shared<ScriptedSyntheticChildren>( SyntheticChildren::Flags() .SetCascades(options->m_cascade) .SetSkipPointers(options->m_skip_pointers) .SetSkipReferences(options->m_skip_references), - class_name_str.c_str())); + class_name_str.c_str()); lldb::TypeCategoryImplSP category; DataVisualization::Categories::GetCategory( @@ -523,19 +501,11 @@ Status *error); }; -//------------------------------------------------------------------------- // CommandObjectTypeFormatAdd -//------------------------------------------------------------------------- static constexpr OptionDefinition g_type_format_add_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Add this to the given category instead of the default one." }, - { LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "If true, cascade through typedef chains." }, - { LLDB_OPT_SET_ALL, false, "skip-pointers", 'p', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for pointers-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "skip-references", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for references-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "regex", 'x', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Type names are actually regular expressions." }, - { LLDB_OPT_SET_2, false, "type", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Format variables as if they were of this type." } - // clang-format on +#define LLDB_OPTIONS_type_format_add +#include "CommandOptions.inc" }; class CommandObjectTypeFormatAdd : public CommandObjectParsed { @@ -700,18 +670,18 @@ TypeFormatImplSP entry; if (m_command_options.m_custom_type_name.empty()) - entry.reset(new TypeFormatImpl_Format( + entry = std::make_shared<TypeFormatImpl_Format>( format, TypeFormatImpl::Flags() .SetCascades(m_command_options.m_cascade) .SetSkipPointers(m_command_options.m_skip_pointers) - .SetSkipReferences(m_command_options.m_skip_references))); + .SetSkipReferences(m_command_options.m_skip_references)); else - entry.reset(new TypeFormatImpl_EnumType( + entry = std::make_shared<TypeFormatImpl_EnumType>( ConstString(m_command_options.m_custom_type_name.c_str()), TypeFormatImpl::Flags() .SetCascades(m_command_options.m_cascade) .SetSkipPointers(m_command_options.m_skip_pointers) - .SetSkipReferences(m_command_options.m_skip_references))); + .SetSkipReferences(m_command_options.m_skip_references)); // now I have a valid format, let's add it to every type @@ -751,11 +721,8 @@ }; static constexpr OptionDefinition g_type_formatter_delete_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "all", 'a', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Delete from every category." }, - { LLDB_OPT_SET_2, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Delete from given category." }, - { LLDB_OPT_SET_3, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "Delete from given language's category." } - // clang-format on +#define LLDB_OPTIONS_type_formatter_delete +#include "CommandOptions.inc" }; class CommandObjectTypeFormatterDelete : public CommandObjectParsed { @@ -893,9 +860,8 @@ }; static constexpr OptionDefinition g_type_formatter_clear_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "all", 'a', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Clear every category." } - // clang-format on +#define LLDB_OPTIONS_type_formatter_clear +#include "CommandOptions.inc" }; class CommandObjectTypeFormatterClear : public CommandObjectParsed { @@ -980,9 +946,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeFormatDelete -//------------------------------------------------------------------------- class CommandObjectTypeFormatDelete : public CommandObjectTypeFormatterDelete { public: @@ -996,9 +960,7 @@ ~CommandObjectTypeFormatDelete() override = default; }; -//------------------------------------------------------------------------- // CommandObjectTypeFormatClear -//------------------------------------------------------------------------- class CommandObjectTypeFormatClear : public CommandObjectTypeFormatterClear { public: @@ -1011,10 +973,8 @@ static constexpr OptionDefinition g_type_formatter_list_options[] = { - // clang-format off - {LLDB_OPT_SET_1, false, "category-regex", 'w', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Only show categories matching this filter."}, - {LLDB_OPT_SET_2, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "Only show the category for a specific language."} - // clang-format on +#define LLDB_OPTIONS_type_formatter_list +#include "CommandOptions.inc" }; template <typename FormatterType> @@ -1222,9 +1182,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeFormatList -//------------------------------------------------------------------------- class CommandObjectTypeFormatList : public CommandObjectTypeFormatterList<TypeFormatImpl> { @@ -1236,9 +1194,7 @@ #ifndef LLDB_DISABLE_PYTHON -//------------------------------------------------------------------------- // CommandObjectTypeSummaryAdd -//------------------------------------------------------------------------- #endif // LLDB_DISABLE_PYTHON @@ -1353,10 +1309,10 @@ std::string code = (" " + m_options.m_python_function + "(valobj,internal_dict)"); - script_format.reset( - new ScriptSummaryFormat(m_options.m_flags, funct_name, code.c_str())); + script_format = std::make_shared<ScriptSummaryFormat>( + m_options.m_flags, funct_name, code.c_str()); - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter && !interpreter->CheckObjectExists(funct_name)) result.AppendWarningWithFormat( @@ -1366,7 +1322,7 @@ } else if (!m_options.m_python_script .empty()) // we have a quick 1-line script, just use it { - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (!interpreter) { result.AppendError("script interpreter missing - unable to generate " "function wrapper.\n"); @@ -1390,8 +1346,8 @@ std::string code = " " + m_options.m_python_script; - script_format.reset(new ScriptSummaryFormat( - m_options.m_flags, funct_name_str.c_str(), code.c_str())); + script_format = std::make_shared<ScriptSummaryFormat>( + m_options.m_flags, funct_name_str.c_str(), code.c_str()); } else { // Use an IOHandler to grab Python code from the user ScriptAddOptions *options = @@ -1713,9 +1669,7 @@ } } -//------------------------------------------------------------------------- // CommandObjectTypeSummaryDelete -//------------------------------------------------------------------------- class CommandObjectTypeSummaryDelete : public CommandObjectTypeFormatterDelete { public: @@ -1749,9 +1703,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeSummaryList -//------------------------------------------------------------------------- class CommandObjectTypeSummaryList : public CommandObjectTypeFormatterList<TypeSummaryImpl> { @@ -1778,15 +1730,11 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeCategoryDefine -//------------------------------------------------------------------------- static constexpr OptionDefinition g_type_category_define_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "enabled", 'e', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "If specified, this category will be created enabled." }, - { LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "Specify the language that this category is supported for." } - // clang-format on +#define LLDB_OPTIONS_type_category_define +#include "CommandOptions.inc" }; class CommandObjectTypeCategoryDefine : public CommandObjectParsed { @@ -1885,14 +1833,11 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeCategoryEnable -//------------------------------------------------------------------------- static constexpr OptionDefinition g_type_category_enable_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "Enable the category for this language." }, - // clang-format on +#define LLDB_OPTIONS_type_category_enable +#include "CommandOptions.inc" }; class CommandObjectTypeCategoryEnable : public CommandObjectParsed { @@ -2002,9 +1947,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeCategoryDelete -//------------------------------------------------------------------------- class CommandObjectTypeCategoryDelete : public CommandObjectParsed { public: @@ -2062,14 +2005,11 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeCategoryDisable -//------------------------------------------------------------------------- OptionDefinition constexpr g_type_category_disable_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "Enable the category for this language." } - // clang-format on +#define LLDB_OPTIONS_type_category_disable +#include "CommandOptions.inc" }; class CommandObjectTypeCategoryDisable : public CommandObjectParsed { @@ -2174,9 +2114,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeCategoryList -//------------------------------------------------------------------------- class CommandObjectTypeCategoryList : public CommandObjectParsed { public: @@ -2245,9 +2183,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectTypeFilterList -//------------------------------------------------------------------------- class CommandObjectTypeFilterList : public CommandObjectTypeFormatterList<TypeFilterImpl> { @@ -2259,9 +2195,7 @@ #ifndef LLDB_DISABLE_PYTHON -//------------------------------------------------------------------------- // CommandObjectTypeSynthList -//------------------------------------------------------------------------- class CommandObjectTypeSynthList : public CommandObjectTypeFormatterList<SyntheticChildren> { @@ -2274,9 +2208,7 @@ #endif // LLDB_DISABLE_PYTHON -//------------------------------------------------------------------------- // CommandObjectTypeFilterDelete -//------------------------------------------------------------------------- class CommandObjectTypeFilterDelete : public CommandObjectTypeFormatterDelete { public: @@ -2291,9 +2223,7 @@ #ifndef LLDB_DISABLE_PYTHON -//------------------------------------------------------------------------- // CommandObjectTypeSynthDelete -//------------------------------------------------------------------------- class CommandObjectTypeSynthDelete : public CommandObjectTypeFormatterDelete { public: @@ -2309,9 +2239,7 @@ #endif // LLDB_DISABLE_PYTHON -//------------------------------------------------------------------------- // CommandObjectTypeFilterClear -//------------------------------------------------------------------------- class CommandObjectTypeFilterClear : public CommandObjectTypeFormatterClear { public: @@ -2323,9 +2251,7 @@ }; #ifndef LLDB_DISABLE_PYTHON -//------------------------------------------------------------------------- // CommandObjectTypeSynthClear -//------------------------------------------------------------------------- class CommandObjectTypeSynthClear : public CommandObjectTypeFormatterClear { public: @@ -2393,7 +2319,7 @@ entry.reset(impl); - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter(); if (interpreter && !interpreter->CheckObjectExists(impl->GetPythonClassName())) @@ -2491,14 +2417,8 @@ #endif // LLDB_DISABLE_PYTHON static constexpr OptionDefinition g_type_filter_add_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "If true, cascade through typedef chains." }, - { LLDB_OPT_SET_ALL, false, "skip-pointers", 'p', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for pointers-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "skip-references", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Don't use this format for references-to-type objects." }, - { LLDB_OPT_SET_ALL, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Add this to the given category instead of the default one." }, - { LLDB_OPT_SET_ALL, false, "child", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeExpressionPath, "Include this expression path in the synthetic view." }, - { LLDB_OPT_SET_ALL, false, "regex", 'x', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Type names are actually regular expressions." } - // clang-format on +#define LLDB_OPTIONS_type_filter_add +#include "CommandOptions.inc" }; class CommandObjectTypeFilterAdd : public CommandObjectParsed { @@ -2742,14 +2662,10 @@ } }; -//---------------------------------------------------------------------- // "type lookup" -//---------------------------------------------------------------------- static constexpr OptionDefinition g_type_lookup_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "show-help", 'h', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Display available help for types" }, - { LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "Which language's types should the search scope be" } - // clang-format on +#define LLDB_OPTIONS_type_lookup +#include "CommandOptions.inc" }; class CommandObjectTypeLookup : public CommandObjectRaw { @@ -2844,17 +2760,11 @@ return m_cmd_help_long; StreamString stream; - // FIXME: hardcoding languages is not good - lldb::LanguageType languages[] = {eLanguageTypeObjC, - eLanguageTypeC_plus_plus}; - - for (const auto lang_type : languages) { - if (auto language = Language::FindPlugin(lang_type)) { - if (const char *help = language->GetLanguageSpecificTypeLookupHelp()) { - stream.Printf("%s\n", help); - } - } - } + Language::ForEach([&](Language *lang) { + if (const char *help = lang->GetLanguageSpecificTypeLookupHelp()) + stream.Printf("%s\n", help); + return true; + }); m_cmd_help_long = stream.GetString(); return m_cmd_help_long; @@ -2879,10 +2789,6 @@ exe_ctx)) return false; - // TargetSP - // target_sp(GetCommandInterpreter().GetDebugger().GetSelectedTarget()); - // const bool fill_all_in = true; - // ExecutionContext exe_ctx(target_sp.get(), fill_all_in); ExecutionContextScope *best_scope = exe_ctx.GetBestExecutionContextScope(); bool any_found = false; @@ -2894,9 +2800,10 @@ if ((is_global_search = (m_command_options.m_language == eLanguageTypeUnknown))) { - // FIXME: hardcoding languages is not good - languages.push_back(Language::FindPlugin(eLanguageTypeObjC)); - languages.push_back(Language::FindPlugin(eLanguageTypeC_plus_plus)); + Language::ForEach([&](Language *lang) { + languages.push_back(lang); + return true; + }); } else { languages.push_back(Language::FindPlugin(m_command_options.m_language)); } @@ -2994,7 +2901,7 @@ protected: bool DoExecute(llvm::StringRef command, CommandReturnObject &result) override { - TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); + TargetSP target_sp = GetDebugger().GetSelectedTarget(); Thread *thread = GetDefaultThread(); if (!thread) { result.AppendError("no default thread"); @@ -3168,9 +3075,7 @@ ~CommandObjectTypeSummary() override = default; }; -//------------------------------------------------------------------------- // CommandObjectType -//------------------------------------------------------------------------- CommandObjectType::CommandObjectType(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "type",
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectType.h b/src/llvm-project/lldb/source/Commands/CommandObjectType.h index a9223f8..ebb1903 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectType.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectType.h
@@ -1,9 +1,8 @@ //===-- CommandObjectType.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectVersion.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectVersion.cpp index 6155f49..904baf5 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectVersion.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectVersion.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectVersion.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectVersion -//------------------------------------------------------------------------- CommandObjectVersion::CommandObjectVersion(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "version",
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectVersion.h b/src/llvm-project/lldb/source/Commands/CommandObjectVersion.h index d1afafc..30f44ae 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectVersion.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectVersion.h
@@ -1,9 +1,8 @@ //===-- CommandObjectVersion.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectVersion -//------------------------------------------------------------------------- class CommandObjectVersion : public CommandObjectParsed { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.cpp index d2600a4..98e758b 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectWatchpoint.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -143,21 +142,14 @@ return !in_range; } -//------------------------------------------------------------------------- // CommandObjectWatchpointList -//------------------------------------------------------------------------- -//------------------------------------------------------------------------- // CommandObjectWatchpointList::Options -//------------------------------------------------------------------------- #pragma mark List::CommandOptions static constexpr OptionDefinition g_watchpoint_list_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "brief", 'b', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Give a brief description of the watchpoint (no location info)." }, - { LLDB_OPT_SET_2, false, "full", 'f', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Give a full description of the watchpoint and its locations." }, - { LLDB_OPT_SET_3, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Explain everything we know about the watchpoint (for debugging debugger bugs)." } - // clang-format on +#define LLDB_OPTIONS_watchpoint_list +#include "CommandOptions.inc" }; #pragma mark List @@ -230,7 +222,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("Invalid target. No current target or watchpoints."); result.SetStatus(eReturnStatusSuccessFinishNoResult); @@ -296,9 +288,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectWatchpointEnable -//------------------------------------------------------------------------- #pragma mark Enable class CommandObjectWatchpointEnable : public CommandObjectParsed { @@ -320,7 +310,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (!CheckTargetForWatchpointOperations(target, result)) return false; @@ -367,9 +357,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectWatchpointDisable -//------------------------------------------------------------------------- #pragma mark Disable class CommandObjectWatchpointDisable : public CommandObjectParsed { @@ -392,7 +380,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (!CheckTargetForWatchpointOperations(target, result)) return false; @@ -442,9 +430,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectWatchpointDelete -//------------------------------------------------------------------------- #pragma mark Delete class CommandObjectWatchpointDelete : public CommandObjectParsed { @@ -466,7 +452,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (!CheckTargetForWatchpointOperations(target, result)) return false; @@ -518,15 +504,12 @@ } }; -//------------------------------------------------------------------------- // CommandObjectWatchpointIgnore -//------------------------------------------------------------------------- #pragma mark Ignore::CommandOptions static constexpr OptionDefinition g_watchpoint_ignore_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, true, "ignore-count", 'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "Set the number of times this watchpoint is skipped before stopping." } - // clang-format on +#define LLDB_OPTIONS_watchpoint_ignore +#include "CommandOptions.inc" }; class CommandObjectWatchpointIgnore : public CommandObjectParsed { @@ -590,7 +573,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (!CheckTargetForWatchpointOperations(target, result)) return false; @@ -639,16 +622,13 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectWatchpointModify -//------------------------------------------------------------------------- #pragma mark Modify::CommandOptions static constexpr OptionDefinition g_watchpoint_modify_options[] = { - // clang-format off - { LLDB_OPT_SET_ALL, false, "condition", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeExpression, "The watchpoint stops only if this condition expression evaluates to true." } - // clang-format on +#define LLDB_OPTIONS_watchpoint_modify +#include "CommandOptions.inc" }; #pragma mark Modify @@ -719,7 +699,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (!CheckTargetForWatchpointOperations(target, result)) return false; @@ -770,9 +750,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectWatchpointSetVariable -//------------------------------------------------------------------------- #pragma mark SetVariable class CommandObjectWatchpointSetVariable : public CommandObjectParsed { @@ -839,7 +817,7 @@ } bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); StackFrame *frame = m_exe_ctx.GetFramePtr(); // If no argument is present, issue an error message. There's no way to @@ -960,9 +938,7 @@ OptionGroupWatchpoint m_option_watchpoint; }; -//------------------------------------------------------------------------- // CommandObjectWatchpointSetExpression -//------------------------------------------------------------------------- #pragma mark Set class CommandObjectWatchpointSetExpression : public CommandObjectRaw { @@ -1026,7 +1002,7 @@ m_option_group.NotifyOptionParsingStarting( &exe_ctx); // This is a raw command, so notify the option group - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); StackFrame *frame = m_exe_ctx.GetFramePtr(); OptionsWithRaw args(raw_command); @@ -1128,9 +1104,7 @@ OptionGroupWatchpoint m_option_watchpoint; }; -//------------------------------------------------------------------------- // CommandObjectWatchpointSet -//------------------------------------------------------------------------- #pragma mark Set class CommandObjectWatchpointSet : public CommandObjectMultiword { @@ -1151,9 +1125,7 @@ ~CommandObjectWatchpointSet() override = default; }; -//------------------------------------------------------------------------- // CommandObjectMultiwordWatchpoint -//------------------------------------------------------------------------- #pragma mark MultiwordWatchpoint CommandObjectMultiwordWatchpoint::CommandObjectMultiwordWatchpoint(
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.h b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.h index bc0a2c0..f21796e 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpoint.h
@@ -1,9 +1,8 @@ //===-- CommandObjectWatchpoint.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,9 +16,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordWatchpoint -//------------------------------------------------------------------------- class CommandObjectMultiwordWatchpoint : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.cpp b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.cpp index 3a9ebfb..2be0b5b 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.cpp +++ b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectWatchpointCommand.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectWatchpointCommandAdd -//------------------------------------------------------------------------- // FIXME: "script-type" needs to have its contents determined dynamically, so // somebody can add a new scripting @@ -46,12 +43,8 @@ } static constexpr OptionDefinition g_watchpoint_command_add_options[] = { - // clang-format off - { LLDB_OPT_SET_1, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner, "Specify a one-line watchpoint command inline. Be sure to surround it with quotes." }, - { LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Specify whether watchpoint command execution should terminate on error." }, - { LLDB_OPT_SET_ALL, false, "script-type", 's', OptionParser::eRequiredArgument, nullptr, ScriptOptionEnum(), 0, eArgTypeNone, "Specify the language for the commands - if none is specified, the lldb command interpreter will be used." }, - { LLDB_OPT_SET_2, false, "python-function", 'F', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePythonFunction, "Give the name of a Python function to run as command for this watchpoint. Be sure to give a module name if appropriate." } - // clang-format on +#define LLDB_OPTIONS_watchpoint_command_add +#include "CommandOptions.inc" }; class CommandObjectWatchpointCommandAdd : public CommandObjectParsed, @@ -208,9 +201,9 @@ Options *GetOptions() override { return &m_options; } - void IOHandlerActivated(IOHandler &io_handler) override { + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { + if (output_sp && interactive) { output_sp->PutCString( "Enter your debugger command(s). Type 'DONE' to end.\n"); output_sp->Flush(); @@ -226,12 +219,12 @@ WatchpointOptions *wp_options = (WatchpointOptions *)io_handler.GetUserData(); if (wp_options) { - std::unique_ptr<WatchpointOptions::CommandData> data_ap( + std::unique_ptr<WatchpointOptions::CommandData> data_up( new WatchpointOptions::CommandData()); - if (data_ap) { - data_ap->user_source.SplitIntoLines(line); + if (data_up) { + data_up->user_source.SplitIntoLines(line); auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>( - std::move(data_ap)); + std::move(data_up)); wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp); } } @@ -250,19 +243,19 @@ /// Set a one-liner as the callback for the watchpoint. void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *oneliner) { - std::unique_ptr<WatchpointOptions::CommandData> data_ap( + std::unique_ptr<WatchpointOptions::CommandData> data_up( new WatchpointOptions::CommandData()); // It's necessary to set both user_source and script_source to the // oneliner. The former is used to generate callback description (as in // watchpoint command list) while the latter is used for Python to // interpret during the actual callback. - data_ap->user_source.AppendString(oneliner); - data_ap->script_source.assign(oneliner); - data_ap->stop_on_error = m_options.m_stop_on_error; + data_up->user_source.AppendString(oneliner); + data_up->script_source.assign(oneliner); + data_up->stop_on_error = m_options.m_stop_on_error; auto baton_sp = - std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap)); + std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp); } @@ -298,6 +291,7 @@ options.SetStopOnError(data->stop_on_error); options.SetEchoCommands(false); options.SetPrintResults(true); + options.SetPrintErrors(true); options.SetAddToHistory(false); debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx, @@ -390,7 +384,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("There is not a current executable; there are no " @@ -445,7 +439,7 @@ if (m_options.m_use_script_language) { // Special handling for one-liner specified inline. if (m_options.m_use_one_liner) { - m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback( + GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback( wp_options, m_options.m_one_liner.c_str()); } // Special handling for using a Python function by name instead of @@ -455,10 +449,11 @@ else if (!m_options.m_function_name.empty()) { std::string oneliner(m_options.m_function_name); oneliner += "(frame, wp, internal_dict)"; - m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback( + GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback( wp_options, oneliner.c_str()); } else { - m_interpreter.GetScriptInterpreter() + GetDebugger() + .GetScriptInterpreter() ->CollectDataForWatchpointCommandCallback(wp_options, result); } } else { @@ -479,9 +474,7 @@ CommandOptions m_options; }; -//------------------------------------------------------------------------- // CommandObjectWatchpointCommandDelete -//------------------------------------------------------------------------- class CommandObjectWatchpointCommandDelete : public CommandObjectParsed { public: @@ -508,7 +501,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("There is not a current executable; there are no " @@ -559,9 +552,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectWatchpointCommandList -//------------------------------------------------------------------------- class CommandObjectWatchpointCommandList : public CommandObjectParsed { public: @@ -589,7 +580,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + Target *target = GetDebugger().GetSelectedTarget().get(); if (target == nullptr) { result.AppendError("There is not a current executable; there are no " @@ -659,9 +650,7 @@ } }; -//------------------------------------------------------------------------- // CommandObjectWatchpointCommand -//------------------------------------------------------------------------- CommandObjectWatchpointCommand::CommandObjectWatchpointCommand( CommandInterpreter &interpreter)
diff --git a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.h b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.h index e079220..f2f15ef 100644 --- a/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.h +++ b/src/llvm-project/lldb/source/Commands/CommandObjectWatchpointCommand.h
@@ -1,9 +1,8 @@ //===-- CommandObjectWatchpointCommand.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,9 +17,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectMultiwordWatchpoint -//------------------------------------------------------------------------- class CommandObjectWatchpointCommand : public CommandObjectMultiword { public:
diff --git a/src/llvm-project/lldb/source/Commands/Options.td b/src/llvm-project/lldb/source/Commands/Options.td new file mode 100644 index 0000000..9cfbcd2 --- /dev/null +++ b/src/llvm-project/lldb/source/Commands/Options.td
@@ -0,0 +1,308 @@ +include "OptionsBase.td" + +let Command = "target modules dump symtab" in { + def tm_sort : Option<"sort", "s">, Group<1>, + Desc<"Supply a sort order when dumping the symbol table.">, + EnumArg<"SortOrder", "OptionEnumValues(g_sort_option_enumeration)">; +} + +let Command = "help" in { + def help_hide_aliases : Option<"hide-aliases", "a">, + Desc<"Hide aliases in the command list.">; + def help_hide_user : Option<"hide-user-commands", "u">, + Desc<"Hide user-defined commands from the list.">; + def help_show_hidden : Option<"show-hidden-commands", "h">, + Desc<"Include commands prefixed with an underscore.">; +} + +let Command = "settings set" in { + def setset_global : Option<"global", "g">, Arg<"Filename">, + Completion<"DiskFile">, + Desc<"Apply the new value to the global default value.">; + def setset_force : Option<"force", "f">, + Desc<"Force an empty value to be accepted as the default.">; +} + +let Command = "settings write" in { + def setwrite_file : Option<"file", "f">, Required, Arg<"Filename">, + Completion<"DiskFile">, + Desc<"The file into which to write the settings.">; + def setwrite_append : Option<"append", "a">, + Desc<"Append to saved settings file if it exists.">; +} + +let Command = "settings read" in { + def setread_file : Option<"file", "f">, Required, Arg<"Filename">, + Completion<"DiskFile">, + Desc<"The file from which to read the settings.">; +} + +let Command = "breakpoint list" in { + def blist_internal : Option<"internal", "i">, + Desc<"Show debugger internal breakpoints">; + def blist_brief : Option<"brief", "b">, Group<1>, + Desc<"Give a brief description of the breakpoint (no location info).">; + def blist_full : Option<"full", "f">, Group<2>, + Desc<"Give a full description of the breakpoint and its locations.">; + def blist_verbose : Option<"verbose", "v">, Group<3>, + Desc<"Explain everything we know about the breakpoint (for debugging " + "debugger bugs).">; + def blist_dummy_bp : Option<"dummy-breakpoints", "D">, + Desc<"List Dummy breakpoints - i.e. breakpoints set before a file is " + "provided, which prime new targets.">; +} + +let Command = "thread backtrace" in { + def thread_backtrace_count : Option<"count", "c">, Group<1>, Arg<"Count">, + Desc<"How many frames to display (-1 for all)">; + def thread_backtrace_start : Option<"start", "s">, Group<1>, + Arg<"FrameIndex">, Desc<"Frame in which to start the backtrace">; + def thread_backtrace_extended : Option<"extended", "e">, Group<1>, + Arg<"Boolean">, Desc<"Show the extended backtrace, if available">; +} + +let Command = "thread step scope" in { + def thread_step_scope_step_in_avoids_no_debug : + Option<"step-in-avoids-no-debug", "a">, Group<1>, Arg<"Boolean">, + Desc<"A boolean value that sets whether stepping into functions will step " + "over functions with no debug information.">; + def thread_step_scope_step_out_avoids_no_debug : + Option<"step-out-avoids-no-debug", "A">, Group<1>, Arg<"Boolean">, + Desc<"A boolean value, if true stepping out of functions will continue to" + " step out till it hits a function with debug information.">; + def thread_step_scope_count : Option<"count", "c">, Group<1>, Arg<"Count">, + Desc<"How many times to perform the stepping operation - currently only " + "supported for step-inst and next-inst.">; + def thread_step_scope_end_linenumber : Option<"end-linenumber", "e">, + Group<1>, Arg<"LineNum">, Desc<"The line at which to stop stepping - " + "defaults to the next line and only supported for step-in and step-over." + " You can also pass the string 'block' to step to the end of the current" + " block. This is particularly use in conjunction with --step-target to" + " step through a complex calling sequence.">; + def thread_step_scope_run_mode : Option<"run-mode", "m">, Group<1>, + EnumArg<"RunMode", "TriRunningModes()">, Desc<"Determine how to run other " + "threads while stepping the current thread.">; + def thread_step_scope_step_over_regexp : Option<"step-over-regexp", "r">, + Group<1>, Arg<"RegularExpression">, Desc<"A regular expression that defines" + "function names to not to stop at when stepping in.">; + def thread_step_scope_step_in_target : Option<"step-in-target", "t">, + Group<1>, Arg<"FunctionName">, Desc<"The name of the directly called " + "function step in should stop at when stepping into.">; + def thread_step_scope_python_class : Option<"python-class", "C">, Group<2>, + Arg<"PythonClass">, Desc<"The name of the class that will manage this step " + "- only supported for Scripted Step.">; +} + +let Command = "thread until" in { + def thread_until_frame : Option<"frame", "f">, Group<1>, Arg<"FrameIndex">, + Desc<"Frame index for until operation - defaults to 0">; + def thread_until_thread : Option<"thread", "t">, Group<1>, Arg<"ThreadIndex">, + Desc<"Thread index for the thread for until operation">; + def thread_until_run_mode : Option<"run-mode", "m">, Group<1>, + EnumArg<"RunMode", "DuoRunningModes()">, Desc<"Determine how to run other" + "threads while stepping this one">; + def thread_until_address : Option<"address", "a">, Group<1>, + Arg<"AddressOrExpression">, Desc<"Run until we reach the specified address," + "or leave the function - can be specified multiple times.">; +} + +let Command = "thread info" in { + def thread_info_json : Option<"json", "j">, Desc<"Display the thread info in" + " JSON format.">; + def thread_info_stop_info : Option<"stop-info", "s">, Desc<"Display the " + "extended stop info in JSON format.">; +} + +let Command = "thread return" in { + def thread_return_from_expression : Option<"from-expression", "x">, + Desc<"Return from the innermost expression evaluation.">; +} + +let Command = "thread jump" in { + def thread_jump_file : Option<"file", "f">, Group<1>, Arg<"Filename">, + Completion<"SourceFile">, Desc<"Specifies the source file to jump to.">; + def thread_jump_line : Option<"line", "l">, Group<1>, Arg<"LineNum">, + Required, Desc<"Specifies the line number to jump to.">; + def thread_jump_by : Option<"by", "b">, Group<2>, Arg<"Offset">, Required, + Desc<"Jumps by a relative line offset from the current line.">; + def thread_jump_address : Option<"address", "a">, Group<3>, + Arg<"AddressOrExpression">, Required, Desc<"Jumps to a specific address.">; + def thread_jump_force : Option<"force", "r">, Groups<[1,2,3]>, + Desc<"Allows the PC to leave the current function.">; +} + +let Command = "thread plan list" in { + def thread_plan_list_verbose : Option<"verbose", "v">, Group<1>, + Desc<"Display more information about the thread plans">; + def thread_plan_list_internal : Option<"internal", "i">, Group<1>, + Desc<"Display internal as well as user thread plans">; +} + +let Command = "type summary add" in { + def type_summary_add_category : Option<"category", "w">, Arg<"Name">, + Desc<"Add this to the given category instead of the default one.">; + def type_summary_add_cascade : Option<"cascade", "C">, Arg<"Boolean">, + Desc<"If true, cascade through typedef chains.">; + def type_summary_add_no_value : Option<"no-value", "v">, + Desc<"Don't show the value, just show the summary, for this type.">; + def type_summary_add_skip_pointers : Option<"skip-pointers", "p">, + Desc<"Don't use this format for pointers-to-type objects.">; + def type_summary_add_skip_references : Option<"skip-references", "r">, + Desc<"Don't use this format for references-to-type objects.">; + def type_summary_add_regex : Option<"regex", "x">, + Desc<"Type names are actually regular expressions.">; + def type_summary_add_inline_children : Option<"inline-children", "c">, + Group<1>, Required, + Desc<"If true, inline all child values into summary string.">; + def type_summary_add_omit_names : Option<"omit-names", "O">, Group<1>, + Desc<"If true, omit value names in the summary display.">; + def type_summary_add_summary_string : Option<"summary-string", "s">, Group<2>, + Arg<"SummaryString">, Required, + Desc<"Summary string used to display text and object contents.">; + def type_summary_add_python_script : Option<"python-script", "o">, Group<3>, + Arg<"PythonScript">, + Desc<"Give a one-liner Python script as part of the command.">; + def type_summary_add_python_function : Option<"python-function", "F">, + Group<3>, Arg<"PythonFunction">, + Desc<"Give the name of a Python function to use for this type.">; + def type_summary_add_input_python : Option<"input-python", "P">, Group<3>, + Desc<"Input Python code to use for this type manually.">; + def type_summary_add_expand : Option<"expand", "e">, Groups<[2,3]>, + Desc<"Expand aggregate data types to show children on separate lines.">; + def type_summary_add_hide_empty : Option<"hide-empty", "h">, Groups<[2,3]>, + Desc<"Do not expand aggregate data types with no children.">; + def type_summary_add_name : Option<"name", "n">, Groups<[2,3]>, Arg<"Name">, + Desc<"A name for this summary string.">; +} + +let Command = "type synth add" in { + def type_synth_add_cascade : Option<"cascade", "C">, Arg<"Boolean">, + Desc<"If true, cascade through typedef chains.">; + def type_synth_add_skip_pointers : Option<"skip-pointers", "p">, + Desc<"Don't use this format for pointers-to-type objects.">; + def type_synth_add_skip_references : Option<"skip-references", "r">, + Desc<"Don't use this format for references-to-type objects.">; + def type_synth_add_category : Option<"category", "w">, Arg<"Name">, + Desc<"Add this to the given category instead of the default one.">; + def type_synth_add_python_class : Option<"python-class", "l">, Group<2>, + Arg<"PythonClass">, + Desc<"Use this Python class to produce synthetic children.">; + def type_synth_add_input_python : Option<"input-python", "P">, Group<3>, + Desc<"Type Python code to generate a class that provides synthetic " + "children.">; + def type_synth_add_regex : Option<"regex", "x">, + Desc<"Type names are actually regular expressions.">; +} + +let Command = "type format add" in { + def type_format_add_category : Option<"category", "w">, Arg<"Name">, + Desc<"Add this to the given category instead of the default one.">; + def type_format_add_cascade : Option<"cascade", "C">, Arg<"Boolean">, + Desc<"If true, cascade through typedef chains.">; + def type_format_add_skip_pointers : Option<"skip-pointers", "p">, + Desc<"Don't use this format for pointers-to-type objects.">; + def type_format_add_skip_references : Option<"skip-references", "r">, + Desc<"Don't use this format for references-to-type objects.">; + def type_format_add_regex : Option<"regex", "x">, + Desc<"Type names are actually regular expressions.">; + def type_format_add_type : Option<"type", "t">, Group<2>, Arg<"Name">, + Desc<"Format variables as if they were of this type.">; +} + +let Command = "type formatter delete" in { + def type_formatter_delete_all : Option<"all", "a">, Group<1>, + Desc<"Delete from every category.">; + def type_formatter_delete_category : Option<"category", "w">, Group<2>, + Arg<"Name">, Desc<"Delete from given category.">; + def type_formatter_delete_language : Option<"language", "l">, Group<3>, + Arg<"Language">, Desc<"Delete from given language's category.">; +} + +let Command = "type formatter clear" in { + def type_formatter_clear_all : Option<"all", "a">, + Desc<"Clear every category.">; +} + +let Command = "type formatter list" in { + def type_formatter_list_category_regex : Option<"category-regex", "w">, + Group<1>, Arg<"Name">, Desc<"Only show categories matching this filter.">; + def type_formatter_list_language : Option<"language", "l">, Group<2>, + Arg<"Language">, Desc<"Only show the category for a specific language.">; +} + +let Command = "type category define" in { + def type_category_define_enabled : Option<"enabled", "e">, + Desc<"If specified, this category will be created enabled.">; + def type_category_define_language : Option<"language", "l">, Arg<"Language">, + Desc<"Specify the language that this category is supported for.">; +} + +let Command = "type category enable" in { + def type_category_enable_language : Option<"language", "l">, Arg<"Language">, + Desc<"Enable the category for this language.">; +} + +let Command = "type category disable" in { + def type_category_disable_language : Option<"language", "l">, Arg<"Language">, + Desc<"Enable the category for this language.">; +} + +let Command = "type filter add" in { + def type_filter_add_cascade : Option<"cascade", "C">, Arg<"Boolean">, + Desc<"If true, cascade through typedef chains.">; + def type_filter_add_skip_pointers : Option<"skip-pointers", "p">, + Desc<"Don't use this format for pointers-to-type objects.">; + def type_filter_add_skip_references : Option<"skip-references", "r">, + Desc<"Don't use this format for references-to-type objects.">; + def type_filter_add_category : Option<"category", "w">, Arg<"Name">, + Desc<"Add this to the given category instead of the default one.">; + def type_filter_add_child : Option<"child", "c">, Arg<"ExpressionPath">, + Desc<"Include this expression path in the synthetic view.">; + def type_filter_add_regex : Option<"regex", "x">, + Desc<"Type names are actually regular expressions.">; +} + +let Command = "type lookup" in { + def type_lookup_show_help : Option<"show-help", "h">, + Desc<"Display available help for types">; + def type_lookup_language : Option<"language", "l">, Arg<"Language">, + Desc<"Which language's types should the search scope be">; +} + +let Command = "watchpoint list" in { + def watchpoint_list_brief : Option<"brief", "b">, Group<1>, Desc<"Give a " + "brief description of the watchpoint (no location info).">; + def watchpoint_list_full : Option<"full", "f">, Group<2>, Desc<"Give a full " + "description of the watchpoint and its locations.">; + def watchpoint_list_verbose : Option<"verbose", "v">, Group<3>, Desc<"Explain" + "everything we know about the watchpoint (for debugging debugger bugs).">; +} + +let Command = "watchpoint ignore" in { + def watchpoint_ignore_ignore_count : Option<"ignore-count", "i">, + Arg<"Count">, Required, Desc<"Set the number of times this watchpoint is" + " skipped before stopping.">; +} + +let Command = "watchpoint modify" in { + def watchpoint_modify_condition : Option<"condition", "c">, Arg<"Expression">, + Desc<"The watchpoint stops only if this condition expression evaluates " + "to true.">; +} + +let Command = "watchpoint command add" in { + def watchpoint_command_add_one_liner : Option<"one-liner", "o">, Group<1>, + Arg<"OneLiner">, Desc<"Specify a one-line watchpoint command inline. Be " + "sure to surround it with quotes.">; + def watchpoint_command_add_stop_on_error : Option<"stop-on-error", "e">, + Arg<"Boolean">, Desc<"Specify whether watchpoint command execution should " + "terminate on error.">; + def watchpoint_command_add_script_type : Option<"script-type", "s">, + EnumArg<"None", "ScriptOptionEnum()">, Desc<"Specify the language for the" + " commands - if none is specified, the lldb command interpreter will be " + "used.">; + def watchpoint_command_add_python_function : Option<"python-function", "F">, + Group<2>, Arg<"PythonFunction">, Desc<"Give the name of a Python function " + "to run as command for this watchpoint. Be sure to give a module name if " + "appropriate.">; +}
diff --git a/src/llvm-project/lldb/source/Commands/OptionsBase.td b/src/llvm-project/lldb/source/Commands/OptionsBase.td new file mode 100644 index 0000000..a81563e --- /dev/null +++ b/src/llvm-project/lldb/source/Commands/OptionsBase.td
@@ -0,0 +1,160 @@ + +// The fields below describe how the fields of `OptionDefinition` struct are +// initialized by different definitions in the Options.td and this file. +//////////////////////////////////////////////////////////////////////////////// +// Field: usage_mask +// Default value: LLDB_OPT_SET_ALL (Option allowed in all groups) +// Set by: +// - `Group`: Sets a single group to this option. +// Example: def foo : Option<"foo", "f">, Group<1>; +// - `Groups`: Sets a given list of group numbers. +// Example: def foo : Option<"foo", "f">, Groups<[1,4,6]>; +// - `GroupRange`: Sets an interval of groups. Start and end are inclusive. +// Example: def foo : Option<"foo", "f">, GroupRange<1, 4>; +// Sets group 1, 2, 3, 4 for the option. +//////////////////////////////////////////////////////////////////////////////// +// Field: required +// Default value: false (Not required) +// Set by: +// - `Required`: Marks the option as required. +// Example: def foo : Option<"foo", "f">, Required; +//////////////////////////////////////////////////////////////////////////////// +// Field: long_option +// Default value: not available (has to be defined in Option) +// Set by: +// - `Option` constructor: Already set by constructor. +// Example: def foo : Option<"long-option", "l"> +// ^ +// long option value +//////////////////////////////////////////////////////////////////////////////// +// Field: short_option +// Default value: not available (has to be defined in Option) +// Set by: +// - `Option` constructor: Already set by constructor. +// Example: def foo : Option<"long-option", "l"> +// ^ +// short option +//////////////////////////////////////////////////////////////////////////////// +// Field: option_has_arg +// Default value: OptionParser::eNoArgument (No argument allowed) +// Set by: +// - `OptionalArg`: Sets the argument type and marks it as optional. +// - `Arg`: Sets the argument type and marks it as required. +// - `EnumArg`: Sets the argument type to an enum and marks it as required. +// See argument_type field for more info. +//////////////////////////////////////////////////////////////////////////////// +// Field: validator +// Default value: 0 (No validator for option) +// Set by: Nothing. This is currently only set after initialization in LLDB. +//////////////////////////////////////////////////////////////////////////////// +// Field: enum_values +// Default value: {} (No enum associated with this option) +// Set by: +// - `EnumArg`: Sets the argument type and assigns it a enum holding the valid +// values. The enum needs to be a variable in the including code. +// Marks the option as required (see option_has_arg). +// Example: def foo : Option<"foo", "f">, +// EnumArg<"SortOrder", +// "OptionEnumValues(g_sort_option_enumeration)">; +//////////////////////////////////////////////////////////////////////////////// +// Field: completion_type +// Default value: CommandCompletions::eNoCompletion (no tab completion) +// Set by: +// - `Completion`: Gives the option a single completion kind. +// Example: def foo : Option<"foo", "f">, +// Completion<"DiskFile">; +// Sets the completion to eDiskFileCompletion +// +// - `Completions`: Sets a given kinds of completions. +// Example: def foo : Option<"foo", "f">, +// Completions<["DiskFile", "DiskDirectory"]>; +// Sets the completion to +// `eDiskFileCompletion | eDiskDirectoryCompletion`. +//////////////////////////////////////////////////////////////////////////////// +// Field: argument_type +// Default value: eArgTypeNone +// Set by: +// - `OptionalArg`: Sets the argument type and marks it as optional. +// Example: def foo : Option<"foo", "f">, OptionalArg<"Pid">; +// Sets the argument type to eArgTypePid and marks option as +// optional (see option_has_arg). +// - `Arg`: Sets the argument type and marks it as required. +// Example: def foo : Option<"foo", "f">, Arg<"Pid">; +// Sets the argument type to eArgTypePid and marks option as +// required (see option_has_arg). +// - `EnumArg`: Sets the argument type and assigns it a enum holding the valid +// values. The enum needs to be a variable in the including code. +// Marks the option as required (see option_has_arg). +// Example: def foo : Option<"foo", "f">, +// EnumArg<"SortOrder", +// "OptionEnumValues(g_sort_option_enumeration)">; +//////////////////////////////////////////////////////////////////////////////// +// Field: usage_text +// Default value: "" +// Set by: +// - `Desc`: Sets the description for the given option. +// Example: def foo : Option<"foo", "f">, Desc<"does nothing.">; +// Sets the description to "does nothing.". + +// Base class for all options. +class Option<string fullname, string shortname> { + string FullName = fullname; + string ShortName = shortname; + // The full associated command/subcommand such as "settings set". + string Command; +} + +// Moves the option into a list of option groups. +class Groups<list<int> groups> { + list<int> Groups = groups; +} + +// Moves the option in all option groups in a range. +// Start and end values are inclusive. +class GroupRange<int start, int end> { + int GroupStart = start; + int GroupEnd = end; +} +// Moves the option in a single option group. +class Group<int group> { + int GroupStart = group; + int GroupEnd = group; +} + +// Sets the description for the option that should be +// displayed to the user. +class Desc<string description> { + string Description = description; +} + +// Marks the option as required when calling the +// associated command. +class Required { + bit Required = 1; +} + +// Gives the option an optional argument. +class OptionalArg<string type> { + string ArgType = type; + bit OptionalArg = 1; +} + +// Gives the option an required argument. +class Arg<string type> { + string ArgType = type; +} + +// Gives the option an required argument. +class EnumArg<string type, string enum> { + string ArgType = type; + string ArgEnum = enum; +} + +// Sets the available completions for the given option. +class Completions<list<string> completions> { + list<string> Completions = completions; +} +// Sets a single completion for the given option. +class Completion<string completion> { + list<string> Completions = [completion]; +}
diff --git a/src/llvm-project/lldb/source/Core/Address.cpp b/src/llvm-project/lldb/source/Core/Address.cpp index a4dc364..0da83eb 100644 --- a/src/llvm-project/lldb/source/Core/Address.cpp +++ b/src/llvm-project/lldb/source/Core/Address.cpp
@@ -1,9 +1,8 @@ //===-- Address.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -162,7 +161,7 @@ static bool DumpUInt(ExecutionContextScope *exe_scope, const Address &address, uint32_t byte_size, Stream *strm) { if (exe_scope == nullptr || byte_size == 0) - return 0; + return false; std::vector<uint8_t> buf(byte_size, 0); if (ReadBytes(exe_scope, address, &buf[0], buf.size()) == buf.size()) { @@ -928,7 +927,6 @@ return sizeof(Address); } -//---------------------------------------------------------------------- // NOTE: Be careful using this operator. It can correctly compare two // addresses from the same Module correctly. It can't compare two addresses // from different modules in any meaningful way, but it will compare the module @@ -940,7 +938,6 @@ // address results to make much sense // // This basically lets Address objects be used in ordered collection classes. -//---------------------------------------------------------------------- bool lldb_private::operator<(const Address &lhs, const Address &rhs) { ModuleSP lhs_module_sp(lhs.GetModule());
diff --git a/src/llvm-project/lldb/source/Core/AddressRange.cpp b/src/llvm-project/lldb/source/Core/AddressRange.cpp index 1afe4fa..71eec3c 100644 --- a/src/llvm-project/lldb/source/Core/AddressRange.cpp +++ b/src/llvm-project/lldb/source/Core/AddressRange.cpp
@@ -1,9 +1,8 @@ //===-- AddressRange.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -123,6 +122,24 @@ return false; } +bool AddressRange::Extend(const AddressRange &rhs_range) { + addr_t lhs_end_addr = GetBaseAddress().GetFileAddress() + GetByteSize(); + addr_t rhs_base_addr = rhs_range.GetBaseAddress().GetFileAddress(); + + if (!ContainsFileAddress(rhs_range.GetBaseAddress()) && + lhs_end_addr != rhs_base_addr) + // The ranges don't intersect at all on the right side of this range. + return false; + + addr_t rhs_end_addr = rhs_base_addr + rhs_range.GetByteSize(); + if (lhs_end_addr >= rhs_end_addr) + // The rhs range totally overlaps this one, nothing to add. + return false; + + m_byte_size += rhs_end_addr - lhs_end_addr; + return true; +} + void AddressRange::Clear() { m_base_addr.Clear(); m_byte_size = 0;
diff --git a/src/llvm-project/lldb/source/Core/AddressResolver.cpp b/src/llvm-project/lldb/source/Core/AddressResolver.cpp index 8d7cc9f..974d99b 100644 --- a/src/llvm-project/lldb/source/Core/AddressResolver.cpp +++ b/src/llvm-project/lldb/source/Core/AddressResolver.cpp
@@ -1,9 +1,8 @@ //===-- AddressResolver.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,9 +16,7 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // AddressResolver: -//---------------------------------------------------------------------- AddressResolver::AddressResolver() {} AddressResolver::~AddressResolver() {}
diff --git a/src/llvm-project/lldb/source/Core/AddressResolverFileLine.cpp b/src/llvm-project/lldb/source/Core/AddressResolverFileLine.cpp index 203ab27..24c0222 100644 --- a/src/llvm-project/lldb/source/Core/AddressResolverFileLine.cpp +++ b/src/llvm-project/lldb/source/Core/AddressResolverFileLine.cpp
@@ -1,9 +1,8 @@ //===-- AddressResolverFileLine.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,9 +27,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // AddressResolverFileLine: -//---------------------------------------------------------------------- AddressResolverFileLine::AddressResolverFileLine(const FileSpec &file_spec, uint32_t line_no, bool check_inlines)
diff --git a/src/llvm-project/lldb/source/Core/AddressResolverName.cpp b/src/llvm-project/lldb/source/Core/AddressResolverName.cpp index 7683e39..e861368 100644 --- a/src/llvm-project/lldb/source/Core/AddressResolverName.cpp +++ b/src/llvm-project/lldb/source/Core/AddressResolverName.cpp
@@ -1,9 +1,8 @@ //===-- AddressResolverName.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Core/CMakeLists.txt b/src/llvm-project/lldb/source/Core/CMakeLists.txt index 1c23ba7..7ca37f9 100644 --- a/src/llvm-project/lldb/source/Core/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Core/CMakeLists.txt
@@ -1,10 +1,14 @@ set(LLDB_CURSES_LIBS) +set(LLDB_LIBEDIT_LIBS) if (NOT LLDB_DISABLE_CURSES) list(APPEND LLDB_CURSES_LIBS ${CURSES_LIBRARIES}) if(LLVM_ENABLE_TERMINFO AND HAVE_TERMINFO) list(APPEND LLDB_CURSES_LIBS ${TERMINFO_LIBS}) endif() + if (LLVM_BUILD_STATIC) + list(APPEND LLDB_CURSES_LIBS gpm) + endif() endif() add_lldb_library(lldbCore @@ -63,15 +67,11 @@ lldbSymbol lldbTarget lldbUtility - lldbPluginProcessUtility lldbPluginCPlusPlusLanguage lldbPluginObjCLanguage - lldbPluginExpressionParserRust - lldbPluginLanguageRuntimeRust ${LLDB_CURSES_LIBS} LINK_COMPONENTS - BinaryFormat Support Demangle )
diff --git a/src/llvm-project/lldb/source/Core/Communication.cpp b/src/llvm-project/lldb/source/Core/Communication.cpp index afdabc0..a67cb92 100644 --- a/src/llvm-project/lldb/source/Core/Communication.cpp +++ b/src/llvm-project/lldb/source/Core/Communication.cpp
@@ -1,9 +1,8 @@ //===-- Communication.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -205,10 +204,23 @@ m_read_thread_enabled = true; m_read_thread_did_exit = false; - m_read_thread = ThreadLauncher::LaunchThread( - thread_name, Communication::ReadThread, this, error_ptr); + auto maybe_thread = ThreadLauncher::LaunchThread( + thread_name, Communication::ReadThread, this); + if (maybe_thread) { + m_read_thread = *maybe_thread; + } else { + if (error_ptr) + *error_ptr = Status(maybe_thread.takeError()); + else { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(maybe_thread.takeError())); + } + } + if (!m_read_thread.IsJoinable()) m_read_thread_enabled = false; + return m_read_thread_enabled; } @@ -360,7 +372,7 @@ // Let clients know that this thread is exiting comm->BroadcastEvent(eBroadcastBitNoMorePendingInput); comm->BroadcastEvent(eBroadcastBitReadThreadDidExit); - return NULL; + return {}; } void Communication::SetReadThreadBytesReceivedCallback(
diff --git a/src/llvm-project/lldb/source/Core/Debugger.cpp b/src/llvm-project/lldb/source/Core/Debugger.cpp index 765b59c..1a69fc5 100644 --- a/src/llvm-project/lldb/source/Core/Debugger.cpp +++ b/src/llvm-project/lldb/source/Core/Debugger.cpp
@@ -1,9 +1,8 @@ //===-- Debugger.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -122,7 +121,10 @@ "{${frame.no-debug}${function.pc-offset}}}}" #define FILE_AND_LINE \ - "{ at ${line.file.basename}:${line.number}{:${line.column}}}" + "{ at ${ansi.fg.cyan}${line.file.basename}${ansi.normal}" \ + ":${ansi.fg.yellow}${line.number}${ansi.normal}" \ + "{:${ansi.fg.yellow}${line.column}${ansi.normal}}}" + #define IS_OPTIMIZED "{${function.is-optimized} [opt]}" #define IS_ARTIFICIAL "{${frame.is-artificial} [artificial]}" @@ -130,32 +132,36 @@ #define DEFAULT_THREAD_FORMAT \ "thread #${thread.index}: tid = ${thread.id%tid}" \ "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \ - "{, name = '${thread.name}'}" \ - "{, queue = '${thread.queue}'}" \ - "{, activity = '${thread.info.activity.name}'}" \ + "{, name = ${ansi.fg.green}'${thread.name}'${ansi.normal}}" \ + "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \ + "{, activity = " \ + "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \ "{, ${thread.info.trace_messages} messages}" \ - "{, stop reason = ${thread.stop-reason}}" \ + "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \ "{\\nReturn value: ${thread.return-value}}" \ "{\\nCompleted expression: ${thread.completed-expression}}" \ "\\n" #define DEFAULT_THREAD_STOP_FORMAT \ "thread #${thread.index}{, name = '${thread.name}'}" \ - "{, queue = '${thread.queue}'}" \ - "{, activity = '${thread.info.activity.name}'}" \ + "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \ + "{, activity = " \ + "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \ "{, ${thread.info.trace_messages} messages}" \ - "{, stop reason = ${thread.stop-reason}}" \ + "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \ "{\\nReturn value: ${thread.return-value}}" \ "{\\nCompleted expression: ${thread.completed-expression}}" \ "\\n" #define DEFAULT_FRAME_FORMAT \ - "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \ + "frame #${frame.index}: " \ + "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC FILE_AND_LINE \ IS_OPTIMIZED IS_ARTIFICIAL "\\n" #define DEFAULT_FRAME_FORMAT_NO_ARGS \ - "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC_NO_ARGS FILE_AND_LINE \ - IS_OPTIMIZED IS_ARTIFICIAL "\\n" + "frame #${frame.index}: " \ + "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC_NO_ARGS \ + FILE_AND_LINE IS_OPTIMIZED IS_ARTIFICIAL "\\n" // Three parts to this disassembly format specification: // 1. If this is a new function/symbol (no previous symbol/function), print @@ -712,7 +718,7 @@ } DebuggerSP -Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) { +Debugger::FindDebuggerWithInstanceName(ConstString instance_name) { DebuggerSP debugger_sp; if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); @@ -761,14 +767,15 @@ m_input_file_sp(std::make_shared<StreamFile>(stdin, false)), m_output_file_sp(std::make_shared<StreamFile>(stdout, false)), m_error_file_sp(std::make_shared<StreamFile>(stderr, false)), + m_input_recorder(nullptr), m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()), m_terminal_state(), m_target_list(*this), m_platform_list(), m_listener_sp(Listener::MakeListener("lldb.Debugger")), - m_source_manager_ap(), m_source_file_cache(), - m_command_interpreter_ap(llvm::make_unique<CommandInterpreter>( - *this, eScriptLanguageDefault, false)), - m_input_reader_stack(), m_instance_name(), m_loaded_plugins(), - m_event_handler_thread(), m_io_handler_thread(), + m_source_manager_up(), m_source_file_cache(), + m_command_interpreter_up( + llvm::make_unique<CommandInterpreter>(*this, false)), + m_script_interpreter_sp(), m_input_reader_stack(), m_instance_name(), + m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(), m_sync_broadcaster(nullptr, "lldb.debugger.sync"), m_forward_listener_sp(), m_clear_once() { char instance_cstr[256]; @@ -777,7 +784,7 @@ if (log_callback) m_log_callback_stream_sp = std::make_shared<StreamCallback>(log_callback, baton); - m_command_interpreter_ap->Initialize(); + m_command_interpreter_up->Initialize(); // Always add our default platform to the platform list PlatformSP default_platform_sp(Platform::GetHostPlatform()); assert(default_platform_sp); @@ -794,11 +801,11 @@ m_collection_sp->AppendProperty( ConstString("symbols"), ConstString("Symbol lookup and cache settings."), true, ModuleList::GetGlobalModuleListProperties().GetValueProperties()); - if (m_command_interpreter_ap) { + if (m_command_interpreter_up) { m_collection_sp->AppendProperty( ConstString("interpreter"), ConstString("Settings specify to the debugger's command interpreter."), - true, m_command_interpreter_ap->GetValueProperties()); + true, m_command_interpreter_up->GetValueProperties()); } OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64( @@ -824,7 +831,6 @@ Debugger::~Debugger() { Clear(); } void Debugger::Clear() { - //---------------------------------------------------------------------- // Make sure we call this function only once. With the C++ global destructor // chain having a list of debuggers and with code that can be running on // other threads, we need to ensure this doesn't happen multiple times. @@ -833,7 +839,6 @@ // Debugger::~Debugger(); // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp); // static void Debugger::Terminate(); - //---------------------------------------------------------------------- llvm::call_once(m_clear_once, [this]() { ClearIOHandlers(); StopIOHandlerThread(); @@ -857,7 +862,7 @@ if (m_input_file_sp) m_input_file_sp->GetFile().Close(); - m_command_interpreter_ap->Clear(); + m_command_interpreter_up->Clear(); }); } @@ -871,14 +876,18 @@ } bool Debugger::GetAsyncExecution() { - return !m_command_interpreter_ap->GetSynchronous(); + return !m_command_interpreter_up->GetSynchronous(); } void Debugger::SetAsyncExecution(bool async_execution) { - m_command_interpreter_ap->SetSynchronous(!async_execution); + m_command_interpreter_up->SetSynchronous(!async_execution); } -void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) { +repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; } + +void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership, + repro::DataRecorder *recorder) { + m_input_recorder = recorder; if (m_input_file_sp) m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership); else @@ -903,12 +912,10 @@ if (!out_file.IsValid()) out_file.SetStream(stdout, false); - // do not create the ScriptInterpreter just for setting the output file - // handle as the constructor will know how to do the right thing on its own - const bool can_create = false; - ScriptInterpreter *script_interpreter = - GetCommandInterpreter().GetScriptInterpreter(can_create); - if (script_interpreter) + // Do not create the ScriptInterpreter just for setting the output file + // handle as the constructor will know how to do the right thing on its own. + if (ScriptInterpreter *script_interpreter = + GetScriptInterpreter(/*can_create=*/false)) script_interpreter->ResetOutputFileHandle(fh); } @@ -1286,10 +1293,23 @@ error_stream); } +ScriptInterpreter *Debugger::GetScriptInterpreter(bool can_create) { + std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); + + if (!m_script_interpreter_sp) { + if (!can_create) + return nullptr; + m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage( + GetScriptLanguage(), *this); + } + + return m_script_interpreter_sp.get(); +} + SourceManager &Debugger::GetSourceManager() { - if (!m_source_manager_ap) - m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this()); - return *m_source_manager_ap; + if (!m_source_manager_up) + m_source_manager_up = llvm::make_unique<SourceManager>(shared_from_this()); + return *m_source_manager_up; } // This function handles events that were broadcast by the process. @@ -1537,7 +1557,7 @@ listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, thread_event_spec); listener_sp->StartListeningForEvents( - m_command_interpreter_ap.get(), + m_command_interpreter_up.get(), CommandInterpreter::eBroadcastBitQuitCommandReceived | CommandInterpreter::eBroadcastBitAsynchronousOutputData | CommandInterpreter::eBroadcastBitAsynchronousErrorData); @@ -1564,7 +1584,7 @@ } } else if (broadcaster_class == broadcaster_class_thread) { HandleThreadEvent(event_sp); - } else if (broadcaster == m_command_interpreter_ap.get()) { + } else if (broadcaster == m_command_interpreter_up.get()) { if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived) { done = true; @@ -1603,7 +1623,7 @@ lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) { ((Debugger *)arg)->DefaultEventHandler(); - return NULL; + return {}; } bool Debugger::StartEventHandlerThread() { @@ -1622,8 +1642,17 @@ full_name.AsCString() : "dbg.evt-handler"; // Use larger 8MB stack for this thread - m_event_handler_thread = ThreadLauncher::LaunchThread(thread_name, - EventHandlerThread, this, nullptr, g_debugger_event_thread_stack_bytes); + llvm::Expected<HostThread> event_handler_thread = + ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this, + g_debugger_event_thread_stack_bytes); + + if (event_handler_thread) { + m_event_handler_thread = *event_handler_thread; + } else { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(event_handler_thread.takeError())); + } // Make sure DefaultEventHandler() is running and listening to events // before we return from this function. We are only listening for events of @@ -1648,16 +1677,24 @@ Debugger *debugger = (Debugger *)arg; debugger->ExecuteIOHandlers(); debugger->StopEventHandlerThread(); - return NULL; + return {}; } bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); } bool Debugger::StartIOHandlerThread() { - if (!m_io_handler_thread.IsJoinable()) - m_io_handler_thread = ThreadLauncher::LaunchThread( - "lldb.debugger.io-handler", IOHandlerThread, this, nullptr, + if (!m_io_handler_thread.IsJoinable()) { + llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread( + "lldb.debugger.io-handler", IOHandlerThread, this, 8 * 1024 * 1024); // Use larger 8MB stack for this thread + if (io_handler_thread) { + m_io_handler_thread = *io_handler_thread; + } else { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(io_handler_thread.takeError())); + } + } return m_io_handler_thread.IsJoinable(); }
diff --git a/src/llvm-project/lldb/source/Core/Disassembler.cpp b/src/llvm-project/lldb/source/Core/Disassembler.cpp index a34b803..af7cf82 100644 --- a/src/llvm-project/lldb/source/Core/Disassembler.cpp +++ b/src/llvm-project/lldb/source/Core/Disassembler.cpp
@@ -1,9 +1,8 @@ //===-- Disassembler.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -162,7 +161,7 @@ bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch, const char *plugin_name, const char *flavor, const ExecutionContext &exe_ctx, - const ConstString &name, Module *module, + ConstString name, Module *module, uint32_t num_instructions, bool mixed_source_and_assembly, uint32_t num_mixed_context_lines, @@ -742,11 +741,11 @@ } bool Instruction::DumpEmulation(const ArchSpec &arch) { - std::unique_ptr<EmulateInstruction> insn_emulator_ap( + std::unique_ptr<EmulateInstruction> insn_emulator_up( EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr)); - if (insn_emulator_ap) { - insn_emulator_ap->SetInstruction(GetOpcode(), GetAddress(), nullptr); - return insn_emulator_ap->EvaluateInstruction(0); + if (insn_emulator_up) { + insn_emulator_up->SetInstruction(GetOpcode(), GetAddress(), nullptr); + return insn_emulator_up->EvaluateInstruction(0); } return false; @@ -993,11 +992,11 @@ arch.SetTriple(llvm::Triple(value_sp->GetStringValue())); bool success = false; - std::unique_ptr<EmulateInstruction> insn_emulator_ap( + std::unique_ptr<EmulateInstruction> insn_emulator_up( EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr)); - if (insn_emulator_ap) + if (insn_emulator_up) success = - insn_emulator_ap->TestEmulation(out_stream, arch, data_dictionary); + insn_emulator_up->TestEmulation(out_stream, arch, data_dictionary); if (success) out_stream->Printf("Emulation test succeeded."); @@ -1013,14 +1012,14 @@ EmulateInstruction::WriteMemoryCallback write_mem_callback, EmulateInstruction::ReadRegisterCallback read_reg_callback, EmulateInstruction::WriteRegisterCallback write_reg_callback) { - std::unique_ptr<EmulateInstruction> insn_emulator_ap( + std::unique_ptr<EmulateInstruction> insn_emulator_up( EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr)); - if (insn_emulator_ap) { - insn_emulator_ap->SetBaton(baton); - insn_emulator_ap->SetCallbacks(read_mem_callback, write_mem_callback, + if (insn_emulator_up) { + insn_emulator_up->SetBaton(baton); + insn_emulator_up->SetCallbacks(read_mem_callback, write_mem_callback, read_reg_callback, write_reg_callback); - insn_emulator_ap->SetInstruction(GetOpcode(), GetAddress(), nullptr); - return insn_emulator_ap->EvaluateInstruction(evaluate_options); + insn_emulator_up->SetInstruction(GetOpcode(), GetAddress(), nullptr); + return insn_emulator_up->EvaluateInstruction(evaluate_options); } return false; @@ -1088,13 +1087,16 @@ uint32_t InstructionList::GetIndexOfNextBranchInstruction(uint32_t start, - Target &target) const { + Target &target, + bool ignore_calls) const { size_t num_instructions = m_instructions.size(); uint32_t next_branch = UINT32_MAX; size_t i; for (i = start; i < num_instructions; i++) { if (m_instructions[i]->DoesBranch()) { + if (ignore_calls && m_instructions[i]->IsCall()) + continue; next_branch = i; break; } @@ -1238,9 +1240,7 @@ return m_instruction_list.GetSize(); } -//---------------------------------------------------------------------- // Disassembler copy constructor -//---------------------------------------------------------------------- Disassembler::Disassembler(const ArchSpec &arch, const char *flavor) : m_arch(arch), m_instruction_list(), m_base_addr(LLDB_INVALID_ADDRESS), m_flavor() { @@ -1272,9 +1272,7 @@ return m_instruction_list; } -//---------------------------------------------------------------------- // Class PseudoInstruction -//---------------------------------------------------------------------- PseudoInstruction::PseudoInstruction() : Instruction(Address(), AddressClass::eUnknown), m_description() {}
diff --git a/src/llvm-project/lldb/source/Core/DumpDataExtractor.cpp b/src/llvm-project/lldb/source/Core/DumpDataExtractor.cpp index 43a026d..aa84370 100644 --- a/src/llvm-project/lldb/source/Core/DumpDataExtractor.cpp +++ b/src/llvm-project/lldb/source/Core/DumpDataExtractor.cpp
@@ -1,9 +1,8 @@ //===-- DumpDataExtractor.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -552,7 +551,7 @@ case eFormatFloat: { TargetSP target_sp; - bool used_apfloat = false; + bool used_upfloat = false; if (exe_scope) target_sp = exe_scope->CalculateTarget(); if (target_sp) { @@ -601,13 +600,13 @@ if (!sv.empty()) { s->Printf("%*.*s", (int)sv.size(), (int)sv.size(), sv.data()); - used_apfloat = true; + used_upfloat = true; } } } } - if (!used_apfloat) { + if (!used_upfloat) { std::ostringstream ss; if (item_byte_size == sizeof(float) || item_byte_size == 2) { float f;
diff --git a/src/llvm-project/lldb/source/Core/DumpRegisterValue.cpp b/src/llvm-project/lldb/source/Core/DumpRegisterValue.cpp index d7196a5..74b0241 100644 --- a/src/llvm-project/lldb/source/Core/DumpRegisterValue.cpp +++ b/src/llvm-project/lldb/source/Core/DumpRegisterValue.cpp
@@ -1,9 +1,8 @@ //===-- DumpRegisterValue.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Core/DynamicLoader.cpp b/src/llvm-project/lldb/source/Core/DynamicLoader.cpp index 72ee3cf..57130d6 100644 --- a/src/llvm-project/lldb/source/Core/DynamicLoader.cpp +++ b/src/llvm-project/lldb/source/Core/DynamicLoader.cpp
@@ -1,9 +1,8 @@ //===-- DynamicLoader.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -39,10 +38,10 @@ PluginManager::GetDynamicLoaderCreateCallbackForPluginName( const_plugin_name); if (create_callback) { - std::unique_ptr<DynamicLoader> instance_ap( + std::unique_ptr<DynamicLoader> instance_up( create_callback(process, true)); - if (instance_ap) - return instance_ap.release(); + if (instance_up) + return instance_up.release(); } } else { for (uint32_t idx = 0; @@ -50,10 +49,10 @@ PluginManager::GetDynamicLoaderCreateCallbackAtIndex(idx)) != nullptr; ++idx) { - std::unique_ptr<DynamicLoader> instance_ap( + std::unique_ptr<DynamicLoader> instance_up( create_callback(process, false)); - if (instance_ap) - return instance_ap.release(); + if (instance_up) + return instance_up.release(); } } return nullptr; @@ -63,10 +62,8 @@ DynamicLoader::~DynamicLoader() = default; -//---------------------------------------------------------------------- // Accessosors to the global setting as to whether to stop at image (shared // library) loading/unloading. -//---------------------------------------------------------------------- bool DynamicLoader::GetStopWhenImagesChange() const { return m_process->GetStopOnSharedLibraryEvents(); @@ -97,7 +94,7 @@ } if (!executable) { - executable = target.GetSharedModule(module_spec); + executable = target.GetOrCreateModule(module_spec, true /* notify */); if (executable.get() != target.GetExecutableModulePointer()) { // Don't load dependent images since we are in dyld where we will // know and find out about all images that are loaded @@ -167,7 +164,8 @@ return module_sp; } - if ((module_sp = target.GetSharedModule(module_spec))) { + if ((module_sp = target.GetOrCreateModule(module_spec, + true /* notify */))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, base_addr_is_offset); return module_sp; @@ -203,7 +201,8 @@ return module_sp; } - if ((module_sp = target.GetSharedModule(new_module_spec))) { + if ((module_sp = target.GetOrCreateModule(new_module_spec, + true /* notify */))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, false); return module_sp; }
diff --git a/src/llvm-project/lldb/source/Core/EmulateInstruction.cpp b/src/llvm-project/lldb/source/Core/EmulateInstruction.cpp index 0fcb2eb..62942fb 100644 --- a/src/llvm-project/lldb/source/Core/EmulateInstruction.cpp +++ b/src/llvm-project/lldb/source/Core/EmulateInstruction.cpp
@@ -1,9 +1,8 @@ //===-- EmulateInstruction.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -72,14 +71,7 @@ return nullptr; } -EmulateInstruction::EmulateInstruction(const ArchSpec &arch) - : m_arch(arch), m_baton(nullptr), m_read_mem_callback(&ReadMemoryDefault), - m_write_mem_callback(&WriteMemoryDefault), - m_read_reg_callback(&ReadRegisterDefault), - m_write_reg_callback(&WriteRegisterDefault), - m_addr(LLDB_INVALID_ADDRESS) { - ::memset(&m_opcode, 0, sizeof(m_opcode)); -} +EmulateInstruction::EmulateInstruction(const ArchSpec &arch) : m_arch(arch) {} bool EmulateInstruction::ReadRegister(const RegisterInfo *reg_info, RegisterValue ®_value) {
diff --git a/src/llvm-project/lldb/source/Core/FileLineResolver.cpp b/src/llvm-project/lldb/source/Core/FileLineResolver.cpp index 0f41207..3cba1c7 100644 --- a/src/llvm-project/lldb/source/Core/FileLineResolver.cpp +++ b/src/llvm-project/lldb/source/Core/FileLineResolver.cpp
@@ -1,9 +1,8 @@ //===-- FileLineResolver.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // FileLineResolver: -//---------------------------------------------------------------------- FileLineResolver::FileLineResolver(const FileSpec &file_spec, uint32_t line_no, bool check_inlines) : Searcher(), m_file_spec(file_spec), m_line_number(line_no),
diff --git a/src/llvm-project/lldb/source/Core/FileSpecList.cpp b/src/llvm-project/lldb/source/Core/FileSpecList.cpp index ae4831b..95133fa 100644 --- a/src/llvm-project/lldb/source/Core/FileSpecList.cpp +++ b/src/llvm-project/lldb/source/Core/FileSpecList.cpp
@@ -1,9 +1,8 @@ //===-- FileSpecList.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,32 +20,17 @@ FileSpecList::FileSpecList() : m_files() {} -FileSpecList::FileSpecList(const FileSpecList &rhs) = default; - FileSpecList::~FileSpecList() = default; -//------------------------------------------------------------------ -// Assignment operator -//------------------------------------------------------------------ -const FileSpecList &FileSpecList::operator=(const FileSpecList &rhs) { - if (this != &rhs) - m_files = rhs.m_files; - return *this; -} - -//------------------------------------------------------------------ // Append the "file_spec" to the end of the file spec list. -//------------------------------------------------------------------ void FileSpecList::Append(const FileSpec &file_spec) { m_files.push_back(file_spec); } -//------------------------------------------------------------------ // Only append the "file_spec" if this list doesn't already contain it. // // Returns true if "file_spec" was added, false if this list already contained // a copy of "file_spec". -//------------------------------------------------------------------ bool FileSpecList::AppendIfUnique(const FileSpec &file_spec) { collection::iterator end = m_files.end(); if (find(m_files.begin(), end, file_spec) == end) { @@ -56,14 +40,10 @@ return false; } -//------------------------------------------------------------------ // Clears the file list. -//------------------------------------------------------------------ void FileSpecList::Clear() { m_files.clear(); } -//------------------------------------------------------------------ // Dumps the file list to the supplied stream pointer "s". -//------------------------------------------------------------------ void FileSpecList::Dump(Stream *s, const char *separator_cstr) const { collection::const_iterator pos, end = m_files.end(); for (pos = m_files.begin(); pos != end; ++pos) { @@ -73,13 +53,11 @@ } } -//------------------------------------------------------------------ // Find the index of the file in the file spec list that matches "file_spec" // starting "start_idx" entries into the file spec list. // // Returns the valid index of the file that matches "file_spec" if it is found, // else std::numeric_limits<uint32_t>::max() is returned. -//------------------------------------------------------------------ size_t FileSpecList::FindFileIndex(size_t start_idx, const FileSpec &file_spec, bool full) const { const size_t num_files = m_files.size(); @@ -104,10 +82,8 @@ return UINT32_MAX; } -//------------------------------------------------------------------ // Returns the FileSpec object at index "idx". If "idx" is out of range, then // an empty FileSpec object will be returned. -//------------------------------------------------------------------ const FileSpec &FileSpecList::GetFileSpecAtIndex(size_t idx) const { if (idx < m_files.size()) return m_files[idx]; @@ -121,12 +97,10 @@ return nullptr; } -//------------------------------------------------------------------ // Return the size in bytes that this object takes in memory. This returns the // size in bytes of this object's member variables and any FileSpec objects its // member variables contain, the result doesn't not include the string values // for the directories any filenames as those are in shared string pools. -//------------------------------------------------------------------ size_t FileSpecList::MemorySize() const { size_t mem_size = sizeof(FileSpecList); collection::const_iterator pos, end = m_files.end(); @@ -137,9 +111,7 @@ return mem_size; } -//------------------------------------------------------------------ // Return the number of files in the file spec list. -//------------------------------------------------------------------ size_t FileSpecList::GetSize() const { return m_files.size(); } size_t FileSpecList::GetFilesMatchingPartialPath(const char *path,
diff --git a/src/llvm-project/lldb/source/Core/FormatEntity.cpp b/src/llvm-project/lldb/source/Core/FormatEntity.cpp index 200008d..1ffbed2 100644 --- a/src/llvm-project/lldb/source/Core/FormatEntity.cpp +++ b/src/llvm-project/lldb/source/Core/FormatEntity.cpp
@@ -1,9 +1,8 @@ //===-- FormatEntity.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -80,108 +79,98 @@ enum FileKind { FileError = 0, Basename, Dirname, Fullpath }; -#define ENTRY(n, t, f) \ +#define ENTRY(n, t) \ + { n, nullptr, FormatEntity::Entry::Type::t, 0, 0, nullptr, false } +#define ENTRY_VALUE(n, t, v) \ + { n, nullptr, FormatEntity::Entry::Type::t, v, 0, nullptr, false } +#define ENTRY_CHILDREN(n, t, c) \ { \ - n, nullptr, FormatEntity::Entry::Type::t, \ - FormatEntity::Entry::FormatType::f, 0, 0, nullptr, false \ - } -#define ENTRY_VALUE(n, t, f, v) \ - { \ - n, nullptr, FormatEntity::Entry::Type::t, \ - FormatEntity::Entry::FormatType::f, v, 0, nullptr, false \ - } -#define ENTRY_CHILDREN(n, t, f, c) \ - { \ - n, nullptr, FormatEntity::Entry::Type::t, \ - FormatEntity::Entry::FormatType::f, 0, \ + n, nullptr, FormatEntity::Entry::Type::t, 0, \ static_cast<uint32_t>(llvm::array_lengthof(c)), c, false \ } -#define ENTRY_CHILDREN_KEEP_SEP(n, t, f, c) \ +#define ENTRY_CHILDREN_KEEP_SEP(n, t, c) \ { \ - n, nullptr, FormatEntity::Entry::Type::t, \ - FormatEntity::Entry::FormatType::f, 0, \ + n, nullptr, FormatEntity::Entry::Type::t, 0, \ static_cast<uint32_t>(llvm::array_lengthof(c)), c, true \ } #define ENTRY_STRING(n, s) \ - { \ - n, s, FormatEntity::Entry::Type::InsertString, \ - FormatEntity::Entry::FormatType::None, 0, 0, nullptr, false \ - } + { n, s, FormatEntity::Entry::Type::EscapeCode, 0, 0, nullptr, false } static FormatEntity::Entry::Definition g_string_entry[] = { - ENTRY("*", ParentString, None)}; + ENTRY("*", ParentString)}; static FormatEntity::Entry::Definition g_addr_entries[] = { - ENTRY("load", AddressLoad, UInt64), ENTRY("file", AddressFile, UInt64), - ENTRY("load", AddressLoadOrFile, UInt64), + ENTRY("load", AddressLoad), + ENTRY("file", AddressFile), + ENTRY("load", AddressLoadOrFile), }; static FormatEntity::Entry::Definition g_file_child_entries[] = { - ENTRY_VALUE("basename", ParentNumber, CString, FileKind::Basename), - ENTRY_VALUE("dirname", ParentNumber, CString, FileKind::Dirname), - ENTRY_VALUE("fullpath", ParentNumber, CString, FileKind::Fullpath)}; + ENTRY_VALUE("basename", ParentNumber, FileKind::Basename), + ENTRY_VALUE("dirname", ParentNumber, FileKind::Dirname), + ENTRY_VALUE("fullpath", ParentNumber, FileKind::Fullpath)}; static FormatEntity::Entry::Definition g_frame_child_entries[] = { - ENTRY("index", FrameIndex, UInt32), - ENTRY("pc", FrameRegisterPC, UInt64), - ENTRY("fp", FrameRegisterFP, UInt64), - ENTRY("sp", FrameRegisterSP, UInt64), - ENTRY("flags", FrameRegisterFlags, UInt64), - ENTRY("no-debug", FrameNoDebug, None), - ENTRY_CHILDREN("reg", FrameRegisterByName, UInt64, g_string_entry), - ENTRY("is-artificial", FrameIsArtificial, UInt32), + ENTRY("index", FrameIndex), + ENTRY("pc", FrameRegisterPC), + ENTRY("fp", FrameRegisterFP), + ENTRY("sp", FrameRegisterSP), + ENTRY("flags", FrameRegisterFlags), + ENTRY("no-debug", FrameNoDebug), + ENTRY_CHILDREN("reg", FrameRegisterByName, g_string_entry), + ENTRY("is-artificial", FrameIsArtificial), }; static FormatEntity::Entry::Definition g_function_child_entries[] = { - ENTRY("id", FunctionID, UInt64), ENTRY("name", FunctionName, CString), - ENTRY("name-without-args", FunctionNameNoArgs, CString), - ENTRY("name-with-args", FunctionNameWithArgs, CString), - ENTRY("addr-offset", FunctionAddrOffset, UInt64), - ENTRY("concrete-only-addr-offset-no-padding", FunctionAddrOffsetConcrete, - UInt64), - ENTRY("line-offset", FunctionLineOffset, UInt64), - ENTRY("pc-offset", FunctionPCOffset, UInt64), - ENTRY("initial-function", FunctionInitial, None), - ENTRY("changed", FunctionChanged, None), - ENTRY("is-optimized", FunctionIsOptimized, None)}; + ENTRY("id", FunctionID), + ENTRY("name", FunctionName), + ENTRY("name-without-args", FunctionNameNoArgs), + ENTRY("name-with-args", FunctionNameWithArgs), + ENTRY("addr-offset", FunctionAddrOffset), + ENTRY("concrete-only-addr-offset-no-padding", FunctionAddrOffsetConcrete), + ENTRY("line-offset", FunctionLineOffset), + ENTRY("pc-offset", FunctionPCOffset), + ENTRY("initial-function", FunctionInitial), + ENTRY("changed", FunctionChanged), + ENTRY("is-optimized", FunctionIsOptimized)}; static FormatEntity::Entry::Definition g_line_child_entries[] = { - ENTRY_CHILDREN("file", LineEntryFile, None, g_file_child_entries), - ENTRY("number", LineEntryLineNumber, UInt32), - ENTRY("column", LineEntryColumn, UInt32), - ENTRY("start-addr", LineEntryStartAddress, UInt64), - ENTRY("end-addr", LineEntryEndAddress, UInt64), + ENTRY_CHILDREN("file", LineEntryFile, g_file_child_entries), + ENTRY("number", LineEntryLineNumber), + ENTRY("column", LineEntryColumn), + ENTRY("start-addr", LineEntryStartAddress), + ENTRY("end-addr", LineEntryEndAddress), }; static FormatEntity::Entry::Definition g_module_child_entries[] = { - ENTRY_CHILDREN("file", ModuleFile, None, g_file_child_entries), + ENTRY_CHILDREN("file", ModuleFile, g_file_child_entries), }; static FormatEntity::Entry::Definition g_process_child_entries[] = { - ENTRY("id", ProcessID, UInt64), - ENTRY_VALUE("name", ProcessFile, CString, FileKind::Basename), - ENTRY_CHILDREN("file", ProcessFile, None, g_file_child_entries), + ENTRY("id", ProcessID), + ENTRY_VALUE("name", ProcessFile, FileKind::Basename), + ENTRY_CHILDREN("file", ProcessFile, g_file_child_entries), }; static FormatEntity::Entry::Definition g_svar_child_entries[] = { - ENTRY("*", ParentString, None)}; + ENTRY("*", ParentString)}; static FormatEntity::Entry::Definition g_var_child_entries[] = { - ENTRY("*", ParentString, None)}; + ENTRY("*", ParentString)}; static FormatEntity::Entry::Definition g_thread_child_entries[] = { - ENTRY("id", ThreadID, UInt64), - ENTRY("protocol_id", ThreadProtocolID, UInt64), - ENTRY("index", ThreadIndexID, UInt32), - ENTRY_CHILDREN("info", ThreadInfo, None, g_string_entry), - ENTRY("queue", ThreadQueue, CString), - ENTRY("name", ThreadName, CString), - ENTRY("stop-reason", ThreadStopReason, CString), - ENTRY("return-value", ThreadReturnValue, CString), - ENTRY("completed-expression", ThreadCompletedExpression, CString), + ENTRY("id", ThreadID), + ENTRY("protocol_id", ThreadProtocolID), + ENTRY("index", ThreadIndexID), + ENTRY_CHILDREN("info", ThreadInfo, g_string_entry), + ENTRY("queue", ThreadQueue), + ENTRY("name", ThreadName), + ENTRY("stop-reason", ThreadStopReason), + ENTRY("return-value", ThreadReturnValue), + ENTRY("completed-expression", ThreadCompletedExpression), }; static FormatEntity::Entry::Definition g_target_child_entries[] = { - ENTRY("arch", TargetArch, CString), + ENTRY("arch", TargetArch), }; #define _TO_STR2(_val) #_val @@ -224,8 +213,8 @@ }; static FormatEntity::Entry::Definition g_ansi_entries[] = { - ENTRY_CHILDREN("fg", Invalid, None, g_ansi_fg_entries), - ENTRY_CHILDREN("bg", Invalid, None, g_ansi_bg_entries), + ENTRY_CHILDREN("fg", Invalid, g_ansi_fg_entries), + ENTRY_CHILDREN("bg", Invalid, g_ansi_bg_entries), ENTRY_STRING("normal", ANSI_ESC_START _TO_STR(ANSI_CTRL_NORMAL) ANSI_ESC_END), ENTRY_STRING("bold", ANSI_ESC_START _TO_STR(ANSI_CTRL_BOLD) ANSI_ESC_END), @@ -247,37 +236,33 @@ }; static FormatEntity::Entry::Definition g_script_child_entries[] = { - ENTRY("frame", ScriptFrame, None), - ENTRY("process", ScriptProcess, None), - ENTRY("target", ScriptTarget, None), - ENTRY("thread", ScriptThread, None), - ENTRY("var", ScriptVariable, None), - ENTRY("svar", ScriptVariableSynthetic, None), - ENTRY("thread", ScriptThread, None), + ENTRY("frame", ScriptFrame), ENTRY("process", ScriptProcess), + ENTRY("target", ScriptTarget), ENTRY("thread", ScriptThread), + ENTRY("var", ScriptVariable), ENTRY("svar", ScriptVariableSynthetic), + ENTRY("thread", ScriptThread), }; static FormatEntity::Entry::Definition g_top_level_entries[] = { - ENTRY_CHILDREN("addr", AddressLoadOrFile, UInt64, g_addr_entries), - ENTRY("addr-file-or-load", AddressLoadOrFile, UInt64), - ENTRY_CHILDREN("ansi", Invalid, None, g_ansi_entries), - ENTRY("current-pc-arrow", CurrentPCArrow, CString), - ENTRY_CHILDREN("file", File, CString, g_file_child_entries), - ENTRY("language", Lang, CString), - ENTRY_CHILDREN("frame", Invalid, None, g_frame_child_entries), - ENTRY_CHILDREN("function", Invalid, None, g_function_child_entries), - ENTRY_CHILDREN("line", Invalid, None, g_line_child_entries), - ENTRY_CHILDREN("module", Invalid, None, g_module_child_entries), - ENTRY_CHILDREN("process", Invalid, None, g_process_child_entries), - ENTRY_CHILDREN("script", Invalid, None, g_script_child_entries), - ENTRY_CHILDREN_KEEP_SEP("svar", VariableSynthetic, None, - g_svar_child_entries), - ENTRY_CHILDREN("thread", Invalid, None, g_thread_child_entries), - ENTRY_CHILDREN("target", Invalid, None, g_target_child_entries), - ENTRY_CHILDREN_KEEP_SEP("var", Variable, None, g_var_child_entries), + ENTRY_CHILDREN("addr", AddressLoadOrFile, g_addr_entries), + ENTRY("addr-file-or-load", AddressLoadOrFile), + ENTRY_CHILDREN("ansi", Invalid, g_ansi_entries), + ENTRY("current-pc-arrow", CurrentPCArrow), + ENTRY_CHILDREN("file", File, g_file_child_entries), + ENTRY("language", Lang), + ENTRY_CHILDREN("frame", Invalid, g_frame_child_entries), + ENTRY_CHILDREN("function", Invalid, g_function_child_entries), + ENTRY_CHILDREN("line", Invalid, g_line_child_entries), + ENTRY_CHILDREN("module", Invalid, g_module_child_entries), + ENTRY_CHILDREN("process", Invalid, g_process_child_entries), + ENTRY_CHILDREN("script", Invalid, g_script_child_entries), + ENTRY_CHILDREN_KEEP_SEP("svar", VariableSynthetic, g_svar_child_entries), + ENTRY_CHILDREN("thread", Invalid, g_thread_child_entries), + ENTRY_CHILDREN("target", Invalid, g_target_child_entries), + ENTRY_CHILDREN_KEEP_SEP("var", Variable, g_var_child_entries), }; static FormatEntity::Entry::Definition g_root = - ENTRY_CHILDREN("<root>", Root, None, g_top_level_entries); + ENTRY_CHILDREN("<root>", Root, g_top_level_entries); FormatEntity::Entry::Entry(llvm::StringRef s) : string(s.data(), s.size()), printf_format(), children(), @@ -322,7 +307,7 @@ ENUM_TO_CSTR(Invalid); ENUM_TO_CSTR(ParentNumber); ENUM_TO_CSTR(ParentString); - ENUM_TO_CSTR(InsertString); + ENUM_TO_CSTR(EscapeCode); ENUM_TO_CSTR(Root); ENUM_TO_CSTR(String); ENUM_TO_CSTR(Scope); @@ -411,7 +396,7 @@ if (target) { ScriptInterpreter *script_interpreter = - target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); + target->GetDebugger().GetScriptInterpreter(); if (script_interpreter) { Status error; std::string script_output; @@ -477,9 +462,8 @@ // can be discontiguous. Block *inline_block = sc->block->GetContainingInlinedBlock(); AddressRange inline_range; - if (inline_block && - inline_block->GetRangeContainingAddress(format_addr, - inline_range)) + if (inline_block && inline_block->GetRangeContainingAddress( + format_addr, inline_range)) func_addr = inline_range.GetBaseAddress(); } } else if (sc->symbol && sc->symbol->ValueIsAddress()) @@ -1118,9 +1102,18 @@ // FormatEntity::Entry::Definition encoding case Entry::Type::ParentString: // Only used for // FormatEntity::Entry::Definition encoding - case Entry::Type::InsertString: // Only used for - // FormatEntity::Entry::Definition encoding return false; + case Entry::Type::EscapeCode: + if (exe_ctx) { + if (Target *target = exe_ctx->GetTargetPtr()) { + Debugger &debugger = target->GetDebugger(); + if (debugger.GetUseColor()) { + s.PutCString(entry.string); + } + } + } + // Always return true, so colors being disabled is transparent. + return true; case Entry::Type::Root: for (const auto &child : entry.children) { @@ -1715,8 +1708,9 @@ var_representation = buffer; } else var_value_sp->DumpPrintableRepresentation( - ss, ValueObject::ValueObjectRepresentationStyle:: - eValueObjectRepresentationStyleSummary, + ss, + ValueObject::ValueObjectRepresentationStyle:: + eValueObjectRepresentationStyleSummary, eFormatDefault, ValueObject::PrintableRepresentationSpecialCases::eAllow, false); @@ -1911,7 +1905,7 @@ entry.number = entry_def->data; return error; // Success - case FormatEntity::Entry::Type::InsertString: + case FormatEntity::Entry::Type::EscapeCode: entry.type = entry_def->type; entry.string = entry_def->string; return error; // Success @@ -2280,13 +2274,7 @@ return error; } } - // Check if this entry just wants to insert a constant string value - // into the parent_entry, if so, insert the string with AppendText, - // else append the entry to the parent_entry. - if (entry.type == Entry::Type::InsertString) - parent_entry.AppendText(entry.string.c_str()); - else - parent_entry.AppendEntry(std::move(entry)); + parent_entry.AppendEntry(std::move(entry)); } } break;
diff --git a/src/llvm-project/lldb/source/Core/Highlighter.cpp b/src/llvm-project/lldb/source/Core/Highlighter.cpp index c7dd0db..0b0aa96 100644 --- a/src/llvm-project/lldb/source/Core/Highlighter.cpp +++ b/src/llvm-project/lldb/source/Core/Highlighter.cpp
@@ -1,9 +1,8 @@ //===-- Highlighter.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Core/IOHandler.cpp b/src/llvm-project/lldb/source/Core/IOHandler.cpp index 5c0eea5..c3c7220 100644 --- a/src/llvm-project/lldb/source/Core/IOHandler.cpp +++ b/src/llvm-project/lldb/source/Core/IOHandler.cpp
@@ -1,9 +1,8 @@ //===-- IOHandler.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -77,16 +76,19 @@ StreamFileSP(), // Adopt STDIN from top input reader StreamFileSP(), // Adopt STDOUT from top input reader StreamFileSP(), // Adopt STDERR from top input reader - 0) // Flags -{} + 0, // Flags + nullptr // Shadow file recorder + ) {} IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type, const lldb::StreamFileSP &input_sp, const lldb::StreamFileSP &output_sp, - const lldb::StreamFileSP &error_sp, uint32_t flags) + const lldb::StreamFileSP &error_sp, uint32_t flags, + repro::DataRecorder *data_recorder) : m_debugger(debugger), m_input_sp(input_sp), m_output_sp(output_sp), - m_error_sp(error_sp), m_popped(false), m_flags(flags), m_type(type), - m_user_data(nullptr), m_done(false), m_active(false) { + m_error_sp(error_sp), m_data_recorder(data_recorder), m_popped(false), + m_flags(flags), m_type(type), m_user_data(nullptr), m_done(false), + m_active(false) { // If any files are not specified, then adopt them from the top input reader. if (!m_input_sp || !m_output_sp || !m_error_sp) debugger.AdoptTopIOHandlerFilesIfInvalid(m_input_sp, m_output_sp, @@ -154,7 +156,7 @@ llvm::StringRef(), // No continuation prompt false, // Multi-line false, // Don't colorize the prompt (i.e. the confirm message.) - 0, *this), + 0, *this, nullptr), m_default_response(default_response), m_user_response(default_response) { StreamString prompt_stream; prompt_stream.PutCString(prompt); @@ -231,7 +233,7 @@ matches, descriptions); case Completion::Expression: { CompletionResult result; - CompletionRequest request(current_line, current_line - cursor, + CompletionRequest request(current_line, cursor - current_line, skip_first_n_matches, max_matches, result); CommandCompletions::InvokeCommonCompletionCallbacks( io_handler.GetDebugger().GetCommandInterpreter(), @@ -265,7 +267,7 @@ const char *editline_name, // Used for saving history files llvm::StringRef prompt, llvm::StringRef continuation_prompt, bool multi_line, bool color_prompts, uint32_t line_number_start, - IOHandlerDelegate &delegate) + IOHandlerDelegate &delegate, repro::DataRecorder *data_recorder) : IOHandlerEditline(debugger, type, StreamFileSP(), // Inherit input from top input reader StreamFileSP(), // Inherit output from top input reader @@ -273,7 +275,7 @@ 0, // Flags editline_name, // Used for saving history files prompt, continuation_prompt, multi_line, color_prompts, - line_number_start, delegate) {} + line_number_start, delegate, data_recorder) {} IOHandlerEditline::IOHandlerEditline( Debugger &debugger, IOHandler::Type type, @@ -282,10 +284,11 @@ const char *editline_name, // Used for saving history files llvm::StringRef prompt, llvm::StringRef continuation_prompt, bool multi_line, bool color_prompts, uint32_t line_number_start, - IOHandlerDelegate &delegate) - : IOHandler(debugger, type, input_sp, output_sp, error_sp, flags), + IOHandlerDelegate &delegate, repro::DataRecorder *data_recorder) + : IOHandler(debugger, type, input_sp, output_sp, error_sp, flags, + data_recorder), #ifndef LLDB_DISABLE_LIBEDIT - m_editline_ap(), + m_editline_up(), #endif m_delegate(delegate), m_prompt(), m_continuation_prompt(), m_current_lines_ptr(nullptr), m_base_line_number(line_number_start), @@ -300,17 +303,17 @@ use_editline = m_input_sp->GetFile().GetIsRealTerminal(); if (use_editline) { - m_editline_ap.reset(new Editline(editline_name, GetInputFILE(), + m_editline_up.reset(new Editline(editline_name, GetInputFILE(), GetOutputFILE(), GetErrorFILE(), m_color_prompts)); - m_editline_ap->SetIsInputCompleteCallback(IsInputCompleteCallback, this); - m_editline_ap->SetAutoCompleteCallback(AutoCompleteCallback, this); + m_editline_up->SetIsInputCompleteCallback(IsInputCompleteCallback, this); + m_editline_up->SetAutoCompleteCallback(AutoCompleteCallback, this); // See if the delegate supports fixing indentation const char *indent_chars = delegate.IOHandlerGetFixIndentationCharacters(); if (indent_chars) { // The delegate does support indentation, hook it up so when any // indentation character is typed, the delegate gets a chance to fix it - m_editline_ap->SetFixIndentationCallback(FixIndentationCallback, this, + m_editline_up->SetFixIndentationCallback(FixIndentationCallback, this, indent_chars); } } @@ -322,13 +325,13 @@ IOHandlerEditline::~IOHandlerEditline() { #ifndef LLDB_DISABLE_LIBEDIT - m_editline_ap.reset(); + m_editline_up.reset(); #endif } void IOHandlerEditline::Activate() { IOHandler::Activate(); - m_delegate.IOHandlerActivated(*this); + m_delegate.IOHandlerActivated(*this, GetIsInteractive()); } void IOHandlerEditline::Deactivate() { @@ -338,8 +341,11 @@ bool IOHandlerEditline::GetLine(std::string &line, bool &interrupted) { #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) { - return m_editline_ap->GetLine(line, interrupted); + if (m_editline_up) { + bool b = m_editline_up->GetLine(line, interrupted); + if (m_data_recorder) + m_data_recorder->Record(line, true); + return b; } else { #endif line.clear(); @@ -368,7 +374,18 @@ bool got_line = false; m_editing = true; while (!done) { +#ifdef _WIN32 + // ReadFile on Windows is supposed to set ERROR_OPERATION_ABORTED + // according to the docs on MSDN. However, this has evidently been a + // known bug since Windows 8. Therefore, we can't detect if a signal + // interrupted in the fgets. So pressing ctrl-c causes the repl to end + // and the process to exit. A temporary workaround is just to attempt to + // fgets twice until this bug is fixed. + if (fgets(buffer, sizeof(buffer), in) == nullptr && + fgets(buffer, sizeof(buffer), in) == nullptr) { +#else if (fgets(buffer, sizeof(buffer), in) == nullptr) { +#endif const int saved_errno = errno; if (feof(in)) done = true; @@ -395,6 +412,8 @@ } } m_editing = false; + if (m_data_recorder && got_line) + m_data_recorder->Record(line, true); // We might have gotten a newline on a line by itself make sure to return // true in this case. return got_line; @@ -441,8 +460,8 @@ const char *IOHandlerEditline::GetPrompt() { #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) { - return m_editline_ap->GetPrompt(); + if (m_editline_up) { + return m_editline_up->GetPrompt(); } else { #endif if (m_prompt.empty()) @@ -457,8 +476,8 @@ m_prompt = prompt; #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) - m_editline_ap->SetPrompt(m_prompt.empty() ? nullptr : m_prompt.c_str()); + if (m_editline_up) + m_editline_up->SetPrompt(m_prompt.empty() ? nullptr : m_prompt.c_str()); #endif return true; } @@ -472,8 +491,8 @@ m_continuation_prompt = prompt; #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) - m_editline_ap->SetContinuationPrompt(m_continuation_prompt.empty() + if (m_editline_up) + m_editline_up->SetContinuationPrompt(m_continuation_prompt.empty() ? nullptr : m_continuation_prompt.c_str()); #endif @@ -485,8 +504,8 @@ uint32_t IOHandlerEditline::GetCurrentLineIndex() const { #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) - return m_editline_ap->GetCurrentLine(); + if (m_editline_up) + return m_editline_up->GetCurrentLine(); #endif return m_curr_line_idx; } @@ -496,8 +515,8 @@ bool success = false; #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) { - return m_editline_ap->GetLines(m_base_line_number, lines, interrupted); + if (m_editline_up) { + return m_editline_up->GetLines(m_base_line_number, lines, interrupted); } else { #endif bool done = false; @@ -565,8 +584,8 @@ void IOHandlerEditline::Cancel() { #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) - m_editline_ap->Cancel(); + if (m_editline_up) + m_editline_up->Cancel(); #endif } @@ -576,23 +595,23 @@ return true; #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) - return m_editline_ap->Interrupt(); + if (m_editline_up) + return m_editline_up->Interrupt(); #endif return false; } void IOHandlerEditline::GotEOF() { #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) - m_editline_ap->Interrupt(); + if (m_editline_up) + m_editline_up->Interrupt(); #endif } void IOHandlerEditline::PrintAsync(Stream *stream, const char *s, size_t len) { #ifndef LLDB_DISABLE_LIBEDIT - if (m_editline_ap) - m_editline_ap->PrintAsync(stream, s, len); + if (m_editline_up) + m_editline_up->PrintAsync(stream, s, len); else #endif { @@ -994,20 +1013,15 @@ WindowSP CreateSubWindow(const char *name, const Rect &bounds, bool make_active) { - WindowSP subwindow_sp; - if (m_window) { - subwindow_sp.reset(new Window( - name, ::subwin(m_window, bounds.size.height, bounds.size.width, - bounds.origin.y, bounds.origin.x), - true)); - subwindow_sp->m_is_subwin = true; - } else { - subwindow_sp.reset( - new Window(name, ::newwin(bounds.size.height, bounds.size.width, - bounds.origin.y, bounds.origin.x), - true)); - subwindow_sp->m_is_subwin = false; - } + auto get_window = [this, &bounds]() { + return m_window + ? ::subwin(m_window, bounds.size.height, bounds.size.width, + bounds.origin.y, bounds.origin.x) + : ::newwin(bounds.size.height, bounds.size.width, + bounds.origin.y, bounds.origin.x); + }; + WindowSP subwindow_sp = std::make_shared<Window>(name, get_window(), true); + subwindow_sp->m_is_subwin = subwindow_sp.operator bool(); subwindow_sp->m_parent = this; if (make_active) { m_prev_active_window_idx = m_curr_active_window_idx; @@ -1075,9 +1089,7 @@ operator WINDOW *() { return m_window; } - //---------------------------------------------------------------------- // Window drawing utilities - //---------------------------------------------------------------------- void DrawTitleBox(const char *title, const char *bottom_message = nullptr) { attr_t attr = 0; if (IsActive()) @@ -1128,10 +1140,10 @@ const char *text = m_delegate_sp->WindowDelegateGetHelpText(); KeyHelp *key_help = m_delegate_sp->WindowDelegateGetKeyHelp(); if ((text && text[0]) || key_help) { - std::unique_ptr<HelpDialogDelegate> help_delegate_ap( + std::unique_ptr<HelpDialogDelegate> help_delegate_up( new HelpDialogDelegate(text, key_help)); - const size_t num_lines = help_delegate_ap->GetNumLines(); - const size_t max_length = help_delegate_ap->GetMaxLineLength(); + const size_t num_lines = help_delegate_up->GetNumLines(); + const size_t max_length = help_delegate_up->GetMaxLineLength(); Rect bounds = GetBounds(); bounds.Inset(1, 1); if (max_length + 4 < static_cast<size_t>(bounds.size.width)) { @@ -1162,7 +1174,7 @@ else help_window_sp = CreateSubWindow("Help", bounds, true); help_window_sp->SetDelegate( - WindowDelegateSP(help_delegate_ap.release())); + WindowDelegateSP(help_delegate_up.release())); return true; } } @@ -1882,7 +1894,7 @@ WindowSP &GetMainWindow() { if (!m_window_sp) - m_window_sp.reset(new Window("main", stdscr, false)); + m_window_sp = std::make_shared<Window>("main", stdscr, false); return m_window_sp; } @@ -2509,7 +2521,7 @@ return; // Children are already up to date if (!m_frame_delegate_sp) { // Always expand the thread item the first time we show it - m_frame_delegate_sp.reset(new FrameTreeDelegate()); + m_frame_delegate_sp = std::make_shared<FrameTreeDelegate>(); } m_stop_id = process_sp->GetStopID(); @@ -2601,7 +2613,8 @@ if (!m_thread_delegate_sp) { // Always expand the thread item the first time we show it // item.Expand(); - m_thread_delegate_sp.reset(new ThreadTreeDelegate(m_debugger)); + m_thread_delegate_sp = + std::make_shared<ThreadTreeDelegate>(m_debugger); } TreeItem t(&item, *m_thread_delegate_sp, false); @@ -3934,12 +3947,10 @@ m_debugger.GetSourceManager().GetFile(m_sc.line_entry.file); if (m_file_sp) { const size_t num_lines = m_file_sp->GetNumLines(); - int m_line_width = 1; + m_line_width = 1; for (size_t n = num_lines; n >= 10; n = n / 10) ++m_line_width; - snprintf(m_line_format, sizeof(m_line_format), " %%%iu ", - m_line_width); if (num_lines < num_visible_lines || m_selected_line < num_visible_lines) m_first_visible_line = 0; @@ -4056,7 +4067,7 @@ if (bp_attr) window.AttributeOn(bp_attr); - window.Printf(m_line_format, curr_line + 1); + window.Printf(" %*u ", m_line_width, curr_line + 1); if (bp_attr) window.AttributeOff(bp_attr); @@ -4482,7 +4493,6 @@ AddressRange m_disassembly_range; StreamString m_title; lldb::user_id_t m_tid; - char m_line_format[8]; int m_line_width; uint32_t m_selected_line; // The selected line uint32_t m_pc_line; // The line with the PC
diff --git a/src/llvm-project/lldb/source/Core/Mangled.cpp b/src/llvm-project/lldb/source/Core/Mangled.cpp index 20fea1d..c6759cc 100644 --- a/src/llvm-project/lldb/source/Core/Mangled.cpp +++ b/src/llvm-project/lldb/source/Core/Mangled.cpp
@@ -1,9 +1,8 @@ //===-- Mangled.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -73,7 +72,7 @@ return cstring_mangling_scheme(s) != Mangled::eManglingSchemeNone; } -static const ConstString & +static ConstString get_demangled_name_without_arguments(ConstString mangled, ConstString demangled) { // This pair is <mangled name, demangled name without function arguments> @@ -124,46 +123,13 @@ return g_last_mangled; } -static void remove_rust_hash(char *str) { - char *iter = str + strlen(str) - 1; - size_t hashcount = 0; - while (true) { - if (iter == str) { - // Hit the start of the string too early. - return; - } - if ((*iter >= '0' && *iter <= '9') || - (*iter >= 'a' && *iter <= 'f')) { - ++hashcount; - --iter; - if (hashcount > 16) { - // Too many hash chars. - return; - } - } else { - // Not a hash char. - break; - } - } - if (*iter != 'h' || hashcount < 5 || str + 2 >= iter || - iter[-1] != ':' || iter[-2] != ':') { - return; - } - iter[-2] = '\0'; -} - - #pragma mark Mangled -//---------------------------------------------------------------------- // Default constructor -//---------------------------------------------------------------------- Mangled::Mangled() : m_mangled(), m_demangled() {} -//---------------------------------------------------------------------- // Constructor with an optional string and a boolean indicating if it is the // mangled version. -//---------------------------------------------------------------------- -Mangled::Mangled(const ConstString &s, bool mangled) +Mangled::Mangled(ConstString s, bool mangled) : m_mangled(), m_demangled() { if (s) SetValue(s, mangled); @@ -174,7 +140,7 @@ SetValue(ConstString(name), is_mangled); } -Mangled::Mangled(const ConstString &s) : m_mangled(), m_demangled() { +Mangled::Mangled(ConstString s) : m_mangled(), m_demangled() { if (s) SetValue(s); } @@ -184,55 +150,43 @@ SetValue(ConstString(name)); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- Mangled::~Mangled() {} -//---------------------------------------------------------------------- // Convert to pointer operator. This allows code to check any Mangled objects // to see if they contain anything valid using code such as: // // Mangled mangled(...); // if (mangled) // { ... -//---------------------------------------------------------------------- Mangled::operator void *() const { - return (m_mangled) ? const_cast<Mangled *>(this) : NULL; + return (m_mangled) ? const_cast<Mangled *>(this) : nullptr; } -//---------------------------------------------------------------------- // Logical NOT operator. This allows code to check any Mangled objects to see // if they are invalid using code such as: // // Mangled mangled(...); // if (!file_spec) // { ... -//---------------------------------------------------------------------- bool Mangled::operator!() const { return !m_mangled; } -//---------------------------------------------------------------------- // Clear the mangled and demangled values. -//---------------------------------------------------------------------- void Mangled::Clear() { m_mangled.Clear(); m_demangled.Clear(); } -//---------------------------------------------------------------------- // Compare the string values. -//---------------------------------------------------------------------- int Mangled::Compare(const Mangled &a, const Mangled &b) { return ConstString::Compare( a.GetName(lldb::eLanguageTypeUnknown, ePreferMangled), b.GetName(lldb::eLanguageTypeUnknown, ePreferMangled)); } -//---------------------------------------------------------------------- // Set the string value in this objects. If "mangled" is true, then the mangled // named is set with the new value in "s", else the demangled name is set. -//---------------------------------------------------------------------- -void Mangled::SetValue(const ConstString &s, bool mangled) { +void Mangled::SetValue(ConstString s, bool mangled) { if (s) { if (mangled) { m_demangled.Clear(); @@ -247,7 +201,7 @@ } } -void Mangled::SetValue(const ConstString &name) { +void Mangled::SetValue(ConstString name) { if (name) { if (cstring_is_mangled(name.GetCString())) { m_demangled.Clear(); @@ -262,9 +216,7 @@ } } -//---------------------------------------------------------------------- // Local helpers for different demangling implementations. -//---------------------------------------------------------------------- static char *GetMSVCDemangledStr(const char *M) { #if defined(_MSC_VER) const size_t demangled_length = 2048; @@ -317,10 +269,8 @@ return demangled_cstr; } -//---------------------------------------------------------------------- // Explicit demangling for scheduled requests during batch processing. This // makes use of ItaniumPartialDemangler's rich demangle info -//---------------------------------------------------------------------- bool Mangled::DemangleWithRichManglingInfo( RichManglingContext &context, SkipMangledNameFn *skip_mangled_name) { // We need to generate and cache the demangled name. @@ -386,13 +336,11 @@ llvm_unreachable("Fully covered switch above!"); } -//---------------------------------------------------------------------- // Generate the demangled name on demand using this accessor. Code in this // class will need to use this accessor if it wishes to decode the demangled // name. The result is cached and will be kept until a new string value is // supplied to this object, or until the end of the object's lifetime. -//---------------------------------------------------------------------- -const ConstString & +ConstString Mangled::GetDemangledName(lldb::LanguageType language) const { // Check to make sure we have a valid mangled name and that we haven't // already decoded our mangled name. @@ -416,11 +364,6 @@ break; case eManglingSchemeItanium: { demangled_name = GetItaniumDemangledStr(mangled_name); - - if (language == lldb::eLanguageTypeRust) { - remove_rust_hash(demangled_name); - } - break; } case eManglingSchemeNone: @@ -456,9 +399,7 @@ return demangled && regex.Execute(demangled.AsCString()); } -//---------------------------------------------------------------------- // Get the demangled name if there is one, else return the mangled name. -//---------------------------------------------------------------------- ConstString Mangled::GetName(lldb::LanguageType language, Mangled::NamePreference preference) const { if (preference == ePreferMangled && m_mangled) @@ -479,10 +420,8 @@ return demangled; } -//---------------------------------------------------------------------- // Dump a Mangled object to stream "s". We don't force our demangled name to be // computed currently (we don't use the accessor). -//---------------------------------------------------------------------- void Mangled::Dump(Stream *s) const { if (m_mangled) { *s << ", mangled = " << m_mangled; @@ -493,10 +432,8 @@ } } -//---------------------------------------------------------------------- // Dumps a debug version of this string with extra object and state information // to stream "s". -//---------------------------------------------------------------------- void Mangled::DumpDebug(Stream *s) const { s->Printf("%*p: Mangled mangled = ", static_cast<int>(sizeof(void *) * 2), static_cast<const void *>(this)); @@ -505,33 +442,27 @@ m_demangled.DumpDebug(s); } -//---------------------------------------------------------------------- // Return the size in byte that this object takes in memory. The size includes // the size of the objects it owns, and not the strings that it references // because they are shared strings. -//---------------------------------------------------------------------- size_t Mangled::MemorySize() const { return m_mangled.MemorySize() + m_demangled.MemorySize(); } -//---------------------------------------------------------------------- // We "guess" the language because we can't determine a symbol's language from // it's name. For example, a Pascal symbol can be mangled using the C++ // Itanium scheme, and defined in a compilation unit within the same module as // other C++ units. In addition, different targets could have different ways // of mangling names from a given language, likewise the compilation units // within those targets. -//---------------------------------------------------------------------- lldb::LanguageType Mangled::GuessLanguage() const { ConstString mangled = GetMangledName(); if (mangled) { - if (GetDemangledName(lldb::eLanguageTypeUnknown)) { - const char *mangled_name = mangled.GetCString(); - if (CPlusPlusLanguage::IsCPPMangledName(mangled_name)) - return lldb::eLanguageTypeC_plus_plus; - else if (ObjCLanguage::IsPossibleObjCMethodName(mangled_name)) - return lldb::eLanguageTypeObjC; - } + const char *mangled_name = mangled.GetCString(); + if (CPlusPlusLanguage::IsCPPMangledName(mangled_name)) + return lldb::eLanguageTypeC_plus_plus; + else if (ObjCLanguage::IsPossibleObjCMethodName(mangled_name)) + return lldb::eLanguageTypeObjC; } else { // ObjC names aren't really mangled, so they won't necessarily be in the // mangled name slot. @@ -544,14 +475,12 @@ return lldb::eLanguageTypeUnknown; } -//---------------------------------------------------------------------- // Dump OBJ to the supplied stream S. -//---------------------------------------------------------------------- Stream &operator<<(Stream &s, const Mangled &obj) { if (obj.GetMangledName()) s << "mangled = '" << obj.GetMangledName() << "'"; - const ConstString &demangled = + ConstString demangled = obj.GetDemangledName(lldb::eLanguageTypeUnknown); if (demangled) s << ", demangled = '" << demangled << '\'';
diff --git a/src/llvm-project/lldb/source/Core/Module.cpp b/src/llvm-project/lldb/source/Core/Module.cpp index b48d3cc..153d5a7 100644 --- a/src/llvm-project/lldb/source/Core/Module.cpp +++ b/src/llvm-project/lldb/source/Core/Module.cpp
@@ -1,9 +1,8 @@ //===-- Module.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -278,8 +277,8 @@ // function calls back into this module object. The ordering is important // here because symbol files can require the module object file. So we tear // down the symbol file first, then the object file. - m_sections_ap.reset(); - m_symfile_ap.reset(); + m_sections_up.reset(); + m_symfile_up.reset(); m_objfile_sp.reset(); } @@ -292,13 +291,13 @@ std::lock_guard<std::recursive_mutex> guard(m_mutex); if (process_sp) { m_did_load_objfile = true; - auto data_ap = llvm::make_unique<DataBufferHeap>(size_to_read, 0); + auto data_up = llvm::make_unique<DataBufferHeap>(size_to_read, 0); Status readmem_error; const size_t bytes_read = - process_sp->ReadMemory(header_addr, data_ap->GetBytes(), - data_ap->GetByteSize(), readmem_error); + process_sp->ReadMemory(header_addr, data_up->GetBytes(), + data_up->GetByteSize(), readmem_error); if (bytes_read == size_to_read) { - DataBufferSP data_sp(data_ap.release()); + DataBufferSP data_sp(data_up.release()); m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp); if (m_objfile_sp) { @@ -310,6 +309,10 @@ // file's architecture since it might differ in vendor/os if some // parts were unknown. m_arch = m_objfile_sp->GetArchitecture(); + + // Augment the arch with the target's information in case + // we are unable to extract the os/environment from memory. + m_arch.MergeFrom(process_sp->GetTarget().GetArchitecture()); } else { error.SetErrorString("unable to find suitable object file plug-in"); } @@ -331,7 +334,7 @@ ObjectFile *obj_file = GetObjectFile(); if (obj_file != nullptr) { - obj_file->GetUUID(&m_uuid); + m_uuid = obj_file->GetUUID(); m_did_set_uuid = true; } } @@ -595,7 +598,7 @@ return sc_list.GetSize() - initial_count; } -size_t Module::FindGlobalVariables(const ConstString &name, +size_t Module::FindGlobalVariables(ConstString name, const CompilerDeclContext *parent_decl_ctx, size_t max_matches, VariableList &variables) { @@ -635,7 +638,7 @@ return sc_list.GetSize() - start_size; } -Module::LookupInfo::LookupInfo(const ConstString &name, +Module::LookupInfo::LookupInfo(ConstString name, FunctionNameType name_type_mask, LanguageType language) : m_name(name), m_lookup_name(), m_language(language), @@ -795,7 +798,7 @@ } } -size_t Module::FindFunctions(const ConstString &name, +size_t Module::FindFunctions(ConstString name, const CompilerDeclContext *parent_decl_ctx, FunctionNameType name_type_mask, bool include_symbols, bool include_inlines, @@ -943,7 +946,7 @@ } size_t Module::FindTypes_Impl( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeMap &types) { @@ -956,7 +959,7 @@ return 0; } -size_t Module::FindTypesInNamespace(const ConstString &type_name, +size_t Module::FindTypesInNamespace(ConstString type_name, const CompilerDeclContext *parent_decl_ctx, size_t max_matches, TypeList &type_list) { const bool append = true; @@ -974,7 +977,7 @@ } lldb::TypeSP Module::FindFirstType(const SymbolContext &sc, - const ConstString &name, bool exact_match) { + ConstString name, bool exact_match) { TypeList type_list; llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files; const size_t num_matches = @@ -985,7 +988,7 @@ } size_t Module::FindTypes( - const ConstString &name, bool exact_match, size_t max_matches, + ConstString name, bool exact_match, size_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeList &types) { size_t num_matches = 0; @@ -1050,17 +1053,17 @@ if (obj_file != nullptr) { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); - m_symfile_ap.reset( + m_symfile_up.reset( SymbolVendor::FindPlugin(shared_from_this(), feedback_strm)); m_did_load_symbol_vendor = true; } } } - return m_symfile_ap.get(); + return m_symfile_up.get(); } void Module::SetFileSpecAndObjectName(const FileSpec &file, - const ConstString &object_name) { + ConstString object_name) { // Container objects whose paths do not specify a file directly can call this // function to correct the file and object names. m_file = file; @@ -1117,7 +1120,7 @@ const int format_len = strlen(format); if (format_len > 0) { const char last_char = format[format_len - 1]; - if (last_char != '\n' || last_char != '\r') + if (last_char != '\n' && last_char != '\r') strm.EOL(); } Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData()); @@ -1149,7 +1152,7 @@ const int format_len = strlen(format); if (format_len > 0) { const char last_char = format[format_len - 1]; - if (last_char != '\n' || last_char != '\r') + if (last_char != '\n' && last_char != '\r') strm.EOL(); } strm.PutCString("The debug session should be aborted as the original " @@ -1175,7 +1178,7 @@ const int format_len = strlen(format); if (format_len > 0) { const char last_char = format[format_len - 1]; - if (last_char != '\n' || last_char != '\r') + if (last_char != '\n' && last_char != '\r') strm.EOL(); } Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData()); @@ -1243,7 +1246,7 @@ return nullptr; } -const ConstString &Module::GetObjectName() const { return m_object_name; } +ConstString Module::GetObjectName() const { return m_object_name; } ObjectFile *Module::GetObjectFile() { if (!m_did_load_objfile.load()) { @@ -1279,13 +1282,13 @@ } SectionList *Module::GetSectionList() { - // Populate m_sections_ap with sections from objfile. - if (!m_sections_ap) { + // Populate m_sections_up with sections from objfile. + if (!m_sections_up) { ObjectFile *obj_file = GetObjectFile(); if (obj_file != nullptr) obj_file->CreateSections(*GetUnifiedSectionList()); } - return m_sections_ap.get(); + return m_sections_up.get(); } void Module::SectionFileAddressesChanged() { @@ -1297,13 +1300,19 @@ sym_vendor->SectionFileAddressesChanged(); } -SectionList *Module::GetUnifiedSectionList() { - if (!m_sections_ap) - m_sections_ap = llvm::make_unique<SectionList>(); - return m_sections_ap.get(); +UnwindTable &Module::GetUnwindTable() { + if (!m_unwind_table) + m_unwind_table.emplace(*this); + return *m_unwind_table; } -const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name, +SectionList *Module::GetUnifiedSectionList() { + if (!m_sections_up) + m_sections_up = llvm::make_unique<SectionList>(); + return m_sections_up.get(); +} + +const Symbol *Module::FindFirstSymbolWithNameAndType(ConstString name, SymbolType symbol_type) { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( @@ -1336,7 +1345,7 @@ } } -size_t Module::FindFunctionSymbols(const ConstString &name, +size_t Module::FindFunctionSymbols(ConstString name, uint32_t name_type_mask, SymbolContextList &sc_list) { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); @@ -1352,7 +1361,7 @@ return 0; } -size_t Module::FindSymbolsWithNameAndType(const ConstString &name, +size_t Module::FindSymbolsWithNameAndType(ConstString name, SymbolType symbol_type, SymbolContextList &sc_list) { // No need to protect this call using m_mutex all other method calls are @@ -1420,11 +1429,11 @@ void Module::SetSymbolFileFileSpec(const FileSpec &file) { if (!FileSystem::Instance().Exists(file)) return; - if (m_symfile_ap) { + if (m_symfile_up) { // Remove any sections in the unified section list that come from the // current symbol vendor. SectionList *section_list = GetSectionList(); - SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile(); + SymbolFile *symbol_file = m_symfile_up->GetSymbolFile(); if (section_list && symbol_file) { ObjectFile *obj_file = symbol_file->GetObjectFile(); // Make sure we have an object file and that the symbol vendor's objfile @@ -1443,6 +1452,10 @@ // one obj_file->ClearSymtab(); + // Clear the unwind table too, as that may also be affected by the + // symbol file information. + m_unwind_table.reset(); + // The symbol file might be a directory bundle ("/tmp/a.out.dSYM") // instead of a full path to the symbol file within the bundle // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to @@ -1472,10 +1485,10 @@ } // Keep all old symbol files around in case there are any lingering type // references in any SBValue objects that might have been handed out. - m_old_symfiles.push_back(std::move(m_symfile_ap)); + m_old_symfiles.push_back(std::move(m_symfile_up)); } m_symfile_spec = file; - m_symfile_ap.reset(); + m_symfile_up.reset(); m_did_load_symbol_vendor = false; } @@ -1532,8 +1545,7 @@ const uint32_t num_specs = file_specs.GetSize(); if (num_specs) { - ScriptInterpreter *script_interpreter = - debugger.GetCommandInterpreter().GetScriptInterpreter(); + ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); if (script_interpreter) { for (uint32_t i = 0; i < num_specs; ++i) { FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i)); @@ -1622,7 +1634,7 @@ return false; } - const ConstString &object_name = module_ref.GetObjectName(); + ConstString object_name = module_ref.GetObjectName(); if (object_name) { if (object_name != GetObjectName()) return false;
diff --git a/src/llvm-project/lldb/source/Core/ModuleChild.cpp b/src/llvm-project/lldb/source/Core/ModuleChild.cpp index 8649574..2fcb2ff 100644 --- a/src/llvm-project/lldb/source/Core/ModuleChild.cpp +++ b/src/llvm-project/lldb/source/Core/ModuleChild.cpp
@@ -1,9 +1,8 @@ //===-- ModuleChild.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,6 @@ ModuleChild::ModuleChild(const lldb::ModuleSP &module_sp) : m_module_wp(module_sp) {} -ModuleChild::ModuleChild(const ModuleChild &rhs) - : m_module_wp(rhs.m_module_wp) {} - ModuleChild::~ModuleChild() {} const ModuleChild &ModuleChild::operator=(const ModuleChild &rhs) {
diff --git a/src/llvm-project/lldb/source/Core/ModuleList.cpp b/src/llvm-project/lldb/source/Core/ModuleList.cpp index b8de86f..9d795f9 100644 --- a/src/llvm-project/lldb/source/Core/ModuleList.cpp +++ b/src/llvm-project/lldb/source/Core/ModuleList.cpp
@@ -1,9 +1,8 @@ //===-- ModuleList.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,10 +11,10 @@ #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/FileSystem.h" -#include "lldb/Host/Symbols.h" #include "lldb/Interpreter/OptionValueFileSpec.h" #include "lldb/Interpreter/OptionValueProperties.h" #include "lldb/Interpreter/Property.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Symbol/VariableList.h" @@ -88,7 +87,8 @@ } // namespace ModuleListProperties::ModuleListProperties() { - m_collection_sp.reset(new OptionValueProperties(ConstString("symbols"))); + m_collection_sp = + std::make_shared<OptionValueProperties>(ConstString("symbols")); m_collection_sp->Initialize(g_properties); llvm::SmallString<128> path; @@ -102,6 +102,11 @@ nullptr, idx, g_properties[idx].default_uint_value != 0); } +bool ModuleListProperties::SetEnableExternalLookup(bool new_value) { + return m_collection_sp->SetPropertyAtIndexAsBoolean( + nullptr, ePropertyEnableExternalLookup, new_value); +} + FileSpec ModuleListProperties::GetClangModulesCachePath() const { return m_collection_sp ->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false, @@ -114,7 +119,6 @@ nullptr, ePropertyClangModulesCachePath, path); } - ModuleList::ModuleList() : m_modules(), m_modules_mutex(), m_notifier(nullptr) {} @@ -130,25 +134,12 @@ const ModuleList &ModuleList::operator=(const ModuleList &rhs) { if (this != &rhs) { - // That's probably me nit-picking, but in theoretical situation: - // - // * that two threads A B and - // * two ModuleList's x y do opposite assignments ie.: - // - // in thread A: | in thread B: - // x = y; | y = x; - // - // This establishes correct(same) lock taking order and thus avoids - // priority inversion. - if (uintptr_t(this) > uintptr_t(&rhs)) { - std::lock_guard<std::recursive_mutex> lhs_guard(m_modules_mutex); - std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_modules_mutex); - m_modules = rhs.m_modules; - } else { - std::lock_guard<std::recursive_mutex> lhs_guard(m_modules_mutex); - std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_modules_mutex); - m_modules = rhs.m_modules; - } + std::lock(m_modules_mutex, rhs.m_modules_mutex); + std::lock_guard<std::recursive_mutex> lhs_guard(m_modules_mutex, + std::adopt_lock); + std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_modules_mutex, + std::adopt_lock); + m_modules = rhs.m_modules; } return *this; } @@ -160,11 +151,13 @@ std::lock_guard<std::recursive_mutex> guard(m_modules_mutex); m_modules.push_back(module_sp); if (use_notifier && m_notifier) - m_notifier->ModuleAdded(*this, module_sp); + m_notifier->NotifyModuleAdded(*this, module_sp); } } -void ModuleList::Append(const ModuleSP &module_sp) { AppendImpl(module_sp); } +void ModuleList::Append(const ModuleSP &module_sp, bool notify) { + AppendImpl(module_sp, notify); +} void ModuleList::ReplaceEquivalent(const ModuleSP &module_sp) { if (module_sp) { @@ -190,7 +183,7 @@ } } -bool ModuleList::AppendIfNeeded(const ModuleSP &module_sp) { +bool ModuleList::AppendIfNeeded(const ModuleSP &module_sp, bool notify) { if (module_sp) { std::lock_guard<std::recursive_mutex> guard(m_modules_mutex); collection::iterator pos, end = m_modules.end(); @@ -199,7 +192,7 @@ return false; // Already in the list } // Only push module_sp on the list if it wasn't already in there. - Append(module_sp); + Append(module_sp, notify); return true; } return false; @@ -227,7 +220,7 @@ if (pos->get() == module_sp.get()) { m_modules.erase(pos); if (use_notifier && m_notifier) - m_notifier->ModuleRemoved(*this, module_sp); + m_notifier->NotifyModuleRemoved(*this, module_sp); return true; } } @@ -241,12 +234,12 @@ ModuleSP module_sp(*pos); collection::iterator retval = m_modules.erase(pos); if (use_notifier && m_notifier) - m_notifier->ModuleRemoved(*this, module_sp); + m_notifier->NotifyModuleRemoved(*this, module_sp); return retval; } -bool ModuleList::Remove(const ModuleSP &module_sp) { - return RemoveImpl(module_sp); +bool ModuleList::Remove(const ModuleSP &module_sp, bool notify) { + return RemoveImpl(module_sp, notify); } bool ModuleList::ReplaceModule(const lldb::ModuleSP &old_module_sp, @@ -255,7 +248,7 @@ return false; AppendImpl(new_module_sp, false); if (m_notifier) - m_notifier->ModuleUpdated(*this, old_module_sp, new_module_sp); + m_notifier->NotifyModuleUpdated(*this, old_module_sp, new_module_sp); return true; } @@ -304,9 +297,11 @@ size_t num_removed = 0; collection::iterator pos, end = module_list.m_modules.end(); for (pos = module_list.m_modules.begin(); pos != end; ++pos) { - if (Remove(*pos)) + if (Remove(*pos, false /* notify */)) ++num_removed; } + if (m_notifier) + m_notifier->NotifyModulesRemoved(module_list); return num_removed; } @@ -317,7 +312,7 @@ void ModuleList::ClearImpl(bool use_notifier) { std::lock_guard<std::recursive_mutex> guard(m_modules_mutex); if (use_notifier && m_notifier) - m_notifier->WillClearList(*this); + m_notifier->NotifyWillClearList(*this); m_modules.clear(); } @@ -344,7 +339,7 @@ return module_sp; } -size_t ModuleList::FindFunctions(const ConstString &name, +size_t ModuleList::FindFunctions(ConstString name, FunctionNameType name_type_mask, bool include_symbols, bool include_inlines, bool append, @@ -380,7 +375,7 @@ return sc_list.GetSize() - old_size; } -size_t ModuleList::FindFunctionSymbols(const ConstString &name, +size_t ModuleList::FindFunctionSymbols(ConstString name, lldb::FunctionNameType name_type_mask, SymbolContextList &sc_list) { const size_t old_size = sc_list.GetSize(); @@ -439,7 +434,7 @@ return sc_list.GetSize(); } -size_t ModuleList::FindGlobalVariables(const ConstString &name, +size_t ModuleList::FindGlobalVariables(ConstString name, size_t max_matches, VariableList &variable_list) const { size_t initial_size = variable_list.GetSize(); @@ -463,7 +458,7 @@ return variable_list.GetSize() - initial_size; } -size_t ModuleList::FindSymbolsWithNameAndType(const ConstString &name, +size_t ModuleList::FindSymbolsWithNameAndType(ConstString name, SymbolType symbol_type, SymbolContextList &sc_list, bool append) const { @@ -542,7 +537,7 @@ } size_t -ModuleList::FindTypes(Module *search_first, const ConstString &name, +ModuleList::FindTypes(Module *search_first, ConstString name, bool name_is_fully_qualified, size_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeList &types) const { @@ -830,7 +825,7 @@ if (module_sp) return error; - module_sp.reset(new Module(module_spec)); + module_sp = std::make_shared<Module>(module_spec); // Make sure there are a module and an object file since we can specify a // valid file path with an architecture that might not be in that file. By // getting the object file we can guarantee that the architecture matches @@ -872,7 +867,7 @@ auto resolved_module_spec(module_spec); resolved_module_spec.GetFileSpec() = search_path_spec; - module_sp.reset(new Module(resolved_module_spec)); + module_sp = std::make_shared<Module>(resolved_module_spec); if (module_sp->GetObjectFile()) { // If we get in here we got the correct arch, now we just need to // verify the UUID if one was given @@ -971,7 +966,7 @@ } if (!module_sp) { - module_sp.reset(new Module(platform_module_spec)); + module_sp = std::make_shared<Module>(platform_module_spec); // Make sure there are a module and an object file since we can specify a // valid file path with an architecture that might not be in that file. // By getting the object file we can guarantee that the architecture
diff --git a/src/llvm-project/lldb/source/Core/Opcode.cpp b/src/llvm-project/lldb/source/Core/Opcode.cpp index ed8be78..6ca46de 100644 --- a/src/llvm-project/lldb/source/Core/Opcode.cpp +++ b/src/llvm-project/lldb/source/Core/Opcode.cpp
@@ -1,9 +1,8 @@ //===-- Opcode.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Core/PluginManager.cpp b/src/llvm-project/lldb/source/Core/PluginManager.cpp index fbb2580..24cadcd 100644 --- a/src/llvm-project/lldb/source/Core/PluginManager.cpp +++ b/src/llvm-project/lldb/source/Core/PluginManager.cpp
@@ -1,9 +1,8 @@ //===-- PluginManager.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -220,7 +219,7 @@ return g_instances; } -bool PluginManager::RegisterPlugin(const ConstString &name, +bool PluginManager::RegisterPlugin(ConstString name, const char *description, ABICreateInstance create_callback) { if (create_callback) { @@ -262,7 +261,7 @@ } ABICreateInstance -PluginManager::GetABICreateCallbackForPluginName(const ConstString &name) { +PluginManager::GetABICreateCallbackForPluginName(ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetABIInstancesMutex()); ABIInstances &instances = GetABIInstances(); @@ -296,7 +295,7 @@ return g_instances; } -void PluginManager::RegisterPlugin(const ConstString &name, +void PluginManager::RegisterPlugin(ConstString name, llvm::StringRef description, ArchitectureCreateInstance create_callback) { std::lock_guard<std::mutex> guard(GetArchitectureMutex()); @@ -349,7 +348,7 @@ return g_instances; } -bool PluginManager::RegisterPlugin(const ConstString &name, +bool PluginManager::RegisterPlugin(ConstString name, const char *description, DisassemblerCreateInstance create_callback) { if (create_callback) { @@ -394,7 +393,7 @@ DisassemblerCreateInstance PluginManager::GetDisassemblerCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetDisassemblerMutex()); DisassemblerInstances &instances = GetDisassemblerInstances(); @@ -434,7 +433,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, DynamicLoaderCreateInstance create_callback, DebuggerInitializeCallback debugger_init_callback) { if (create_callback) { @@ -479,7 +478,7 @@ DynamicLoaderCreateInstance PluginManager::GetDynamicLoaderCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetDynamicLoaderMutex()); DynamicLoaderInstances &instances = GetDynamicLoaderInstances(); @@ -519,7 +518,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, JITLoaderCreateInstance create_callback, DebuggerInitializeCallback debugger_init_callback) { if (create_callback) { @@ -562,7 +561,7 @@ } JITLoaderCreateInstance PluginManager::GetJITLoaderCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetJITLoaderMutex()); JITLoaderInstances &instances = GetJITLoaderInstances(); @@ -600,7 +599,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, EmulateInstructionCreateInstance create_callback) { if (create_callback) { EmulateInstructionInstance instance; @@ -643,7 +642,7 @@ EmulateInstructionCreateInstance PluginManager::GetEmulateInstructionCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetEmulateInstructionMutex()); EmulateInstructionInstances &instances = GetEmulateInstructionInstances(); @@ -683,7 +682,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, OperatingSystemCreateInstance create_callback, DebuggerInitializeCallback debugger_init_callback) { if (create_callback) { @@ -728,7 +727,7 @@ OperatingSystemCreateInstance PluginManager::GetOperatingSystemCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetOperatingSystemMutex()); OperatingSystemInstances &instances = GetOperatingSystemInstances(); @@ -764,7 +763,7 @@ return g_instances; } -bool PluginManager::RegisterPlugin(const ConstString &name, +bool PluginManager::RegisterPlugin(ConstString name, const char *description, LanguageCreateInstance create_callback) { if (create_callback) { @@ -806,7 +805,7 @@ } LanguageCreateInstance -PluginManager::GetLanguageCreateCallbackForPluginName(const ConstString &name) { +PluginManager::GetLanguageCreateCallbackForPluginName(ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetLanguageMutex()); LanguageInstances &instances = GetLanguageInstances(); @@ -829,6 +828,7 @@ std::string description; LanguageRuntimeCreateInstance create_callback; LanguageRuntimeGetCommandObject command_callback; + LanguageRuntimeGetExceptionPrecondition precondition_callback; }; typedef std::vector<LanguageRuntimeInstance> LanguageRuntimeInstances; @@ -844,9 +844,10 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, LanguageRuntimeCreateInstance create_callback, - LanguageRuntimeGetCommandObject command_callback) { + LanguageRuntimeGetCommandObject command_callback, + LanguageRuntimeGetExceptionPrecondition precondition_callback) { if (create_callback) { LanguageRuntimeInstance instance; assert((bool)name); @@ -855,6 +856,7 @@ instance.description = description; instance.create_callback = create_callback; instance.command_callback = command_callback; + instance.precondition_callback = precondition_callback; std::lock_guard<std::recursive_mutex> guard(GetLanguageRuntimeMutex()); GetLanguageRuntimeInstances().push_back(instance); } @@ -896,9 +898,18 @@ return nullptr; } +LanguageRuntimeGetExceptionPrecondition +PluginManager::GetLanguageRuntimeGetExceptionPreconditionAtIndex(uint32_t idx) { + std::lock_guard<std::recursive_mutex> guard(GetLanguageRuntimeMutex()); + LanguageRuntimeInstances &instances = GetLanguageRuntimeInstances(); + if (idx < instances.size()) + return instances[idx].precondition_callback; + return nullptr; +} + LanguageRuntimeCreateInstance PluginManager::GetLanguageRuntimeCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetLanguageRuntimeMutex()); LanguageRuntimeInstances &instances = GetLanguageRuntimeInstances(); @@ -935,7 +946,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, SystemRuntimeCreateInstance create_callback) { if (create_callback) { SystemRuntimeInstance instance; @@ -978,7 +989,7 @@ SystemRuntimeCreateInstance PluginManager::GetSystemRuntimeCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetSystemRuntimeMutex()); SystemRuntimeInstances &instances = GetSystemRuntimeInstances(); @@ -1021,7 +1032,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, ObjectFileCreateInstance create_callback, ObjectFileCreateMemoryInstance create_memory_callback, ObjectFileGetModuleSpecifications get_module_specifications, @@ -1088,7 +1099,7 @@ ObjectFileCreateInstance PluginManager::GetObjectFileCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetObjectFileMutex()); ObjectFileInstances &instances = GetObjectFileInstances(); @@ -1104,7 +1115,7 @@ ObjectFileCreateMemoryInstance PluginManager::GetObjectFileCreateMemoryCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetObjectFileMutex()); ObjectFileInstances &instances = GetObjectFileInstances(); @@ -1160,7 +1171,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, ObjectContainerCreateInstance create_callback, ObjectFileGetModuleSpecifications get_module_specifications) { if (create_callback) { @@ -1205,7 +1216,7 @@ ObjectContainerCreateInstance PluginManager::GetObjectContainerCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetObjectContainerMutex()); ObjectContainerInstances &instances = GetObjectContainerInstances(); @@ -1255,7 +1266,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, PlatformCreateInstance create_callback, DebuggerInitializeCallback debugger_init_callback) { if (create_callback) { @@ -1316,7 +1327,7 @@ } PlatformCreateInstance -PluginManager::GetPlatformCreateCallbackForPluginName(const ConstString &name) { +PluginManager::GetPlatformCreateCallbackForPluginName(ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetPlatformInstancesMutex()); PlatformInstances &instances = GetPlatformInstances(); @@ -1374,7 +1385,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, ProcessCreateInstance create_callback, DebuggerInitializeCallback debugger_init_callback) { if (create_callback) { @@ -1433,7 +1444,7 @@ } ProcessCreateInstance -PluginManager::GetProcessCreateCallbackForPluginName(const ConstString &name) { +PluginManager::GetProcessCreateCallbackForPluginName(ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetProcessMutex()); ProcessInstances &instances = GetProcessInstances(); @@ -1473,7 +1484,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, lldb::ScriptLanguage script_language, ScriptInterpreterCreateInstance create_callback) { if (!create_callback) @@ -1517,8 +1528,9 @@ return nullptr; } -lldb::ScriptInterpreterSP PluginManager::GetScriptInterpreterForLanguage( - lldb::ScriptLanguage script_lang, CommandInterpreter &interpreter) { +lldb::ScriptInterpreterSP +PluginManager::GetScriptInterpreterForLanguage(lldb::ScriptLanguage script_lang, + Debugger &debugger) { std::lock_guard<std::recursive_mutex> guard(GetScriptInterpreterMutex()); ScriptInterpreterInstances &instances = GetScriptInterpreterInstances(); @@ -1529,20 +1541,18 @@ none_instance = pos->create_callback; if (script_lang == pos->language) - return pos->create_callback(interpreter); + return pos->create_callback(debugger); } // If we didn't find one, return the ScriptInterpreter for the null language. assert(none_instance != nullptr); - return none_instance(interpreter); + return none_instance(debugger); } #pragma mark - #pragma mark StructuredDataPlugin -// ----------------------------------------------------------------------------- // StructuredDataPlugin -// ----------------------------------------------------------------------------- struct StructuredDataPluginInstance { StructuredDataPluginInstance() @@ -1569,7 +1579,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, StructuredDataPluginCreateInstance create_callback, DebuggerInitializeCallback debugger_init_callback, StructuredDataFilterLaunchInfo filter_callback) { @@ -1617,7 +1627,7 @@ StructuredDataPluginCreateInstance PluginManager::GetStructuredDataPluginCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetStructuredDataPluginMutex()); StructuredDataPluginInstances &instances = @@ -1672,7 +1682,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, SymbolFileCreateInstance create_callback, DebuggerInitializeCallback debugger_init_callback) { if (create_callback) { @@ -1716,7 +1726,7 @@ SymbolFileCreateInstance PluginManager::GetSymbolFileCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetSymbolFileMutex()); SymbolFileInstances &instances = GetSymbolFileInstances(); @@ -1752,7 +1762,7 @@ return g_instances; } -bool PluginManager::RegisterPlugin(const ConstString &name, +bool PluginManager::RegisterPlugin(ConstString name, const char *description, SymbolVendorCreateInstance create_callback) { if (create_callback) { @@ -1796,7 +1806,7 @@ SymbolVendorCreateInstance PluginManager::GetSymbolVendorCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetSymbolVendorMutex()); SymbolVendorInstances &instances = GetSymbolVendorInstances(); @@ -1833,7 +1843,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, UnwindAssemblyCreateInstance create_callback) { if (create_callback) { UnwindAssemblyInstance instance; @@ -1876,7 +1886,7 @@ UnwindAssemblyCreateInstance PluginManager::GetUnwindAssemblyCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetUnwindAssemblyMutex()); UnwindAssemblyInstances &instances = GetUnwindAssemblyInstances(); @@ -1913,7 +1923,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, MemoryHistoryCreateInstance create_callback) { if (create_callback) { MemoryHistoryInstance instance; @@ -1956,7 +1966,7 @@ MemoryHistoryCreateInstance PluginManager::GetMemoryHistoryCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetMemoryHistoryMutex()); MemoryHistoryInstances &instances = GetMemoryHistoryInstances(); @@ -1996,7 +2006,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, InstrumentationRuntimeCreateInstance create_callback, InstrumentationRuntimeGetType get_type_callback) { if (create_callback) { @@ -2055,7 +2065,7 @@ InstrumentationRuntimeCreateInstance PluginManager::GetInstrumentationRuntimeCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard( GetInstrumentationRuntimeMutex()); @@ -2094,7 +2104,7 @@ return g_instances; } -bool PluginManager::RegisterPlugin(const ConstString &name, +bool PluginManager::RegisterPlugin(ConstString name, const char *description, TypeSystemCreateInstance create_callback, TypeSystemEnumerateSupportedLanguages @@ -2140,7 +2150,7 @@ TypeSystemCreateInstance PluginManager::GetTypeSystemCreateCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetTypeSystemMutex()); TypeSystemInstances &instances = GetTypeSystemInstances(); @@ -2166,7 +2176,7 @@ TypeSystemEnumerateSupportedLanguages PluginManager::GetTypeSystemEnumerateSupportedLanguagesCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetTypeSystemMutex()); TypeSystemInstances &instances = GetTypeSystemInstances(); @@ -2204,7 +2214,7 @@ } bool PluginManager::RegisterPlugin( - const ConstString &name, const char *description, + ConstString name, const char *description, REPLCreateInstance create_callback, REPLEnumerateSupportedLanguages enumerate_languages_callback) { if (create_callback) { @@ -2246,7 +2256,7 @@ } REPLCreateInstance -PluginManager::GetREPLCreateCallbackForPluginName(const ConstString &name) { +PluginManager::GetREPLCreateCallbackForPluginName(ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetREPLMutex()); REPLInstances &instances = GetREPLInstances(); @@ -2271,7 +2281,7 @@ REPLEnumerateSupportedLanguages PluginManager::GetREPLSystemEnumerateSupportedLanguagesCallbackForPluginName( - const ConstString &name) { + ConstString name) { if (name) { std::lock_guard<std::recursive_mutex> guard(GetREPLMutex()); REPLInstances &instances = GetREPLInstances(); @@ -2368,8 +2378,8 @@ // This will put a plugin's settings under e.g. // "plugin.<plugin_type_name>.<plugin_type_desc>.SETTINGNAME". static lldb::OptionValuePropertiesSP GetDebuggerPropertyForPlugins( - Debugger &debugger, const ConstString &plugin_type_name, - const ConstString &plugin_type_desc, bool can_create) { + Debugger &debugger, ConstString plugin_type_name, + ConstString plugin_type_desc, bool can_create) { lldb::OptionValuePropertiesSP parent_properties_sp( debugger.GetValueProperties()); if (parent_properties_sp) { @@ -2404,8 +2414,8 @@ // "<plugin_type_name>.plugin.<plugin_type_desc>.SETTINGNAME" and Platform // generic settings would be under "platform.SETTINGNAME". static lldb::OptionValuePropertiesSP GetDebuggerPropertyForPluginsOldStyle( - Debugger &debugger, const ConstString &plugin_type_name, - const ConstString &plugin_type_desc, bool can_create) { + Debugger &debugger, ConstString plugin_type_name, + ConstString plugin_type_desc, bool can_create) { static ConstString g_property_name("plugin"); lldb::OptionValuePropertiesSP parent_properties_sp( debugger.GetValueProperties()); @@ -2438,12 +2448,12 @@ namespace { typedef lldb::OptionValuePropertiesSP -GetDebuggerPropertyForPluginsPtr(Debugger &, const ConstString &, - const ConstString &, bool can_create); +GetDebuggerPropertyForPluginsPtr(Debugger &, ConstString , + ConstString , bool can_create); lldb::OptionValuePropertiesSP -GetSettingForPlugin(Debugger &debugger, const ConstString &setting_name, - const ConstString &plugin_type_name, +GetSettingForPlugin(Debugger &debugger, ConstString setting_name, + ConstString plugin_type_name, GetDebuggerPropertyForPluginsPtr get_debugger_property = GetDebuggerPropertyForPlugins) { lldb::OptionValuePropertiesSP properties_sp; @@ -2458,10 +2468,10 @@ } bool CreateSettingForPlugin( - Debugger &debugger, const ConstString &plugin_type_name, - const ConstString &plugin_type_desc, + Debugger &debugger, ConstString plugin_type_name, + ConstString plugin_type_desc, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property, + ConstString description, bool is_global_property, GetDebuggerPropertyForPluginsPtr get_debugger_property = GetDebuggerPropertyForPlugins) { if (properties_sp) { @@ -2488,14 +2498,14 @@ } // anonymous namespace lldb::OptionValuePropertiesSP PluginManager::GetSettingForDynamicLoaderPlugin( - Debugger &debugger, const ConstString &setting_name) { + Debugger &debugger, ConstString setting_name) { return GetSettingForPlugin(debugger, setting_name, ConstString(kDynamicLoaderPluginName)); } bool PluginManager::CreateSettingForDynamicLoaderPlugin( Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property) { + ConstString description, bool is_global_property) { return CreateSettingForPlugin( debugger, ConstString(kDynamicLoaderPluginName), ConstString("Settings for dynamic loader plug-ins"), properties_sp, @@ -2504,7 +2514,7 @@ lldb::OptionValuePropertiesSP PluginManager::GetSettingForPlatformPlugin(Debugger &debugger, - const ConstString &setting_name) { + ConstString setting_name) { return GetSettingForPlugin(debugger, setting_name, ConstString(kPlatformPluginName), GetDebuggerPropertyForPluginsOldStyle); @@ -2512,7 +2522,7 @@ bool PluginManager::CreateSettingForPlatformPlugin( Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property) { + ConstString description, bool is_global_property) { return CreateSettingForPlugin(debugger, ConstString(kPlatformPluginName), ConstString("Settings for platform plug-ins"), properties_sp, description, is_global_property, @@ -2521,14 +2531,14 @@ lldb::OptionValuePropertiesSP PluginManager::GetSettingForProcessPlugin(Debugger &debugger, - const ConstString &setting_name) { + ConstString setting_name) { return GetSettingForPlugin(debugger, setting_name, ConstString(kProcessPluginName)); } bool PluginManager::CreateSettingForProcessPlugin( Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property) { + ConstString description, bool is_global_property) { return CreateSettingForPlugin(debugger, ConstString(kProcessPluginName), ConstString("Settings for process plug-ins"), properties_sp, description, is_global_property); @@ -2536,14 +2546,14 @@ lldb::OptionValuePropertiesSP PluginManager::GetSettingForSymbolFilePlugin(Debugger &debugger, - const ConstString &setting_name) { + ConstString setting_name) { return GetSettingForPlugin(debugger, setting_name, ConstString(kSymbolFilePluginName)); } bool PluginManager::CreateSettingForSymbolFilePlugin( Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property) { + ConstString description, bool is_global_property) { return CreateSettingForPlugin( debugger, ConstString(kSymbolFilePluginName), ConstString("Settings for symbol file plug-ins"), properties_sp, @@ -2552,14 +2562,14 @@ lldb::OptionValuePropertiesSP PluginManager::GetSettingForJITLoaderPlugin(Debugger &debugger, - const ConstString &setting_name) { + ConstString setting_name) { return GetSettingForPlugin(debugger, setting_name, ConstString(kJITLoaderPluginName)); } bool PluginManager::CreateSettingForJITLoaderPlugin( Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property) { + ConstString description, bool is_global_property) { return CreateSettingForPlugin(debugger, ConstString(kJITLoaderPluginName), ConstString("Settings for JIT loader plug-ins"), properties_sp, description, is_global_property); @@ -2568,7 +2578,7 @@ static const char *kOperatingSystemPluginName("os"); lldb::OptionValuePropertiesSP PluginManager::GetSettingForOperatingSystemPlugin( - Debugger &debugger, const ConstString &setting_name) { + Debugger &debugger, ConstString setting_name) { lldb::OptionValuePropertiesSP properties_sp; lldb::OptionValuePropertiesSP plugin_type_properties_sp( GetDebuggerPropertyForPlugins( @@ -2583,7 +2593,7 @@ bool PluginManager::CreateSettingForOperatingSystemPlugin( Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property) { + ConstString description, bool is_global_property) { if (properties_sp) { lldb::OptionValuePropertiesSP plugin_type_properties_sp( GetDebuggerPropertyForPlugins( @@ -2600,14 +2610,14 @@ } lldb::OptionValuePropertiesSP PluginManager::GetSettingForStructuredDataPlugin( - Debugger &debugger, const ConstString &setting_name) { + Debugger &debugger, ConstString setting_name) { return GetSettingForPlugin(debugger, setting_name, ConstString(kStructuredDataPluginName)); } bool PluginManager::CreateSettingForStructuredDataPlugin( Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, bool is_global_property) { + ConstString description, bool is_global_property) { return CreateSettingForPlugin( debugger, ConstString(kStructuredDataPluginName), ConstString("Settings for structured data plug-ins"), properties_sp,
diff --git a/src/llvm-project/lldb/source/Core/RichManglingContext.cpp b/src/llvm-project/lldb/source/Core/RichManglingContext.cpp index f5fbe38..3d1941e 100644 --- a/src/llvm-project/lldb/source/Core/RichManglingContext.cpp +++ b/src/llvm-project/lldb/source/Core/RichManglingContext.cpp
@@ -1,9 +1,8 @@ //===-- RichManglingContext.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // RichManglingContext -//---------------------------------------------------------------------- void RichManglingContext::ResetProvider(InfoProvider new_provider) { // If we want to support parsers for other languages some day, we need a // switch here to delete the correct parser type. @@ -35,7 +32,7 @@ m_provider = new_provider; } -bool RichManglingContext::FromItaniumName(const ConstString &mangled) { +bool RichManglingContext::FromItaniumName(ConstString mangled) { bool err = m_ipd.partialDemangle(mangled.GetCString()); if (!err) { ResetProvider(ItaniumPartialDemangler); @@ -54,7 +51,7 @@ return !err; // true == success } -bool RichManglingContext::FromCxxMethodName(const ConstString &demangled) { +bool RichManglingContext::FromCxxMethodName(ConstString demangled) { ResetProvider(PluginCxxLanguage); m_cxx_method_parser = new CPlusPlusLanguage::MethodName(demangled); return true;
diff --git a/src/llvm-project/lldb/source/Core/SearchFilter.cpp b/src/llvm-project/lldb/source/Core/SearchFilter.cpp index 5d26c71..531fa07 100644 --- a/src/llvm-project/lldb/source/Core/SearchFilter.cpp +++ b/src/llvm-project/lldb/source/Core/SearchFilter.cpp
@@ -1,9 +1,8 @@ //===-- SearchFilter.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -73,10 +72,6 @@ SearchFilter::SearchFilter(const TargetSP &target_sp, unsigned char filterType) : m_target_sp(target_sp), SubclassID(filterType) {} -SearchFilter::SearchFilter(const SearchFilter &rhs) = default; - -SearchFilter &SearchFilter::operator=(const SearchFilter &rhs) = default; - SearchFilter::~SearchFilter() = default; SearchFilterSP SearchFilter::CreateFromStructuredData( @@ -172,9 +167,7 @@ return ret_sp; } -//---------------------------------------------------------------------- // Helper functions for serialization. -//---------------------------------------------------------------------- StructuredData::DictionarySP SearchFilter::WrapOptionsDict(StructuredData::DictionarySP options_dict_sp) { @@ -205,10 +198,8 @@ options_dict_sp->AddItem(GetKey(name), module_array_sp); } -//---------------------------------------------------------------------- // UTILITY Functions to help iterate down through the elements of the // SymbolContext. -//---------------------------------------------------------------------- void SearchFilter::Search(Searcher &searcher) { SymbolContext empty_sc; @@ -364,11 +355,9 @@ return Searcher::eCallbackReturnContinue; } -//---------------------------------------------------------------------- // SearchFilterForUnconstrainedSearches: // Selects a shared library matching a given file spec, consulting the targets // "black list". -//---------------------------------------------------------------------- SearchFilterSP SearchFilterForUnconstrainedSearches::CreateFromStructuredData( Target &target, const StructuredData::Dictionary &data_dict, Status &error) { @@ -404,25 +393,13 @@ return std::make_shared<SearchFilterForUnconstrainedSearches>(*this); } -//---------------------------------------------------------------------- // SearchFilterByModule: // Selects a shared library matching a given file spec -//---------------------------------------------------------------------- SearchFilterByModule::SearchFilterByModule(const lldb::TargetSP &target_sp, const FileSpec &module) : SearchFilter(target_sp, FilterTy::ByModule), m_module_spec(module) {} -SearchFilterByModule::SearchFilterByModule(const SearchFilterByModule &rhs) = - default; - -SearchFilterByModule &SearchFilterByModule:: -operator=(const SearchFilterByModule &rhs) { - m_target_sp = rhs.m_target_sp; - m_module_spec = rhs.m_module_spec; - return *this; -} - SearchFilterByModule::~SearchFilterByModule() = default; bool SearchFilterByModule::ModulePasses(const ModuleSP &module_sp) { @@ -534,10 +511,8 @@ return WrapOptionsDict(options_dict_sp); } -//---------------------------------------------------------------------- // SearchFilterByModuleList: // Selects a shared library matching a given file spec -//---------------------------------------------------------------------- SearchFilterByModuleList::SearchFilterByModuleList( const lldb::TargetSP &target_sp, const FileSpecList &module_list) @@ -549,9 +524,6 @@ enum FilterTy filter_ty) : SearchFilter(target_sp, filter_ty), m_module_spec_list(module_list) {} -SearchFilterByModuleList::SearchFilterByModuleList( - const SearchFilterByModuleList &rhs) = default; - SearchFilterByModuleList &SearchFilterByModuleList:: operator=(const SearchFilterByModuleList &rhs) { m_target_sp = rhs.m_target_sp; @@ -688,10 +660,8 @@ return WrapOptionsDict(options_dict_sp); } -//---------------------------------------------------------------------- // SearchFilterByModuleListAndCU: // Selects a shared library matching a given file spec -//---------------------------------------------------------------------- SearchFilterByModuleListAndCU::SearchFilterByModuleListAndCU( const lldb::TargetSP &target_sp, const FileSpecList &module_list,
diff --git a/src/llvm-project/lldb/source/Core/Section.cpp b/src/llvm-project/lldb/source/Core/Section.cpp index 87f75e1..f30ddd2 100644 --- a/src/llvm-project/lldb/source/Core/Section.cpp +++ b/src/llvm-project/lldb/source/Core/Section.cpp
@@ -1,9 +1,8 @@ //===-- Section.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -105,6 +104,8 @@ return "dwarf-str-offsets-dwo"; case eSectionTypeDWARFDebugTypes: return "dwarf-types"; + case eSectionTypeDWARFDebugTypesDwo: + return "dwarf-types-dwo"; case eSectionTypeDWARFDebugNames: return "dwarf-names"; case eSectionTypeELFSymbolTable: @@ -144,7 +145,7 @@ } Section::Section(const ModuleSP &module_sp, ObjectFile *obj_file, - user_id_t sect_id, const ConstString &name, + user_id_t sect_id, ConstString name, SectionType sect_type, addr_t file_addr, addr_t byte_size, lldb::offset_t file_offset, lldb::offset_t file_size, uint32_t log2align, uint32_t flags, @@ -166,7 +167,7 @@ Section::Section(const lldb::SectionSP &parent_section_sp, const ModuleSP &module_sp, ObjectFile *obj_file, - user_id_t sect_id, const ConstString &name, + user_id_t sect_id, ConstString name, SectionType sect_type, addr_t file_addr, addr_t byte_size, lldb::offset_t file_offset, lldb::offset_t file_size, uint32_t log2align, uint32_t flags, @@ -343,7 +344,7 @@ s->PutChar('.'); } else { // The top most section prints the module basename - const char *name = NULL; + const char *name = nullptr; ModuleSP module_sp(GetModule()); if (m_obj_file) { @@ -382,9 +383,7 @@ return false; } -//------------------------------------------------------------------ /// Get the permissions as OR'ed bits from lldb::Permissions -//------------------------------------------------------------------ uint32_t Section::GetPermissions() const { uint32_t permissions = 0; if (m_readable) @@ -396,9 +395,7 @@ return permissions; } -//------------------------------------------------------------------ /// Set the permissions using bits OR'ed from lldb::Permissions -//------------------------------------------------------------------ void Section::SetPermissions(uint32_t permissions) { m_readable = (permissions & ePermissionsReadable) != 0; m_writable = (permissions & ePermissionsWritable) != 0; @@ -507,14 +504,14 @@ } SectionSP -SectionList::FindSectionByName(const ConstString §ion_dstr) const { +SectionList::FindSectionByName(ConstString section_dstr) const { SectionSP sect_sp; // Check if we have a valid section string if (section_dstr && !m_sections.empty()) { const_iterator sect_iter; const_iterator end = m_sections.end(); for (sect_iter = m_sections.begin(); - sect_iter != end && sect_sp.get() == NULL; ++sect_iter) { + sect_iter != end && sect_sp.get() == nullptr; ++sect_iter) { Section *child_section = sect_iter->get(); if (child_section) { if (child_section->GetName() == section_dstr) { @@ -535,7 +532,7 @@ const_iterator sect_iter; const_iterator end = m_sections.end(); for (sect_iter = m_sections.begin(); - sect_iter != end && sect_sp.get() == NULL; ++sect_iter) { + sect_iter != end && sect_sp.get() == nullptr; ++sect_iter) { if ((*sect_iter)->GetID() == sect_id) { sect_sp = *sect_iter; break; @@ -572,7 +569,7 @@ const_iterator sect_iter; const_iterator end = m_sections.end(); for (sect_iter = m_sections.begin(); - sect_iter != end && sect_sp.get() == NULL; ++sect_iter) { + sect_iter != end && sect_sp.get() == nullptr; ++sect_iter) { Section *sect = sect_iter->get(); if (sect->ContainsFileAddress(vm_addr)) { // The file address is in this section. We need to make sure one of our @@ -582,7 +579,7 @@ sect_sp = sect->GetChildren().FindSectionContainingFileAddress( vm_addr, depth - 1); - if (sect_sp.get() == NULL && !sect->IsFake()) + if (sect_sp.get() == nullptr && !sect->IsFake()) sect_sp = *sect_iter; } } @@ -590,7 +587,7 @@ } bool SectionList::ContainsSection(user_id_t sect_id) const { - return FindSectionByID(sect_id).get() != NULL; + return FindSectionByID(sect_id).get() != nullptr; } void SectionList::Dump(Stream *s, Target *target, bool show_header, @@ -613,7 +610,7 @@ const_iterator sect_iter; const_iterator end = m_sections.end(); for (sect_iter = m_sections.begin(); sect_iter != end; ++sect_iter) { - (*sect_iter)->Dump(s, target_has_loaded_sections ? target : NULL, depth); + (*sect_iter)->Dump(s, target_has_loaded_sections ? target : nullptr, depth); } if (show_header && !m_sections.empty())
diff --git a/src/llvm-project/lldb/source/Core/SourceManager.cpp b/src/llvm-project/lldb/source/Core/SourceManager.cpp index fe603c5..87065ab 100644 --- a/src/llvm-project/lldb/source/Core/SourceManager.cpp +++ b/src/llvm-project/lldb/source/Core/SourceManager.cpp
@@ -1,9 +1,8 @@ //===-- SourceManager.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -50,9 +49,7 @@ static inline bool is_newline_char(char ch) { return ch == '\n' || ch == '\r'; } -//---------------------------------------------------------------------- // SourceManager constructor -//---------------------------------------------------------------------- SourceManager::SourceManager(const TargetSP &target_sp) : m_last_file_sp(), m_last_line(0), m_last_count(0), m_default_set(false), m_target_wp(target_sp), @@ -62,9 +59,7 @@ : m_last_file_sp(), m_last_line(0), m_last_count(0), m_default_set(false), m_target_wp(), m_debugger_wp(debugger_sp) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SourceManager::~SourceManager() {} SourceManager::FileSP SourceManager::GetFile(const FileSpec &file_spec) { @@ -331,7 +326,7 @@ bool inlines_okay = true; bool append = false; size_t num_matches = executable_ptr->FindFunctions( - main_name, NULL, lldb::eFunctionNameTypeBase, inlines_okay, + main_name, nullptr, lldb::eFunctionNameTypeBase, inlines_okay, symbols_okay, append, sc_list); for (size_t idx = 0; idx < num_matches; idx++) { SymbolContext sc; @@ -404,7 +399,7 @@ if (num_matches != 0) { if (num_matches > 1) { SymbolContext sc; - FileSpec *test_cu_spec = NULL; + FileSpec *test_cu_spec = nullptr; for (unsigned i = 0; i < num_matches; i++) { sc_list.GetContextAtIndex(i, sc); @@ -466,12 +461,12 @@ const char *SourceManager::File::PeekLineData(uint32_t line) { if (!LineIsValid(line)) - return NULL; + return nullptr; size_t line_offset = GetLineOffset(line); if (line_offset < m_data_sp->GetByteSize()) return (const char *)m_data_sp->GetBytes() + line_offset; - return NULL; + return nullptr; } uint32_t SourceManager::File::GetLineLength(uint32_t line, @@ -626,7 +621,7 @@ return true; if (m_offsets.empty()) { - if (m_data_sp.get() == NULL) + if (m_data_sp.get() == nullptr) return false; const char *start = (char *)m_data_sp->GetBytes();
diff --git a/src/llvm-project/lldb/source/Core/StreamAsynchronousIO.cpp b/src/llvm-project/lldb/source/Core/StreamAsynchronousIO.cpp index b8938bd..d283749 100644 --- a/src/llvm-project/lldb/source/Core/StreamAsynchronousIO.cpp +++ b/src/llvm-project/lldb/source/Core/StreamAsynchronousIO.cpp
@@ -1,9 +1,8 @@ //===-- StreamAsynchronousIO.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Core/StreamFile.cpp b/src/llvm-project/lldb/source/Core/StreamFile.cpp index d246345..ce6e1ea 100644 --- a/src/llvm-project/lldb/source/Core/StreamFile.cpp +++ b/src/llvm-project/lldb/source/Core/StreamFile.cpp
@@ -1,9 +1,8 @@ //===-- StreamFile.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // StreamFile constructor -//---------------------------------------------------------------------- StreamFile::StreamFile() : Stream(), m_file() {} StreamFile::StreamFile(uint32_t flags, uint32_t addr_size, ByteOrder byte_order)
diff --git a/src/llvm-project/lldb/source/Core/UserSettingsController.cpp b/src/llvm-project/lldb/source/Core/UserSettingsController.cpp index 4406057..3a65676 100644 --- a/src/llvm-project/lldb/source/Core/UserSettingsController.cpp +++ b/src/llvm-project/lldb/source/Core/UserSettingsController.cpp
@@ -1,9 +1,8 @@ //====-- UserSettingsController.cpp ------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -95,7 +94,7 @@ lldb::OptionValuePropertiesSP Properties::GetSubProperty(const ExecutionContext *exe_ctx, - const ConstString &name) { + ConstString name) { OptionValuePropertiesSP properties_sp(GetValueProperties()); if (properties_sp) return properties_sp->GetSubProperty(exe_ctx, name);
diff --git a/src/llvm-project/lldb/source/Core/Value.cpp b/src/llvm-project/lldb/source/Core/Value.cpp index 98a39ea..fdb4adb 100644 --- a/src/llvm-project/lldb/source/Core/Value.cpp +++ b/src/llvm-project/lldb/source/Core/Value.cpp
@@ -1,9 +1,8 @@ //===-- Value.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -40,17 +39,17 @@ using namespace lldb_private; Value::Value() - : m_value(), m_vector(), m_compiler_type(), m_context(NULL), + : m_value(), m_vector(), m_compiler_type(), m_context(nullptr), m_value_type(eValueTypeScalar), m_context_type(eContextTypeInvalid), m_data_buffer() {} Value::Value(const Scalar &scalar) - : m_value(scalar), m_vector(), m_compiler_type(), m_context(NULL), + : m_value(scalar), m_vector(), m_compiler_type(), m_context(nullptr), m_value_type(eValueTypeScalar), m_context_type(eContextTypeInvalid), m_data_buffer() {} Value::Value(const void *bytes, int len) - : m_value(), m_vector(), m_compiler_type(), m_context(NULL), + : m_value(), m_vector(), m_compiler_type(), m_context(nullptr), m_value_type(eValueTypeHostAddress), m_context_type(eContextTypeInvalid), m_data_buffer() { SetBytes(bytes, len); @@ -132,13 +131,13 @@ RegisterInfo *Value::GetRegisterInfo() const { if (m_context_type == eContextTypeRegisterInfo) return static_cast<RegisterInfo *>(m_context); - return NULL; + return nullptr; } Type *Value::GetType() { if (m_context_type == eContextTypeLLDBType) return static_cast<Type *>(m_context); - return NULL; + return nullptr; } size_t Value::AppendDataToHostBuffer(const Value &rhs) { @@ -210,35 +209,31 @@ } uint64_t Value::GetValueByteSize(Status *error_ptr, ExecutionContext *exe_ctx) { - uint64_t byte_size = 0; - switch (m_context_type) { case eContextTypeRegisterInfo: // RegisterInfo * - if (GetRegisterInfo()) - byte_size = GetRegisterInfo()->byte_size; + if (GetRegisterInfo()) { + if (error_ptr) + error_ptr->Clear(); + return GetRegisterInfo()->byte_size; + } break; case eContextTypeInvalid: case eContextTypeLLDBType: // Type * case eContextTypeVariable: // Variable * { - const CompilerType &ast_type = GetCompilerType(); - if (ast_type.IsValid()) - if (llvm::Optional<uint64_t> size = ast_type.GetByteSize( - exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr)) - byte_size = *size; - } break; - } - - if (error_ptr) { - if (byte_size == 0) { - if (error_ptr->Success()) - error_ptr->SetErrorString("Unable to determine byte size."); - } else { - error_ptr->Clear(); + auto *scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr; + if (llvm::Optional<uint64_t> size = GetCompilerType().GetByteSize(scope)) { + if (error_ptr) + error_ptr->Clear(); + return *size; } + break; } - return byte_size; + } + if (error_ptr && error_ptr->Success()) + error_ptr->SetErrorString("Unable to determine byte size."); + return 0; } const CompilerType &Value::GetCompilerType() { @@ -358,11 +353,11 @@ break; } case eValueTypeLoadAddress: - if (exe_ctx == NULL) { + if (exe_ctx == nullptr) { error.SetErrorString("can't read load address (no execution context)"); } else { Process *process = exe_ctx->GetProcessPtr(); - if (process == NULL || !process->IsAlive()) { + if (process == nullptr || !process->IsAlive()) { Target *target = exe_ctx->GetTargetPtr(); if (target) { // Allow expressions to run and evaluate things when the target has @@ -395,16 +390,16 @@ break; case eValueTypeFileAddress: - if (exe_ctx == NULL) { + if (exe_ctx == nullptr) { error.SetErrorString("can't read file address (no execution context)"); - } else if (exe_ctx->GetTargetPtr() == NULL) { + } else if (exe_ctx->GetTargetPtr() == nullptr) { error.SetErrorString("can't read file address (invalid target)"); } else { address = m_value.ULongLong(LLDB_INVALID_ADDRESS); if (address == LLDB_INVALID_ADDRESS) { error.SetErrorString("invalid file address"); } else { - if (module == NULL) { + if (module == nullptr) { // The only thing we can currently lock down to a module so that we // can resolve a file address, is a variable. Variable *variable = GetVariable(); @@ -519,6 +514,10 @@ if (error.Fail()) return error; + // No memory to read for zero-sized types. + if (byte_size == 0) + return error; + // Make sure we have enough room within "data", and if we don't make // something large enough that does if (!data.ValidOffsetForDataOfSize(data_offset, byte_size)) { @@ -528,7 +527,7 @@ } uint8_t *dst = const_cast<uint8_t *>(data.PeekData(data_offset, byte_size)); - if (dst != NULL) { + if (dst != nullptr) { if (address_type == eAddressTypeHost) { // The address is an address in this process, so just copy it. if (address == 0) { @@ -598,7 +597,7 @@ { DataExtractor data; lldb::addr_t addr = m_value.ULongLong(LLDB_INVALID_ADDRESS); - Status error(GetValueAsData(exe_ctx, data, 0, NULL)); + Status error(GetValueAsData(exe_ctx, data, 0, nullptr)); if (error.Success()) { Scalar scalar; if (compiler_type.GetValueAsScalar(data, 0, data.GetByteSize(), @@ -626,7 +625,7 @@ Variable *Value::GetVariable() { if (m_context_type == eContextTypeVariable) return static_cast<Variable *>(m_context); - return NULL; + return nullptr; } void Value::Clear() { @@ -634,7 +633,7 @@ m_vector.Clear(); m_compiler_type.Clear(); m_value_type = eValueTypeScalar; - m_context = NULL; + m_context = nullptr; m_context_type = eContextTypeInvalid; m_data_buffer.Clear(); } @@ -703,7 +702,7 @@ if (idx < GetSize()) { return &(m_values[idx]); } else - return NULL; + return nullptr; } void ValueList::Clear() { m_values.clear(); }
diff --git a/src/llvm-project/lldb/source/Core/ValueObject.cpp b/src/llvm-project/lldb/source/Core/ValueObject.cpp index 95e944b..297365b 100644 --- a/src/llvm-project/lldb/source/Core/ValueObject.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObject.cpp
@@ -1,9 +1,8 @@ //===-- ValueObject.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,10 +31,10 @@ #include "lldb/Symbol/Declaration.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Symbol/Type.h" +#include "lldb/Symbol/Variable.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Language.h" #include "lldb/Target/LanguageRuntime.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" @@ -78,17 +77,16 @@ static user_id_t g_value_obj_uid = 0; -//---------------------------------------------------------------------- // ValueObject constructor -//---------------------------------------------------------------------- ValueObject::ValueObject(ValueObject &parent) : UserID(++g_value_obj_uid), // Unique identifier for every value object - m_parent(&parent), m_root(NULL), m_update_point(parent.GetUpdatePoint()), - m_name(), m_data(), m_value(), m_error(), m_value_str(), - m_old_value_str(), m_location_str(), m_summary_str(), m_object_desc_str(), - m_validation_result(), m_manager(parent.GetManager()), m_children(), - m_synthetic_children(), m_dynamic_value(NULL), m_synthetic_value(NULL), - m_deref_valobj(NULL), m_format(eFormatDefault), + m_parent(&parent), m_root(nullptr), + m_update_point(parent.GetUpdatePoint()), m_name(), m_data(), m_value(), + m_error(), m_value_str(), m_old_value_str(), m_location_str(), + m_summary_str(), m_object_desc_str(), m_validation_result(), + m_manager(parent.GetManager()), m_children(), m_synthetic_children(), + m_dynamic_value(nullptr), m_synthetic_value(nullptr), + m_deref_valobj(nullptr), m_format(eFormatDefault), m_last_format(eFormatDefault), m_last_format_mgr_revision(0), m_type_summary_sp(), m_type_format_sp(), m_synthetic_children_sp(), m_type_validator_sp(), m_user_id_of_forced_summary(), @@ -106,21 +104,19 @@ m_manager->ManageObject(this); } -//---------------------------------------------------------------------- // ValueObject constructor -//---------------------------------------------------------------------- ValueObject::ValueObject(ExecutionContextScope *exe_scope, AddressType child_ptr_or_ref_addr_type) : UserID(++g_value_obj_uid), // Unique identifier for every value object - m_parent(NULL), m_root(NULL), m_update_point(exe_scope), m_name(), + m_parent(nullptr), m_root(nullptr), m_update_point(exe_scope), m_name(), m_data(), m_value(), m_error(), m_value_str(), m_old_value_str(), m_location_str(), m_summary_str(), m_object_desc_str(), m_validation_result(), m_manager(), m_children(), m_synthetic_children(), - m_dynamic_value(NULL), m_synthetic_value(NULL), m_deref_valobj(NULL), - m_format(eFormatDefault), m_last_format(eFormatDefault), - m_last_format_mgr_revision(0), m_type_summary_sp(), m_type_format_sp(), - m_synthetic_children_sp(), m_type_validator_sp(), - m_user_id_of_forced_summary(), + m_dynamic_value(nullptr), m_synthetic_value(nullptr), + m_deref_valobj(nullptr), m_format(eFormatDefault), + m_last_format(eFormatDefault), m_last_format_mgr_revision(0), + m_type_summary_sp(), m_type_format_sp(), m_synthetic_children_sp(), + m_type_validator_sp(), m_user_id_of_forced_summary(), m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type), m_value_checksum(), m_preferred_display_language(lldb::eLanguageTypeUnknown), @@ -135,9 +131,7 @@ m_manager->ManageObject(this); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ValueObject::~ValueObject() {} bool ValueObject::UpdateValueIfNeeded(bool update_format) { @@ -285,51 +279,21 @@ return compiler_type; } - CompilerType class_type; - bool is_pointer_type = false; - - if (ClangASTContext::IsObjCObjectPointerType(compiler_type, &class_type)) { - is_pointer_type = true; - } else if (ClangASTContext::IsObjCObjectOrInterfaceType(compiler_type)) { - class_type = compiler_type; - } else { - return compiler_type; - } - m_did_calculate_complete_objc_class_type = true; - if (class_type) { - ConstString class_name(class_type.GetConstTypeName()); + ProcessSP process_sp( + GetUpdatePoint().GetExecutionContextRef().GetProcessSP()); - if (class_name) { - ProcessSP process_sp( - GetUpdatePoint().GetExecutionContextRef().GetProcessSP()); + if (!process_sp) + return compiler_type; - if (process_sp) { - ObjCLanguageRuntime *objc_language_runtime( - process_sp->GetObjCLanguageRuntime()); - - if (objc_language_runtime) { - TypeSP complete_objc_class_type_sp = - objc_language_runtime->LookupInCompleteClassCache(class_name); - - if (complete_objc_class_type_sp) { - CompilerType complete_class( - complete_objc_class_type_sp->GetFullCompilerType()); - - if (complete_class.GetCompleteType()) { - if (is_pointer_type) { - m_override_type = complete_class.GetPointerType(); - } else { - m_override_type = complete_class; - } - - if (m_override_type.IsValid()) - return m_override_type; - } - } - } - } + if (auto *runtime = + process_sp->GetLanguageRuntime(GetObjectRuntimeLanguage())) { + if (llvm::Optional<CompilerType> complete_type = + runtime->GetRuntimeType(compiler_type)) { + m_override_type = complete_type.getValue(); + if (m_override_type.IsValid()) + return m_override_type; } } return compiler_type; @@ -351,7 +315,7 @@ return m_error; } -const ConstString &ValueObject::GetName() const { return m_name; } +ConstString ValueObject::GetName() const { return m_name; } const char *ValueObject::GetLocationAsCString() { return GetLocationAsCStringImpl(m_value, m_data); @@ -471,7 +435,7 @@ } ValueObject *child = m_children.GetChildAtIndex(idx); - if (child != NULL) + if (child != nullptr) return child->GetSP(); } return child_sp; @@ -544,13 +508,13 @@ return root; } -size_t ValueObject::GetIndexOfChildWithName(const ConstString &name) { +size_t ValueObject::GetIndexOfChildWithName(ConstString name) { bool omit_empty_base_classes = true; return GetCompilerType().GetIndexOfChildWithName(name.GetCString(), omit_empty_base_classes); } -ValueObjectSP ValueObject::GetChildMemberWithName(const ConstString &name, +ValueObjectSP ValueObject::GetChildMemberWithName(ConstString name, bool can_create) { // when getting a child by name, it could be buried inside some base classes // (which really aren't part of the expression path), so we need a vector of @@ -618,12 +582,12 @@ m_children.SetChildrenCount(num_children); } -void ValueObject::SetName(const ConstString &name) { m_name = name; } +void ValueObject::SetName(ConstString name) { m_name = name; } ValueObject *ValueObject::CreateChildAtIndex(size_t idx, bool synthetic_array_member, int32_t synthetic_index) { - ValueObject *valobj = NULL; + ValueObject *valobj = nullptr; bool omit_empty_base_classes = true; bool ignore_array_bounds = synthetic_array_member; @@ -716,7 +680,7 @@ summary_options); } if (m_summary_str.empty()) - return NULL; + return nullptr; return m_summary_str.c_str(); } @@ -769,12 +733,12 @@ if (is_pointer_type) { Status error; ValueObjectSP pointee_sp = Dereference(error); - if (error.Fail() || pointee_sp.get() == NULL) + if (error.Fail() || pointee_sp.get() == nullptr) return 0; return pointee_sp->GetData(data, error); } else { ValueObjectSP child_sp = GetChildAtIndex(0, true); - if (child_sp.get() == NULL) + if (child_sp.get() == nullptr) return 0; Status error; return child_sp->GetData(data, error); @@ -783,7 +747,7 @@ } else /* (items > 1) */ { Status error; - lldb_private::DataBufferHeap *heap_buf_ptr = NULL; + lldb_private::DataBufferHeap *heap_buf_ptr = nullptr; lldb::DataBufferSP data_sp(heap_buf_ptr = new lldb_private::DataBufferHeap()); @@ -929,7 +893,7 @@ static bool CopyStringDataToBufferSP(const StreamString &source, lldb::DataBufferSP &destination) { - destination.reset(new DataBufferHeap(source.GetSize() + 1, 0)); + destination = std::make_shared<DataBufferHeap>(source.GetSize() + 1, 0); memcpy(destination->GetBytes(), source.GetString().data(), source.GetSize()); return true; } @@ -970,7 +934,7 @@ if (is_array) { // We have an array uint64_t array_size = 0; - if (compiler_type.IsArrayType(NULL, &array_size, NULL)) { + if (compiler_type.IsArrayType(nullptr, &array_size, nullptr)) { cstr_len = array_size; if (cstr_len > max_length) { capped_data = true; @@ -992,7 +956,7 @@ CopyStringDataToBufferSP(s, buffer_sp); return {0, was_capped}; } - buffer_sp.reset(new DataBufferHeap(cstr_len, 0)); + buffer_sp = std::make_shared<DataBufferHeap>(cstr_len, 0); memcpy(buffer_sp->GetBytes(), cstr, cstr_len); return {cstr_len, was_capped}; } else { @@ -1092,44 +1056,40 @@ } const char *ValueObject::GetObjectDescription() { - if (!UpdateValueIfNeeded(true)) - return NULL; + return nullptr; + // Return cached value. if (!m_object_desc_str.empty()) return m_object_desc_str.c_str(); ExecutionContext exe_ctx(GetExecutionContextRef()); Process *process = exe_ctx.GetProcessPtr(); - if (process == NULL) - return NULL; + if (!process) + return nullptr; - StreamString s; - - LanguageType language = GetObjectRuntimeLanguage(); - LanguageRuntime *runtime = process->GetLanguageRuntime(language); - - if (runtime == NULL) { - // Aw, hell, if the things a pointer, or even just an integer, let's try - // ObjC anyway... - CompilerType compiler_type = GetCompilerType(); - if (compiler_type) { - bool is_signed; - if (compiler_type.IsIntegerType(is_signed) || - compiler_type.IsPointerType()) { - runtime = process->GetLanguageRuntime(eLanguageTypeObjC); + // Returns the object description produced by one language runtime. + auto get_object_description = [&](LanguageType language) -> const char * { + if (LanguageRuntime *runtime = process->GetLanguageRuntime(language)) { + StreamString s; + if (runtime->GetObjectDescription(s, *this)) { + m_object_desc_str.append(s.GetString()); + return m_object_desc_str.c_str(); } } - } + return nullptr; + }; - if (runtime && runtime->GetObjectDescription(s, *this)) { - m_object_desc_str.append(s.GetString()); - } + // Try the native language runtime first. + LanguageType native_language = GetObjectRuntimeLanguage(); + if (const char *desc = get_object_description(native_language)) + return desc; - if (m_object_desc_str.empty()) - return NULL; - else - return m_object_desc_str.c_str(); + // Try the Objective-C language runtime. This fallback is necessary + // for Objective-C++ and mixed Objective-C / C++ programs. + if (Language::LanguageIsCFamily(native_language)) + return get_object_description(eLanguageTypeObjC); + return nullptr; } bool ValueObject::GetValueAsCString(const lldb_private::TypeFormatImpl &format, @@ -1169,7 +1129,7 @@ if (my_format != m_last_format || m_value_str.empty()) { m_last_format = my_format; if (!format_sp) - format_sp.reset(new TypeFormatImpl_Format(my_format)); + format_sp = std::make_shared<TypeFormatImpl_Format>(my_format); if (GetValueAsCString(*format_sp.get(), m_value_str)) { if (!m_value_did_change && m_old_value_valid) { // The value was gotten successfully, so we consider the value as @@ -1180,7 +1140,7 @@ } } if (m_value_str.empty()) - return NULL; + return nullptr; return m_value_str.c_str(); } @@ -1291,7 +1251,7 @@ buffer_sp, lldb::eByteOrderInvalid, 8)); // none of this matters for a string - pass some defaults options.SetStream(&s); - options.SetPrefixToken(0); + options.SetPrefixToken(nullptr); options.SetQuote('"'); options.SetSourceSize(buffer_sp->GetByteSize()); options.SetIsTruncated(read_string.second); @@ -1658,12 +1618,12 @@ return GetCompilerType().GetMinimumLanguage(); } -void ValueObject::AddSyntheticChild(const ConstString &key, +void ValueObject::AddSyntheticChild(ConstString key, ValueObject *valobj) { m_synthetic_children[key] = valobj; } -ValueObjectSP ValueObject::GetSyntheticChild(const ConstString &key) const { +ValueObjectSP ValueObject::GetSyntheticChild(ConstString key) const { ValueObjectSP synthetic_child_sp; std::map<ConstString, ValueObject *>::const_iterator pos = m_synthetic_children.find(key); @@ -1680,7 +1640,7 @@ bool ValueObject::IsPointerType() { return GetCompilerType().IsPointerType(); } bool ValueObject::IsArrayType() { - return GetCompilerType().IsArrayType(NULL, NULL, NULL); + return GetCompilerType().IsArrayType(nullptr, nullptr, nullptr); } bool ValueObject::IsScalarType() { return GetCompilerType().IsScalarType(); } @@ -1699,20 +1659,33 @@ if (process) return process->IsPossibleDynamicValue(*this); else - return GetCompilerType().IsPossibleDynamicType(NULL, true, true); + return GetCompilerType().IsPossibleDynamicType(nullptr, true, true); } bool ValueObject::IsRuntimeSupportValue() { Process *process(GetProcessSP().get()); - if (process) { - LanguageRuntime *runtime = - process->GetLanguageRuntime(GetObjectRuntimeLanguage()); - if (!runtime) - runtime = process->GetObjCLanguageRuntime(); - if (runtime) - return runtime->IsRuntimeSupportValue(*this); + if (!process) + return false; + + // We trust the the compiler did the right thing and marked runtime support + // values as artificial. + if (!GetVariable() || !GetVariable()->IsArtificial()) + return false; + + LanguageType lang = eLanguageTypeUnknown; + if (auto *sym_ctx_scope = GetSymbolContextScope()) { + if (auto *func = sym_ctx_scope->CalculateSymbolContextFunction()) + lang = func->GetLanguage(); + else if (auto *comp_unit = + sym_ctx_scope->CalculateSymbolContextCompileUnit()) + lang = comp_unit->GetLanguage(); } - return false; + + if (auto *runtime = process->GetLanguageRuntime(lang)) + if (runtime->IsWhitelistedRuntimeValue(GetName())) + return false; + + return true; } bool ValueObject::IsNilReference() { @@ -1907,7 +1880,7 @@ // We haven't made a synthetic array member for expression yet, so lets // make one and cache it for any future reference. synthetic_child_sp = GetValueForExpressionPath( - expression, NULL, NULL, + expression, nullptr, nullptr, GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal( GetValueForExpressionPathOptions::SyntheticChildrenTraversal:: None)); @@ -1930,7 +1903,7 @@ TargetSP target_sp(GetTargetSP()); if (target_sp && !target_sp->GetEnableSyntheticValue()) { - m_synthetic_value = NULL; + m_synthetic_value = nullptr; return; } @@ -1939,7 +1912,7 @@ if (!UpdateFormatsIfNeeded() && m_synthetic_value) return; - if (m_synthetic_children_sp.get() == NULL) + if (m_synthetic_children_sp.get() == nullptr) return; if (current_synth_sp == m_synthetic_children_sp && m_synthetic_value) @@ -1966,7 +1939,7 @@ if (use_dynamic == eNoDynamicValues) return ValueObjectSP(); - if (!IsDynamic() && m_dynamic_value == NULL) { + if (!IsDynamic() && m_dynamic_value == nullptr) { CalculateDynamicValue(use_dynamic); } if (m_dynamic_value) @@ -1994,7 +1967,7 @@ bool ValueObject::HasSyntheticValue() { UpdateFormatsIfNeeded(); - if (m_synthetic_children_sp.get() == NULL) + if (m_synthetic_children_sp.get() == nullptr) return false; CalculateSyntheticValue(true); @@ -2027,7 +2000,7 @@ else return GetParent(); } - return NULL; + return nullptr; } bool ValueObject::IsBaseClass(uint32_t &depth) { @@ -2741,7 +2714,7 @@ printer.PrintValueObject(); } -ValueObjectSP ValueObject::CreateConstantValue(const ConstString &name) { +ValueObjectSP ValueObject::CreateConstantValue(ConstString name) { ValueObjectSP valobj_sp; if (UpdateValueIfNeeded(false) && m_error.Success()) { @@ -2917,7 +2890,7 @@ return ValueObjectCast::Create(*this, GetName(), compiler_type); } -lldb::ValueObjectSP ValueObject::Clone(const ConstString &new_name) { +lldb::ValueObjectSP ValueObject::Clone(ConstString new_name) { return ValueObjectCast::Create(*this, new_name, GetCompilerType()); } @@ -3012,12 +2985,12 @@ ExecutionContext exe_ctx( m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped)); - if (exe_ctx.GetTargetPtr() == NULL) + if (exe_ctx.GetTargetPtr() == nullptr) return false; // If we don't have a process nothing can change. Process *process = exe_ctx.GetProcessPtr(); - if (process == NULL) + if (process == nullptr) return false; // If our stop id is the current stop ID, nothing has changed: @@ -3098,7 +3071,7 @@ if ((clear_mask & eClearUserVisibleDataItemsSyntheticChildren) == eClearUserVisibleDataItemsSyntheticChildren) { if (m_synthetic_value) - m_synthetic_value = NULL; + m_synthetic_value = nullptr; } if ((clear_mask & eClearUserVisibleDataItemsValidator) == @@ -3111,7 +3084,7 @@ if (!m_parent->IsPointerOrReferenceType()) return m_parent->GetSymbolContextScope(); } - return NULL; + return nullptr; } lldb::ValueObjectSP @@ -3405,4 +3378,3 @@ return m_root_valobj_sp->GetFrameSP(); return lldb::StackFrameSP(); } -
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectCast.cpp b/src/llvm-project/lldb/source/Core/ValueObjectCast.cpp index fb0b55b..6ccda8c 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectCast.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectCast.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectCast.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,14 +22,14 @@ using namespace lldb_private; lldb::ValueObjectSP ValueObjectCast::Create(ValueObject &parent, - const ConstString &name, + ConstString name, const CompilerType &cast_type) { ValueObjectCast *cast_valobj_ptr = new ValueObjectCast(parent, name, cast_type); return cast_valobj_ptr->GetSP(); } -ValueObjectCast::ValueObjectCast(ValueObject &parent, const ConstString &name, +ValueObjectCast::ValueObjectCast(ValueObject &parent, ConstString name, const CompilerType &cast_type) : ValueObject(parent), m_cast_type(cast_type) { SetName(name);
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectChild.cpp b/src/llvm-project/lldb/source/Core/ValueObjectChild.cpp index 0f7be83..01f2e20 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectChild.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectChild.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectChild.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,7 +28,7 @@ ValueObjectChild::ValueObjectChild( ValueObject &parent, const CompilerType &compiler_type, - const ConstString &name, uint64_t byte_size, int32_t byte_offset, + ConstString name, uint64_t byte_size, int32_t byte_offset, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool is_base_class, bool is_deref_of_parent, AddressType child_ptr_or_ref_addr_type, uint64_t language_flags)
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectConstResult.cpp b/src/llvm-project/lldb/source/Core/ValueObjectConstResult.cpp index f6e32c0..a1b2cac 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectConstResult.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectConstResult.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectConstResult.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -50,7 +49,7 @@ ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope, const CompilerType &compiler_type, - const ConstString &name, + ConstString name, const DataExtractor &data, lldb::addr_t address) { return (new ValueObjectConstResult(exe_scope, compiler_type, name, data, @@ -60,7 +59,7 @@ ValueObjectConstResult::ValueObjectConstResult( ExecutionContextScope *exe_scope, const CompilerType &compiler_type, - const ConstString &name, const DataExtractor &data, lldb::addr_t address) + ConstString name, const DataExtractor &data, lldb::addr_t address) : ValueObject(exe_scope), m_type_name(), m_byte_size(0), m_impl(this, address) { m_data = data; @@ -82,7 +81,7 @@ ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope, const CompilerType &compiler_type, - const ConstString &name, + ConstString name, const lldb::DataBufferSP &data_sp, lldb::ByteOrder data_byte_order, uint32_t data_addr_size, @@ -94,14 +93,14 @@ ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope, Value &value, - const ConstString &name, + ConstString name, Module *module) { return (new ValueObjectConstResult(exe_scope, value, name, module))->GetSP(); } ValueObjectConstResult::ValueObjectConstResult( ExecutionContextScope *exe_scope, const CompilerType &compiler_type, - const ConstString &name, const lldb::DataBufferSP &data_sp, + ConstString name, const lldb::DataBufferSP &data_sp, lldb::ByteOrder data_byte_order, uint32_t data_addr_size, lldb::addr_t address) : ValueObject(exe_scope), m_type_name(), m_byte_size(0), @@ -121,7 +120,7 @@ ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope, const CompilerType &compiler_type, - const ConstString &name, + ConstString name, lldb::addr_t address, AddressType address_type, uint32_t addr_byte_size) { @@ -132,7 +131,7 @@ ValueObjectConstResult::ValueObjectConstResult( ExecutionContextScope *exe_scope, const CompilerType &compiler_type, - const ConstString &name, lldb::addr_t address, AddressType address_type, + ConstString name, lldb::addr_t address, AddressType address_type, uint32_t addr_byte_size) : ValueObject(exe_scope), m_type_name(), m_byte_size(0), m_impl(this, address) { @@ -176,7 +175,7 @@ ValueObjectConstResult::ValueObjectConstResult(ExecutionContextScope *exe_scope, const Value &value, - const ConstString &name, + ConstString name, Module *module) : ValueObject(exe_scope), m_type_name(), m_byte_size(0), m_impl(this) { m_value = value;
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectConstResultCast.cpp b/src/llvm-project/lldb/source/Core/ValueObjectConstResultCast.cpp index c040432..b47e699 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectConstResultCast.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectConstResultCast.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectConstResultCast.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,7 +21,7 @@ using namespace lldb_private; ValueObjectConstResultCast::ValueObjectConstResultCast( - ValueObject &parent, const ConstString &name, const CompilerType &cast_type, + ValueObject &parent, ConstString name, const CompilerType &cast_type, lldb::addr_t live_address) : ValueObjectCast(parent, name, cast_type), m_impl(this, live_address) { m_name = name;
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectConstResultChild.cpp b/src/llvm-project/lldb/source/Core/ValueObjectConstResultChild.cpp index 441c164..4e0b303 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectConstResultChild.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectConstResultChild.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectConstResultChild.cpp --------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,7 +23,7 @@ ValueObjectConstResultChild::ValueObjectConstResultChild( ValueObject &parent, const CompilerType &compiler_type, - const ConstString &name, uint32_t byte_size, int32_t byte_offset, + ConstString name, uint32_t byte_size, int32_t byte_offset, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool is_base_class, bool is_deref_of_parent, lldb::addr_t live_address, uint64_t language_flags)
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectConstResultImpl.cpp b/src/llvm-project/lldb/source/Core/ValueObjectConstResultImpl.cpp index 6bf8e62..de51735 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectConstResultImpl.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectConstResultImpl.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectConstResultImpl.cpp ---------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -40,7 +39,7 @@ m_address_of_backend() {} lldb::ValueObjectSP ValueObjectConstResultImpl::Dereference(Status &error) { - if (m_impl_backend == NULL) + if (m_impl_backend == nullptr) return lldb::ValueObjectSP(); return m_impl_backend->ValueObject::Dereference(error); @@ -48,12 +47,12 @@ ValueObject *ValueObjectConstResultImpl::CreateChildAtIndex( size_t idx, bool synthetic_array_member, int32_t synthetic_index) { - if (m_impl_backend == NULL) - return NULL; + if (m_impl_backend == nullptr) + return nullptr; m_impl_backend->UpdateValueIfNeeded(false); - ValueObjectConstResultChild *valobj = NULL; + ValueObjectConstResultChild *valobj = nullptr; bool omit_empty_base_classes = true; bool ignore_array_bounds = synthetic_array_member; @@ -107,7 +106,7 @@ lldb::ValueObjectSP ValueObjectConstResultImpl::GetSyntheticChildAtOffset( uint32_t offset, const CompilerType &type, bool can_create, ConstString name_const_str) { - if (m_impl_backend == NULL) + if (m_impl_backend == nullptr) return lldb::ValueObjectSP(); return m_impl_backend->ValueObject::GetSyntheticChildAtOffset( @@ -115,10 +114,10 @@ } lldb::ValueObjectSP ValueObjectConstResultImpl::AddressOf(Status &error) { - if (m_address_of_backend.get() != NULL) + if (m_address_of_backend.get() != nullptr) return m_address_of_backend; - if (m_impl_backend == NULL) + if (m_impl_backend == nullptr) return lldb::ValueObjectSP(); if (m_live_address != LLDB_INVALID_ADDRESS) { CompilerType compiler_type(m_impl_backend->GetCompilerType()); @@ -144,7 +143,7 @@ lldb::ValueObjectSP ValueObjectConstResultImpl::Cast(const CompilerType &compiler_type) { - if (m_impl_backend == NULL) + if (m_impl_backend == nullptr) return lldb::ValueObjectSP(); ValueObjectConstResultCast *result_cast = @@ -157,7 +156,7 @@ ValueObjectConstResultImpl::GetAddressOf(bool scalar_is_load_address, AddressType *address_type) { - if (m_impl_backend == NULL) + if (m_impl_backend == nullptr) return 0; if (m_live_address == LLDB_INVALID_ADDRESS) { @@ -174,7 +173,7 @@ size_t ValueObjectConstResultImpl::GetPointeeData(DataExtractor &data, uint32_t item_idx, uint32_t item_count) { - if (m_impl_backend == NULL) + if (m_impl_backend == nullptr) return 0; return m_impl_backend->ValueObject::GetPointeeData(data, item_idx, item_count);
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectDynamicValue.cpp b/src/llvm-project/lldb/source/Core/ValueObjectDynamicValue.cpp index 161b6e4..90b46d1 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectDynamicValue.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectDynamicValue.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectDynamicValue.cpp ------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectList.cpp b/src/llvm-project/lldb/source/Core/ValueObjectList.cpp index 7a7e0d8..358a1b1 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectList.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectList.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectList.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,13 +17,6 @@ using namespace lldb; using namespace lldb_private; -ValueObjectList::ValueObjectList() : m_value_objects() {} - -ValueObjectList::ValueObjectList(const ValueObjectList &rhs) - : m_value_objects(rhs.m_value_objects) {} - -ValueObjectList::~ValueObjectList() {} - const ValueObjectList &ValueObjectList::operator=(const ValueObjectList &rhs) { if (this != &rhs) m_value_objects = rhs.m_value_objects;
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectMemory.cpp b/src/llvm-project/lldb/source/Core/ValueObjectMemory.cpp index 2410320..95d4330 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectMemory.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectMemory.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectMemory.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -50,7 +49,7 @@ : ValueObject(exe_scope), m_address(address), m_type_sp(type_sp), m_compiler_type() { // Do not attempt to construct one of these objects with no variable! - assert(m_type_sp.get() != NULL); + assert(m_type_sp.get() != nullptr); SetName(ConstString(name)); m_value.SetContext(Value::eContextTypeLLDBType, m_type_sp.get()); TargetSP target_sp(GetTargetSP()); @@ -137,10 +136,8 @@ uint64_t ValueObjectMemory::GetByteSize() { if (m_type_sp) - return m_type_sp->GetByteSize(); - if (llvm::Optional<uint64_t> size = m_compiler_type.GetByteSize(nullptr)) - return *size; - return 0; + return m_type_sp->GetByteSize().getValueOr(0); + return m_compiler_type.GetByteSize(nullptr).getValueOr(0); } lldb::ValueType ValueObjectMemory::GetValueType() const {
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectRegister.cpp b/src/llvm-project/lldb/source/Core/ValueObjectRegister.cpp index 41d1c27..75a254f 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectRegister.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectRegister.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectRegister.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -77,7 +76,7 @@ else m_reg_ctx_sp.reset(); - if (m_reg_ctx_sp.get() == NULL) { + if (m_reg_ctx_sp.get() == nullptr) { SetValueIsValid(false); m_error.SetErrorToGenericError(); } else @@ -88,7 +87,7 @@ ValueObject *ValueObjectRegisterContext::CreateChildAtIndex( size_t idx, bool synthetic_array_member, int32_t synthetic_index) { - ValueObject *new_valobj = NULL; + ValueObject *new_valobj = nullptr; const size_t num_children = GetNumChildren(); if (idx < num_children) { @@ -113,7 +112,7 @@ ValueObjectRegisterSet::ValueObjectRegisterSet(ExecutionContextScope *exe_scope, lldb::RegisterContextSP ®_ctx, uint32_t reg_set_idx) - : ValueObject(exe_scope), m_reg_ctx_sp(reg_ctx), m_reg_set(NULL), + : ValueObject(exe_scope), m_reg_ctx_sp(reg_ctx), m_reg_set(nullptr), m_reg_set_idx(reg_set_idx) { assert(reg_ctx); m_reg_set = reg_ctx->GetRegisterSet(m_reg_set_idx); @@ -150,13 +149,13 @@ SetValueDidChange(false); ExecutionContext exe_ctx(GetExecutionContextRef()); StackFrame *frame = exe_ctx.GetFramePtr(); - if (frame == NULL) + if (frame == nullptr) m_reg_ctx_sp.reset(); else { m_reg_ctx_sp = frame->GetRegisterContext(); if (m_reg_ctx_sp) { const RegisterSet *reg_set = m_reg_ctx_sp->GetRegisterSet(m_reg_set_idx); - if (reg_set == NULL) + if (reg_set == nullptr) m_reg_ctx_sp.reset(); else if (m_reg_set != reg_set) { SetValueDidChange(true); @@ -176,7 +175,7 @@ ValueObject *ValueObjectRegisterSet::CreateChildAtIndex( size_t idx, bool synthetic_array_member, int32_t synthetic_index) { - ValueObject *valobj = NULL; + ValueObject *valobj = nullptr; if (m_reg_ctx_sp && m_reg_set) { const size_t num_children = GetNumChildren(); if (idx < num_children) @@ -187,13 +186,13 @@ } lldb::ValueObjectSP -ValueObjectRegisterSet::GetChildMemberWithName(const ConstString &name, +ValueObjectRegisterSet::GetChildMemberWithName(ConstString name, bool can_create) { - ValueObject *valobj = NULL; + ValueObject *valobj = nullptr; if (m_reg_ctx_sp && m_reg_set) { const RegisterInfo *reg_info = m_reg_ctx_sp->GetRegisterInfoByName(name.AsCString()); - if (reg_info != NULL) + if (reg_info != nullptr) valobj = new ValueObjectRegister(*this, m_reg_ctx_sp, reg_info->kinds[eRegisterKindLLDB]); } @@ -204,11 +203,11 @@ } size_t -ValueObjectRegisterSet::GetIndexOfChildWithName(const ConstString &name) { +ValueObjectRegisterSet::GetIndexOfChildWithName(ConstString name) { if (m_reg_ctx_sp && m_reg_set) { const RegisterInfo *reg_info = m_reg_ctx_sp->GetRegisterInfoByName(name.AsCString()); - if (reg_info != NULL) + if (reg_info != nullptr) return reg_info->kinds[eRegisterKindLLDB]; } return UINT32_MAX; @@ -290,7 +289,7 @@ m_error.Clear(); ExecutionContext exe_ctx(GetExecutionContextRef()); StackFrame *frame = exe_ctx.GetFramePtr(); - if (frame == NULL) { + if (frame == nullptr) { m_reg_ctx_sp.reset(); m_reg_value.Clear(); }
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectSyntheticFilter.cpp b/src/llvm-project/lldb/source/Core/ValueObjectSyntheticFilter.cpp index d22b1dc..4004732 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectSyntheticFilter.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectSyntheticFilter.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectSyntheticFilter.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -37,7 +36,7 @@ return m_backend.GetChildAtIndex(idx, true); } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return m_backend.GetIndexOfChildWithName(name); } @@ -73,7 +72,7 @@ } ConstString ValueObjectSynthetic::GetDisplayTypeName() { - if (ConstString synth_name = m_synth_filter_ap->GetSyntheticTypeName()) + if (ConstString synth_name = m_synth_filter_up->GetSyntheticTypeName()) return synth_name; return m_parent->GetDisplayTypeName(); @@ -87,7 +86,7 @@ return m_synthetic_children_count <= max ? m_synthetic_children_count : max; if (max < UINT32_MAX) { - size_t num_children = m_synth_filter_ap->CalculateNumChildren(max); + size_t num_children = m_synth_filter_up->CalculateNumChildren(max); if (log) log->Printf("[ValueObjectSynthetic::CalculateNumChildren] for VO of name " "%s and type %s, the filter returned %zu child values", @@ -96,7 +95,7 @@ return num_children; } else { size_t num_children = (m_synthetic_children_count = - m_synth_filter_ap->CalculateNumChildren(max)); + m_synth_filter_up->CalculateNumChildren(max)); if (log) log->Printf("[ValueObjectSynthetic::CalculateNumChildren] for VO of name " "%s and type %s, the filter returned %zu child values", @@ -118,7 +117,7 @@ bool ValueObjectSynthetic::MightHaveChildren() { if (m_might_have_children == eLazyBoolCalculate) m_might_have_children = - (m_synth_filter_ap->MightHaveChildren() ? eLazyBoolYes : eLazyBoolNo); + (m_synth_filter_up->MightHaveChildren() ? eLazyBoolYes : eLazyBoolNo); return (m_might_have_children != eLazyBoolNo); } @@ -141,9 +140,9 @@ valobj_for_frontend = deref_sp.get(); } } - m_synth_filter_ap = (m_synth_sp->GetFrontEnd(*valobj_for_frontend)); - if (!m_synth_filter_ap.get()) - m_synth_filter_ap = llvm::make_unique<DummySyntheticFrontEnd>(*m_parent); + m_synth_filter_up = (m_synth_sp->GetFrontEnd(*valobj_for_frontend)); + if (!m_synth_filter_up) + m_synth_filter_up = llvm::make_unique<DummySyntheticFrontEnd>(*m_parent); } bool ValueObjectSynthetic::UpdateValue() { @@ -174,7 +173,7 @@ } // let our backend do its update - if (!m_synth_filter_ap->Update()) { + if (!m_synth_filter_up->Update()) { if (log) log->Printf("[ValueObjectSynthetic::UpdateValue] name=%s, synthetic " "filter said caches are stale - clearing", @@ -199,7 +198,7 @@ m_provides_value = eLazyBoolCalculate; - lldb::ValueObjectSP synth_val(m_synth_filter_ap->GetSyntheticValue()); + lldb::ValueObjectSP synth_val(m_synth_filter_up->GetSyntheticValue()); if (synth_val && synth_val->CanProvideValue()) { if (log) @@ -236,13 +235,13 @@ ValueObject *valobj; if (!m_children_byindex.GetValueForKey(idx, valobj)) { - if (can_create && m_synth_filter_ap.get() != nullptr) { + if (can_create && m_synth_filter_up != nullptr) { if (log) log->Printf("[ValueObjectSynthetic::GetChildAtIndex] name=%s, child at " "index %zu not cached and will be created", GetName().AsCString(), idx); - lldb::ValueObjectSP synth_guy = m_synth_filter_ap->GetChildAtIndex(idx); + lldb::ValueObjectSP synth_guy = m_synth_filter_up->GetChildAtIndex(idx); if (log) log->Printf( @@ -269,7 +268,7 @@ "index %zu not cached and cannot " "be created (can_create = %s, synth_filter = %p)", GetName().AsCString(), idx, can_create ? "yes" : "no", - static_cast<void *>(m_synth_filter_ap.get())); + static_cast<void *>(m_synth_filter_up.get())); return lldb::ValueObjectSP(); } @@ -284,7 +283,7 @@ } lldb::ValueObjectSP -ValueObjectSynthetic::GetChildMemberWithName(const ConstString &name, +ValueObjectSynthetic::GetChildMemberWithName(ConstString name, bool can_create) { UpdateValueIfNeeded(); @@ -296,19 +295,19 @@ return GetChildAtIndex(index, can_create); } -size_t ValueObjectSynthetic::GetIndexOfChildWithName(const ConstString &name) { +size_t ValueObjectSynthetic::GetIndexOfChildWithName(ConstString name) { UpdateValueIfNeeded(); uint32_t found_index = UINT32_MAX; bool did_find = m_name_toindex.GetValueForKey(name.GetCString(), found_index); - if (!did_find && m_synth_filter_ap.get() != nullptr) { - uint32_t index = m_synth_filter_ap->GetIndexOfChildWithName(name); + if (!did_find && m_synth_filter_up != nullptr) { + uint32_t index = m_synth_filter_up->GetIndexOfChildWithName(name); if (index == UINT32_MAX) return index; m_name_toindex.SetValueForKey(name.GetCString(), index); return index; - } else if (!did_find && m_synth_filter_ap.get() == nullptr) + } else if (!did_find && m_synth_filter_up == nullptr) return UINT32_MAX; else /*if (iter != m_name_toindex.end())*/ return found_index;
diff --git a/src/llvm-project/lldb/source/Core/ValueObjectVariable.cpp b/src/llvm-project/lldb/source/Core/ValueObjectVariable.cpp index 4d401c5..5aee824 100644 --- a/src/llvm-project/lldb/source/Core/ValueObjectVariable.cpp +++ b/src/llvm-project/lldb/source/Core/ValueObjectVariable.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectVariable.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -58,7 +57,7 @@ const lldb::VariableSP &var_sp) : ValueObject(exe_scope), m_variable_sp(var_sp) { // Do not attempt to construct one of these objects with no variable! - assert(m_variable_sp.get() != NULL); + assert(m_variable_sp.get() != nullptr); m_name = var_sp->GetName(); } @@ -136,7 +135,7 @@ else m_error.SetErrorString("empty constant data"); // constant bytes can't be edited - sorry - m_resolved_value.SetContext(Value::eContextTypeInvalid, NULL); + m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr); } else { lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS; ExecutionContext exe_ctx(GetExecutionContextRef()); @@ -262,7 +261,7 @@ SetValueIsValid(m_error.Success()); } else { // could not find location, won't allow editing - m_resolved_value.SetContext(Value::eContextTypeInvalid, NULL); + m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr); } } return m_error.Success(); @@ -299,7 +298,7 @@ SymbolContextScope *ValueObjectVariable::GetSymbolContextScope() { if (m_variable_sp) return m_variable_sp->GetSymbolContextScope(); - return NULL; + return nullptr; } bool ValueObjectVariable::GetDeclaration(Declaration &decl) {
diff --git a/src/llvm-project/lldb/source/DataFormatters/CXXFunctionPointer.cpp b/src/llvm-project/lldb/source/DataFormatters/CXXFunctionPointer.cpp index 9059891..0ca000e 100644 --- a/src/llvm-project/lldb/source/DataFormatters/CXXFunctionPointer.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/CXXFunctionPointer.cpp
@@ -1,9 +1,8 @@ //===-- CXXFunctionPointer.cpp-----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/DataFormatters/DataVisualization.cpp b/src/llvm-project/lldb/source/DataFormatters/DataVisualization.cpp index 23b8b6e..08b3b34 100644 --- a/src/llvm-project/lldb/source/DataFormatters/DataVisualization.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/DataVisualization.cpp
@@ -1,10 +1,9 @@ //===-- DataVisualization.cpp ---------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -51,32 +50,21 @@ return GetFormatManager().GetSummaryForType(type_sp); } -#ifndef LLDB_DISABLE_PYTHON lldb::SyntheticChildrenSP DataVisualization::GetSyntheticChildren(ValueObject &valobj, lldb::DynamicValueType use_dynamic) { return GetFormatManager().GetSyntheticChildren(valobj, use_dynamic); } -#endif - -#ifndef LLDB_DISABLE_PYTHON -lldb::SyntheticChildrenSP DataVisualization::GetSyntheticChildrenForType( - lldb::TypeNameSpecifierImplSP type_sp) { - return GetFormatManager().GetSyntheticChildrenForType(type_sp); -} -#endif lldb::TypeFilterImplSP DataVisualization::GetFilterForType(lldb::TypeNameSpecifierImplSP type_sp) { return GetFormatManager().GetFilterForType(type_sp); } -#ifndef LLDB_DISABLE_PYTHON lldb::ScriptedSyntheticChildrenSP DataVisualization::GetSyntheticForType(lldb::TypeNameSpecifierImplSP type_sp) { return GetFormatManager().GetSyntheticForType(type_sp); } -#endif lldb::TypeValidatorImplSP DataVisualization::GetValidator(ValueObject &valobj, @@ -97,11 +85,11 @@ matching_category, matching_type); } -bool DataVisualization::Categories::GetCategory(const ConstString &category, +bool DataVisualization::Categories::GetCategory(ConstString category, lldb::TypeCategoryImplSP &entry, bool allow_create) { entry = GetFormatManager().GetCategory(category, allow_create); - return (entry.get() != NULL); + return (entry.get() != nullptr); } bool DataVisualization::Categories::GetCategory( @@ -112,11 +100,11 @@ return (entry.get() != nullptr); } -void DataVisualization::Categories::Add(const ConstString &category) { +void DataVisualization::Categories::Add(ConstString category) { GetFormatManager().GetCategory(category); } -bool DataVisualization::Categories::Delete(const ConstString &category) { +bool DataVisualization::Categories::Delete(ConstString category) { GetFormatManager().DisableCategory(category); return GetFormatManager().DeleteCategory(category); } @@ -125,12 +113,12 @@ GetFormatManager().ClearCategories(); } -void DataVisualization::Categories::Clear(const ConstString &category) { +void DataVisualization::Categories::Clear(ConstString category) { GetFormatManager().GetCategory(category)->Clear( eFormatCategoryItemSummary | eFormatCategoryItemRegexSummary); } -void DataVisualization::Categories::Enable(const ConstString &category, +void DataVisualization::Categories::Enable(ConstString category, TypeCategoryMap::Position pos) { if (GetFormatManager().GetCategory(category)->IsEnabled()) GetFormatManager().DisableCategory(category); @@ -144,7 +132,7 @@ lang_category->Enable(); } -void DataVisualization::Categories::Disable(const ConstString &category) { +void DataVisualization::Categories::Disable(ConstString category) { if (GetFormatManager().GetCategory(category)->IsEnabled()) GetFormatManager().DisableCategory(category); } @@ -193,17 +181,17 @@ } bool DataVisualization::NamedSummaryFormats::GetSummaryFormat( - const ConstString &type, lldb::TypeSummaryImplSP &entry) { + ConstString type, lldb::TypeSummaryImplSP &entry) { return GetFormatManager().GetNamedSummaryContainer().Get(type, entry); } void DataVisualization::NamedSummaryFormats::Add( - const ConstString &type, const lldb::TypeSummaryImplSP &entry) { + ConstString type, const lldb::TypeSummaryImplSP &entry) { GetFormatManager().GetNamedSummaryContainer().Add( FormatManager::GetValidTypeName(type), entry); } -bool DataVisualization::NamedSummaryFormats::Delete(const ConstString &type) { +bool DataVisualization::NamedSummaryFormats::Delete(ConstString type) { return GetFormatManager().GetNamedSummaryContainer().Delete(type); }
diff --git a/src/llvm-project/lldb/source/DataFormatters/DumpValueObjectOptions.cpp b/src/llvm-project/lldb/source/DataFormatters/DumpValueObjectOptions.cpp index 17f8d00..84f2169 100644 --- a/src/llvm-project/lldb/source/DataFormatters/DumpValueObjectOptions.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/DumpValueObjectOptions.cpp
@@ -1,10 +1,9 @@ //===-- DumpValueObjectOptions.cpp -----------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/DataFormatters/FormatCache.cpp b/src/llvm-project/lldb/source/DataFormatters/FormatCache.cpp index bb5f379..7e328cb 100644 --- a/src/llvm-project/lldb/source/DataFormatters/FormatCache.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/FormatCache.cpp
@@ -1,10 +1,9 @@ //===-- FormatCache.cpp ------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -110,7 +109,7 @@ { } -FormatCache::Entry &FormatCache::GetEntry(const ConstString &type) { +FormatCache::Entry &FormatCache::GetEntry(ConstString type) { auto i = m_map.find(type), e = m_map.end(); if (i != e) return i->second; @@ -118,7 +117,7 @@ return m_map[type]; } -bool FormatCache::GetFormat(const ConstString &type, +bool FormatCache::GetFormat(ConstString type, lldb::TypeFormatImplSP &format_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); auto entry = GetEntry(type); @@ -136,7 +135,7 @@ return false; } -bool FormatCache::GetSummary(const ConstString &type, +bool FormatCache::GetSummary(ConstString type, lldb::TypeSummaryImplSP &summary_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); auto entry = GetEntry(type); @@ -154,7 +153,7 @@ return false; } -bool FormatCache::GetSynthetic(const ConstString &type, +bool FormatCache::GetSynthetic(ConstString type, lldb::SyntheticChildrenSP &synthetic_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); auto entry = GetEntry(type); @@ -172,7 +171,7 @@ return false; } -bool FormatCache::GetValidator(const ConstString &type, +bool FormatCache::GetValidator(ConstString type, lldb::TypeValidatorImplSP &validator_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); auto entry = GetEntry(type); @@ -190,25 +189,25 @@ return false; } -void FormatCache::SetFormat(const ConstString &type, +void FormatCache::SetFormat(ConstString type, lldb::TypeFormatImplSP &format_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); GetEntry(type).SetFormat(format_sp); } -void FormatCache::SetSummary(const ConstString &type, +void FormatCache::SetSummary(ConstString type, lldb::TypeSummaryImplSP &summary_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); GetEntry(type).SetSummary(summary_sp); } -void FormatCache::SetSynthetic(const ConstString &type, +void FormatCache::SetSynthetic(ConstString type, lldb::SyntheticChildrenSP &synthetic_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); GetEntry(type).SetSynthetic(synthetic_sp); } -void FormatCache::SetValidator(const ConstString &type, +void FormatCache::SetValidator(ConstString type, lldb::TypeValidatorImplSP &validator_sp) { std::lock_guard<std::recursive_mutex> guard(m_mutex); GetEntry(type).SetValidator(validator_sp);
diff --git a/src/llvm-project/lldb/source/DataFormatters/FormatClasses.cpp b/src/llvm-project/lldb/source/DataFormatters/FormatClasses.cpp index 1c595c3..271963b 100644 --- a/src/llvm-project/lldb/source/DataFormatters/FormatClasses.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/FormatClasses.cpp
@@ -1,10 +1,9 @@ //===-- FormatClasses.cpp ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/DataFormatters/FormatManager.cpp b/src/llvm-project/lldb/source/DataFormatters/FormatManager.cpp index da03c64..dd2808a 100644 --- a/src/llvm-project/lldb/source/DataFormatters/FormatManager.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/FormatManager.cpp
@@ -1,9 +1,8 @@ //===-- FormatManager.cpp ----------------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -147,7 +146,7 @@ const char *FormatManager::GetFormatAsCString(Format format) { if (format >= eFormatDefault && format < kNumFormats) return g_format_infos[format].format_name; - return NULL; + return nullptr; } void FormatManager::EnableAllCategories() { @@ -298,7 +297,7 @@ lldb::TypeFormatImplSP format_current_sp = category_sp->GetFormatForType(type_sp); if (format_current_sp && - (format_chosen_sp.get() == NULL || + (format_chosen_sp.get() == nullptr || (prio_category > category_sp->GetEnabledPosition()))) { prio_category = category_sp->GetEnabledPosition(); format_chosen_sp = format_current_sp; @@ -322,7 +321,7 @@ lldb::TypeSummaryImplSP summary_current_sp = category_sp->GetSummaryForType(type_sp); if (summary_current_sp && - (summary_chosen_sp.get() == NULL || + (summary_chosen_sp.get() == nullptr || (prio_category > category_sp->GetEnabledPosition()))) { prio_category = category_sp->GetEnabledPosition(); summary_chosen_sp = summary_current_sp; @@ -346,7 +345,7 @@ lldb::TypeFilterImplSP filter_current_sp( (TypeFilterImpl *)category_sp->GetFilterForType(type_sp).get()); if (filter_current_sp && - (filter_chosen_sp.get() == NULL || + (filter_chosen_sp.get() == nullptr || (prio_category > category_sp->GetEnabledPosition()))) { prio_category = category_sp->GetEnabledPosition(); filter_chosen_sp = filter_current_sp; @@ -355,7 +354,6 @@ return filter_chosen_sp; } -#ifndef LLDB_DISABLE_PYTHON lldb::ScriptedSyntheticChildrenSP FormatManager::GetSyntheticForType(lldb::TypeNameSpecifierImplSP type_sp) { if (!type_sp) @@ -372,7 +370,7 @@ (ScriptedSyntheticChildren *)category_sp->GetSyntheticForType(type_sp) .get()); if (synth_current_sp && - (synth_chosen_sp.get() == NULL || + (synth_chosen_sp.get() == nullptr || (prio_category > category_sp->GetEnabledPosition()))) { prio_category = category_sp->GetEnabledPosition(); synth_chosen_sp = synth_current_sp; @@ -380,21 +378,6 @@ } return synth_chosen_sp; } -#endif - -#ifndef LLDB_DISABLE_PYTHON -lldb::SyntheticChildrenSP FormatManager::GetSyntheticChildrenForType( - lldb::TypeNameSpecifierImplSP type_sp) { - if (!type_sp) - return lldb::SyntheticChildrenSP(); - lldb::TypeFilterImplSP filter_sp = GetFilterForType(type_sp); - lldb::ScriptedSyntheticChildrenSP synth_sp = GetSyntheticForType(type_sp); - if (filter_sp->GetRevision() > synth_sp->GetRevision()) - return lldb::SyntheticChildrenSP(filter_sp.get()); - else - return lldb::SyntheticChildrenSP(synth_sp.get()); -} -#endif lldb::TypeValidatorImplSP FormatManager::GetValidatorForType(lldb::TypeNameSpecifierImplSP type_sp) { @@ -411,7 +394,7 @@ lldb::TypeValidatorImplSP validator_current_sp( category_sp->GetValidatorForType(type_sp).get()); if (validator_current_sp && - (validator_chosen_sp.get() == NULL || + (validator_chosen_sp.get() == nullptr || (prio_category > category_sp->GetEnabledPosition()))) { prio_category = category_sp->GetEnabledPosition(); validator_chosen_sp = validator_current_sp; @@ -432,7 +415,7 @@ } lldb::TypeCategoryImplSP -FormatManager::GetCategory(const ConstString &category_name, bool can_create) { +FormatManager::GetCategory(ConstString category_name, bool can_create) { if (!category_name) return GetCategory(m_default_category_name); lldb::TypeCategoryImplSP category; @@ -574,7 +557,7 @@ return true; } -ConstString FormatManager::GetValidTypeName(const ConstString &type) { +ConstString FormatManager::GetValidTypeName(ConstString type) { return ::GetValidTypeName_Impl(type); } @@ -781,7 +764,6 @@ return retval; } -#ifndef LLDB_DISABLE_PYTHON lldb::SyntheticChildrenSP FormatManager::GetHardcodedSyntheticChildren(FormattersMatchData &match_data) { SyntheticChildrenSP retval_sp; @@ -860,7 +842,6 @@ m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses()); return retval; } -#endif lldb::TypeValidatorImplSP FormatManager::GetValidator(ValueObject &valobj, @@ -1009,14 +990,12 @@ sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("OSType"), ostype_summary); -#ifndef LLDB_DISABLE_PYTHON TypeFormatImpl::Flags fourchar_flags; fourchar_flags.SetCascades(true).SetSkipPointers(true).SetSkipReferences( true); AddFormat(sys_category_sp, lldb::eFormatOSType, ConstString("FourCharCode"), fourchar_flags); -#endif } void FormatManager::LoadVectorFormatters() {
diff --git a/src/llvm-project/lldb/source/DataFormatters/FormattersHelpers.cpp b/src/llvm-project/lldb/source/DataFormatters/FormattersHelpers.cpp index 1a13215..8f007df 100644 --- a/src/llvm-project/lldb/source/DataFormatters/FormattersHelpers.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/FormattersHelpers.cpp
@@ -1,10 +1,9 @@ //===-- FormattersHelpers.cpp -------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -74,7 +73,6 @@ category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp); } -#ifndef LLDB_DISABLE_PYTHON void lldb_private::formatters::AddCXXSummary( TypeCategoryImpl::SharedPointer category_sp, CXXFunctionSummaryFormat::Callback funct, const char *description, @@ -118,7 +116,6 @@ else category_sp->GetTypeFiltersContainer()->Add(type_name, filter_sp); } -#endif size_t lldb_private::formatters::ExtractIndexFromString(const char *item_name) { if (!item_name || !*item_name) @@ -126,7 +123,7 @@ if (*item_name != '[') return UINT32_MAX; item_name++; - char *endptr = NULL; + char *endptr = nullptr; unsigned long int idx = ::strtoul(item_name, &endptr, 0); if (idx == 0 && endptr == item_name) return UINT32_MAX;
diff --git a/src/llvm-project/lldb/source/DataFormatters/LanguageCategory.cpp b/src/llvm-project/lldb/source/DataFormatters/LanguageCategory.cpp index 4a4b7c5..969b025 100644 --- a/src/llvm-project/lldb/source/DataFormatters/LanguageCategory.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/LanguageCategory.cpp
@@ -1,10 +1,9 @@ //===-- LanguageCategory.cpp ---------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/DataFormatters/StringPrinter.cpp b/src/llvm-project/lldb/source/DataFormatters/StringPrinter.cpp index 6a000f0..27d649b 100644 --- a/src/llvm-project/lldb/source/DataFormatters/StringPrinter.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/StringPrinter.cpp
@@ -1,10 +1,9 @@ //===-- StringPrinter.cpp ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,6 +20,7 @@ #include <ctype.h> #include <locale> +#include <memory> using namespace lldb; using namespace lldb_private; @@ -271,7 +271,7 @@ llvm::ConversionFlags), const StringPrinter::ReadBufferAndDumpToStreamOptions &dump_options) { Stream &stream(*dump_options.GetStream()); - if (dump_options.GetPrefixToken() != 0) + if (dump_options.GetPrefixToken() != nullptr) stream.Printf("%s", dump_options.GetPrefixToken()); if (dump_options.GetQuote() != 0) stream.Printf("%c", dump_options.GetQuote()); @@ -307,7 +307,8 @@ llvm::UTF8 *utf8_data_end_ptr = nullptr; if (ConvertFunction) { - utf8_data_buffer_sp.reset(new DataBufferHeap(4 * bufferSPSize, 0)); + utf8_data_buffer_sp = + std::make_shared<DataBufferHeap>(4 * bufferSPSize, 0); utf8_data_ptr = (llvm::UTF8 *)utf8_data_buffer_sp->GetBytes(); utf8_data_end_ptr = utf8_data_ptr + utf8_data_buffer_sp->GetByteSize(); ConvertFunction(&data_ptr, data_end_ptr, &utf8_data_ptr, @@ -372,7 +373,7 @@ } if (dump_options.GetQuote() != 0) stream.Printf("%c", dump_options.GetQuote()); - if (dump_options.GetSuffixToken() != 0) + if (dump_options.GetSuffixToken() != nullptr) stream.Printf("%s", dump_options.GetSuffixToken()); if (dump_options.GetIsTruncated()) stream.Printf("..."); @@ -448,7 +449,7 @@ const char *prefix_token = options.GetPrefixToken(); char quote = options.GetQuote(); - if (prefix_token != 0) + if (prefix_token != nullptr) options.GetStream()->Printf("%s%c", prefix_token, quote); else if (quote != 0) options.GetStream()->Printf("%c", quote); @@ -496,7 +497,7 @@ const char *suffix_token = options.GetSuffixToken(); - if (suffix_token != 0) + if (suffix_token != nullptr) options.GetStream()->Printf("%c%s", quote, suffix_token); else if (quote != 0) options.GetStream()->Printf("%c", quote);
diff --git a/src/llvm-project/lldb/source/DataFormatters/TypeCategory.cpp b/src/llvm-project/lldb/source/DataFormatters/TypeCategory.cpp index 5740a09..fed2dfb 100644 --- a/src/llvm-project/lldb/source/DataFormatters/TypeCategory.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/TypeCategory.cpp
@@ -1,9 +1,8 @@ //===-- TypeCategory.cpp -----------------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,9 +19,7 @@ : m_format_cont("format", "regex-format", clist), m_summary_cont("summary", "regex-summary", clist), m_filter_cont("filter", "regex-filter", clist), -#ifndef LLDB_DISABLE_PYTHON m_synth_cont("synth", "regex-synth", clist), -#endif m_validator_cont("validator", "regex-validator", clist), m_enabled(false), m_change_listener(clist), m_mutex(), m_name(name), m_languages() { for (const lldb::LanguageType lang : langs) @@ -139,7 +136,6 @@ regex_filter = GetRegexTypeFiltersContainer()->Get(candidates, filter_sp, &reason_filter); -#ifndef LLDB_DISABLE_PYTHON bool regex_synth = false; uint32_t reason_synth = 0; bool pick_synth = false; @@ -170,14 +166,6 @@ entry = filter_sp; return true; } - -#else - if (filter_sp) { - entry = filter_sp; - return true; - } -#endif - return false; } @@ -213,12 +201,10 @@ eFormatCategoryItemRegexFilter) GetRegexTypeFiltersContainer()->Clear(); -#ifndef LLDB_DISABLE_PYTHON if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth) GetTypeSyntheticsContainer()->Clear(); if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth) GetRegexTypeSyntheticsContainer()->Clear(); -#endif if ((items & eFormatCategoryItemValidator) == eFormatCategoryItemValidator) GetTypeValidatorsContainer()->Clear(); @@ -247,12 +233,10 @@ eFormatCategoryItemRegexFilter) success = GetRegexTypeFiltersContainer()->Delete(name) || success; -#ifndef LLDB_DISABLE_PYTHON if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth) success = GetTypeSyntheticsContainer()->Delete(name) || success; if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth) success = GetRegexTypeSyntheticsContainer()->Delete(name) || success; -#endif if ((items & eFormatCategoryItemValidator) == eFormatCategoryItemValidator) success = GetTypeValidatorsContainer()->Delete(name) || success; @@ -283,12 +267,10 @@ eFormatCategoryItemRegexFilter) count += GetRegexTypeFiltersContainer()->GetCount(); -#ifndef LLDB_DISABLE_PYTHON if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth) count += GetTypeSyntheticsContainer()->GetCount(); if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth) count += GetRegexTypeSyntheticsContainer()->GetCount(); -#endif if ((items & eFormatCategoryItemValidator) == eFormatCategoryItemValidator) count += GetTypeValidatorsContainer()->GetCount(); @@ -309,9 +291,7 @@ lldb::TypeFormatImplSP format_sp; lldb::TypeSummaryImplSP summary_sp; TypeFilterImpl::SharedPointer filter_sp; -#ifndef LLDB_DISABLE_PYTHON ScriptedSyntheticChildren::SharedPointer synth_sp; -#endif TypeValidatorImpl::SharedPointer validator_sp; if ((items & eFormatCategoryItemValue) == eFormatCategoryItemValue) { @@ -374,7 +354,6 @@ } } -#ifndef LLDB_DISABLE_PYTHON if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth) { if (GetTypeSyntheticsContainer()->Get(type_name, synth_sp)) { if (matching_category) @@ -394,7 +373,6 @@ return true; } } -#endif if ((items & eFormatCategoryItemValidator) == eFormatCategoryItemValidator) { if (GetTypeValidatorsContainer()->Get(type_name, validator_sp)) { @@ -467,7 +445,6 @@ return retval; } -#ifndef LLDB_DISABLE_PYTHON TypeCategoryImpl::SynthContainer::MapValueType TypeCategoryImpl::GetSyntheticForType(lldb::TypeNameSpecifierImplSP type_sp) { SynthContainer::MapValueType retval; @@ -483,7 +460,6 @@ return retval; } -#endif TypeCategoryImpl::ValidatorContainer::MapValueType TypeCategoryImpl::GetValidatorForType(lldb::TypeNameSpecifierImplSP type_sp) { @@ -555,7 +531,6 @@ index - GetTypeFiltersContainer()->GetCount()); } -#ifndef LLDB_DISABLE_PYTHON TypeCategoryImpl::SynthContainer::MapValueType TypeCategoryImpl::GetSyntheticAtIndex(size_t index) { if (index < GetTypeSyntheticsContainer()->GetCount()) @@ -573,7 +548,6 @@ return GetRegexTypeSyntheticsContainer()->GetTypeNameSpecifierAtIndex( index - GetTypeSyntheticsContainer()->GetCount()); } -#endif TypeCategoryImpl::ValidatorContainer::MapValueType TypeCategoryImpl::GetValidatorAtIndex(size_t index) {
diff --git a/src/llvm-project/lldb/source/DataFormatters/TypeCategoryMap.cpp b/src/llvm-project/lldb/source/DataFormatters/TypeCategoryMap.cpp index 3193f27..69757c9 100644 --- a/src/llvm-project/lldb/source/DataFormatters/TypeCategoryMap.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/TypeCategoryMap.cpp
@@ -1,10 +1,9 @@ //===-- TypeCategoryMap.cpp ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -112,7 +111,7 @@ decltype(sorted_categories)::iterator viter = sorted_categories.begin(), vend = sorted_categories.end(); for (; viter != vend; viter++) - if (viter->get()) + if (*viter) Enable(*viter, Last); } @@ -250,7 +249,6 @@ return lldb::TypeSummaryImplSP(); } -#ifndef LLDB_DISABLE_PYTHON lldb::SyntheticChildrenSP TypeCategoryMap::GetSyntheticChildren(FormattersMatchData &match_data) { std::lock_guard<std::recursive_mutex> guard(m_map_mutex); @@ -292,7 +290,6 @@ "empty SP"); return lldb::SyntheticChildrenSP(); } -#endif lldb::TypeValidatorImplSP TypeCategoryMap::GetValidator(FormattersMatchData &match_data) {
diff --git a/src/llvm-project/lldb/source/DataFormatters/TypeFormat.cpp b/src/llvm-project/lldb/source/DataFormatters/TypeFormat.cpp index f00a679..b526e9a 100644 --- a/src/llvm-project/lldb/source/DataFormatters/TypeFormat.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/TypeFormat.cpp
@@ -1,9 +1,8 @@ //===-- TypeFormat.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -70,7 +69,7 @@ // default value logic if (GetFormat() == eFormatCString) { lldb_private::Flags type_flags(compiler_type.GetTypeInfo( - NULL)); // disambiguate w.r.t. TypeFormatImpl::Flags + nullptr)); // disambiguate w.r.t. TypeFormatImpl::Flags if (type_flags.Test(eTypeIsPointer) && !type_flags.Test(eTypeIsObjC)) { // if we are dumping a pointer as a c-string, get the pointee data
diff --git a/src/llvm-project/lldb/source/DataFormatters/TypeSummary.cpp b/src/llvm-project/lldb/source/DataFormatters/TypeSummary.cpp index 492d3ef..7f6930f 100644 --- a/src/llvm-project/lldb/source/DataFormatters/TypeSummary.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/TypeSummary.cpp
@@ -1,9 +1,8 @@ //===-- TypeSummary.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,16 +29,6 @@ TypeSummaryOptions::TypeSummaryOptions() : m_lang(eLanguageTypeUnknown), m_capping(eTypeSummaryCapped) {} -TypeSummaryOptions::TypeSummaryOptions(const TypeSummaryOptions &rhs) - : m_lang(rhs.m_lang), m_capping(rhs.m_capping) {} - -TypeSummaryOptions &TypeSummaryOptions:: -operator=(const TypeSummaryOptions &rhs) { - m_lang = rhs.m_lang; - m_capping = rhs.m_capping; - return *this; -} - lldb::LanguageType TypeSummaryOptions::GetLanguage() const { return m_lang; } lldb::TypeSummaryCapping TypeSummaryOptions::GetCapping() const { @@ -178,7 +167,7 @@ } ScriptInterpreter *script_interpreter = - target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); + target_sp->GetDebugger().GetScriptInterpreter(); if (!script_interpreter) { retval.assign("error: no ScriptInterpreter");
diff --git a/src/llvm-project/lldb/source/DataFormatters/TypeSynthetic.cpp b/src/llvm-project/lldb/source/DataFormatters/TypeSynthetic.cpp index de46d50..23c80fc 100644 --- a/src/llvm-project/lldb/source/DataFormatters/TypeSynthetic.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/TypeSynthetic.cpp
@@ -1,10 +1,9 @@ //===-- TypeSynthetic.cpp ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -52,7 +51,7 @@ } size_t -TypeFilterImpl::FrontEnd::GetIndexOfChildWithName(const ConstString &name) { +TypeFilterImpl::FrontEnd::GetIndexOfChildWithName(ConstString name) { const char *name_cstr = name.GetCString(); if (name_cstr) { for (size_t i = 0; i < filter->GetCount(); i++) { @@ -126,12 +125,10 @@ return valobj_sp; } -#ifndef LLDB_DISABLE_PYTHON - ScriptedSyntheticChildren::FrontEnd::FrontEnd(std::string pclass, ValueObject &backend) : SyntheticChildrenFrontEnd(backend), m_python_class(pclass), - m_wrapper_sp(), m_interpreter(NULL) { + m_wrapper_sp(), m_interpreter(nullptr) { if (backend == LLDB_INVALID_UID) return; @@ -140,10 +137,9 @@ if (!target_sp) return; - m_interpreter = - target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); + m_interpreter = target_sp->GetDebugger().GetScriptInterpreter(); - if (m_interpreter != NULL) + if (m_interpreter != nullptr) m_wrapper_sp = m_interpreter->CreateSyntheticScriptedProvider( m_python_class.c_str(), backend.GetSP()); } @@ -163,48 +159,48 @@ } size_t ScriptedSyntheticChildren::FrontEnd::CalculateNumChildren() { - if (!m_wrapper_sp || m_interpreter == NULL) + if (!m_wrapper_sp || m_interpreter == nullptr) return 0; return m_interpreter->CalculateNumChildren(m_wrapper_sp, UINT32_MAX); } size_t ScriptedSyntheticChildren::FrontEnd::CalculateNumChildren(uint32_t max) { - if (!m_wrapper_sp || m_interpreter == NULL) + if (!m_wrapper_sp || m_interpreter == nullptr) return 0; return m_interpreter->CalculateNumChildren(m_wrapper_sp, max); } bool ScriptedSyntheticChildren::FrontEnd::Update() { - if (!m_wrapper_sp || m_interpreter == NULL) + if (!m_wrapper_sp || m_interpreter == nullptr) return false; return m_interpreter->UpdateSynthProviderInstance(m_wrapper_sp); } bool ScriptedSyntheticChildren::FrontEnd::MightHaveChildren() { - if (!m_wrapper_sp || m_interpreter == NULL) + if (!m_wrapper_sp || m_interpreter == nullptr) return false; return m_interpreter->MightHaveChildrenSynthProviderInstance(m_wrapper_sp); } size_t ScriptedSyntheticChildren::FrontEnd::GetIndexOfChildWithName( - const ConstString &name) { - if (!m_wrapper_sp || m_interpreter == NULL) + ConstString name) { + if (!m_wrapper_sp || m_interpreter == nullptr) return UINT32_MAX; return m_interpreter->GetIndexOfChildWithName(m_wrapper_sp, name.GetCString()); } lldb::ValueObjectSP ScriptedSyntheticChildren::FrontEnd::GetSyntheticValue() { - if (!m_wrapper_sp || m_interpreter == NULL) + if (!m_wrapper_sp || m_interpreter == nullptr) return nullptr; return m_interpreter->GetSyntheticValue(m_wrapper_sp); } ConstString ScriptedSyntheticChildren::FrontEnd::GetSyntheticTypeName() { - if (!m_wrapper_sp || m_interpreter == NULL) + if (!m_wrapper_sp || m_interpreter == nullptr) return ConstString(); return m_interpreter->GetSyntheticTypeName(m_wrapper_sp); @@ -219,5 +215,3 @@ return sstr.GetString(); } - -#endif // #ifndef LLDB_DISABLE_PYTHON
diff --git a/src/llvm-project/lldb/source/DataFormatters/TypeValidator.cpp b/src/llvm-project/lldb/source/DataFormatters/TypeValidator.cpp index 6769a5a..5ce24ca 100644 --- a/src/llvm-project/lldb/source/DataFormatters/TypeValidator.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/TypeValidator.cpp
@@ -1,9 +1,8 @@ //===-- TypeValidator.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/DataFormatters/ValueObjectPrinter.cpp b/src/llvm-project/lldb/source/DataFormatters/ValueObjectPrinter.cpp index 0821588..409cffe 100644 --- a/src/llvm-project/lldb/source/DataFormatters/ValueObjectPrinter.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/ValueObjectPrinter.cpp
@@ -1,9 +1,8 @@ //===-- ValueObjectPrinter.cpp -----------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -332,7 +331,7 @@ : m_valobj->GetSummaryFormat().get(); if (m_options.m_omit_summary_depth > 0) - entry = NULL; + entry = nullptr; m_summary_formatter.first = entry; m_summary_formatter.second = true; } @@ -416,8 +415,9 @@ // explicitly) TypeSummaryImpl *entry = GetSummaryFormatter(); if (!IsNil() && !IsUninitialized() && !m_value.empty() && - (entry == NULL || (entry->DoesPrintValue(m_valobj) || - m_options.m_format != eFormatDefault) || + (entry == nullptr || + (entry->DoesPrintValue(m_valobj) || + m_options.m_format != eFormatDefault) || m_summary.empty()) && !m_options.m_hide_value) { if (m_options.m_hide_pointer_value &&
diff --git a/src/llvm-project/lldb/source/DataFormatters/VectorType.cpp b/src/llvm-project/lldb/source/DataFormatters/VectorType.cpp index b11fb14..18880f7 100644 --- a/src/llvm-project/lldb/source/DataFormatters/VectorType.cpp +++ b/src/llvm-project/lldb/source/DataFormatters/VectorType.cpp
@@ -1,9 +1,8 @@ //===-- VectorType.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -234,7 +233,7 @@ bool MightHaveChildren() override { return true; } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren())
diff --git a/src/llvm-project/lldb/source/Expression/CMakeLists.txt b/src/llvm-project/lldb/source/Expression/CMakeLists.txt index 020d470..7e2f19e 100644 --- a/src/llvm-project/lldb/source/Expression/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Expression/CMakeLists.txt
@@ -6,10 +6,8 @@ DiagnosticManager.cpp DWARFExpression.cpp Expression.cpp - ExpressionSourceCode.cpp ExpressionVariable.cpp FunctionCaller.cpp - IRDynamicChecks.cpp IRExecutionUnit.cpp IRInterpreter.cpp IRMemoryMap.cpp @@ -29,7 +27,7 @@ lldbSymbol lldbTarget lldbUtility - lldbPluginExpressionParserClang + lldbPluginCPlusPlusLanguage lldbPluginObjectFileJIT LINK_COMPONENTS
diff --git a/src/llvm-project/lldb/source/Expression/DWARFExpression.cpp b/src/llvm-project/lldb/source/Expression/DWARFExpression.cpp index a6249b3..a9d3653 100644 --- a/src/llvm-project/lldb/source/Expression/DWARFExpression.cpp +++ b/src/llvm-project/lldb/source/Expression/DWARFExpression.cpp
@@ -1,9 +1,8 @@ //===-- DWARFExpression.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -47,25 +46,20 @@ uint32_t index_size = dwarf_cu->GetAddressByteSize(); dw_offset_t addr_base = dwarf_cu->GetAddrBase(); lldb::offset_t offset = addr_base + index * index_size; - return dwarf_cu->GetSymbolFileDWARF()->get_debug_addr_data().GetMaxU64( - &offset, index_size); + return dwarf_cu->GetSymbolFileDWARF() + .GetDWARFContext() + .getOrLoadAddrData() + .GetMaxU64(&offset, index_size); } -//---------------------------------------------------------------------- // DWARFExpression constructor -//---------------------------------------------------------------------- -DWARFExpression::DWARFExpression(DWARFUnit *dwarf_cu) - : m_module_wp(), m_data(), m_dwarf_cu(dwarf_cu), +DWARFExpression::DWARFExpression() + : m_module_wp(), m_data(), m_dwarf_cu(nullptr), m_reg_kind(eRegisterKindDWARF), m_loclist_slide(LLDB_INVALID_ADDRESS) {} -DWARFExpression::DWARFExpression(const DWARFExpression &rhs) - : m_module_wp(rhs.m_module_wp), m_data(rhs.m_data), - m_dwarf_cu(rhs.m_dwarf_cu), m_reg_kind(rhs.m_reg_kind), - m_loclist_slide(rhs.m_loclist_slide) {} - DWARFExpression::DWARFExpression(lldb::ModuleSP module_sp, const DataExtractor &data, - DWARFUnit *dwarf_cu, + const DWARFUnit *dwarf_cu, lldb::offset_t data_offset, lldb::offset_t data_length) : m_module_wp(), m_data(data, data_offset, data_length), @@ -75,58 +69,21 @@ m_module_wp = module_sp; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- DWARFExpression::~DWARFExpression() {} bool DWARFExpression::IsValid() const { return m_data.GetByteSize() > 0; } -void DWARFExpression::SetOpcodeData(const DataExtractor &data) { - m_data = data; -} +void DWARFExpression::UpdateValue(uint64_t const_value, + lldb::offset_t const_value_byte_size, + uint8_t addr_byte_size) { + if (!const_value_byte_size) + return; -void DWARFExpression::CopyOpcodeData(lldb::ModuleSP module_sp, - const DataExtractor &data, - lldb::offset_t data_offset, - lldb::offset_t data_length) { - const uint8_t *bytes = data.PeekData(data_offset, data_length); - if (bytes) { - m_module_wp = module_sp; - m_data.SetData(DataBufferSP(new DataBufferHeap(bytes, data_length))); - m_data.SetByteOrder(data.GetByteOrder()); - m_data.SetAddressByteSize(data.GetAddressByteSize()); - } -} - -void DWARFExpression::CopyOpcodeData(const void *data, - lldb::offset_t data_length, - ByteOrder byte_order, - uint8_t addr_byte_size) { - if (data && data_length) { - m_data.SetData(DataBufferSP(new DataBufferHeap(data, data_length))); - m_data.SetByteOrder(byte_order); - m_data.SetAddressByteSize(addr_byte_size); - } -} - -void DWARFExpression::CopyOpcodeData(uint64_t const_value, - lldb::offset_t const_value_byte_size, - uint8_t addr_byte_size) { - if (const_value_byte_size) { - m_data.SetData( - DataBufferSP(new DataBufferHeap(&const_value, const_value_byte_size))); - m_data.SetByteOrder(endian::InlHostByteOrder()); - m_data.SetAddressByteSize(addr_byte_size); - } -} - -void DWARFExpression::SetOpcodeData(lldb::ModuleSP module_sp, - const DataExtractor &data, - lldb::offset_t data_offset, - lldb::offset_t data_length) { - m_module_wp = module_sp; - m_data.SetData(data, data_offset, data_length); + m_data.SetData( + DataBufferSP(new DataBufferHeap(&const_value, const_value_byte_size))); + m_data.SetByteOrder(endian::InlHostByteOrder()); + m_data.SetAddressByteSize(addr_byte_size); } void DWARFExpression::DumpLocation(Stream *s, lldb::offset_t offset, @@ -491,23 +448,6 @@ case DW_OP_call_ref: // 0x9a DWARF3 1 4- or 8-byte offset of DIE s->Printf("DW_OP_call_ref(0x%8.8" PRIx64 ")", m_data.GetAddress(&offset)); break; - // case DW_OP_call_frame_cfa: s << "call_frame_cfa"; break; - // // 0x9c DWARF3 - // case DW_OP_bit_piece: // 0x9d DWARF3 2 - // s->Printf("DW_OP_bit_piece(0x%x, 0x%x)", - // m_data.GetULEB128(&offset), m_data.GetULEB128(&offset)); - // break; - // case DW_OP_lo_user: s->PutCString("DW_OP_lo_user"); break; - // // 0xe0 - // case DW_OP_hi_user: s->PutCString("DW_OP_hi_user"); break; - // // 0xff - // case DW_OP_APPLE_extern: - // s->Printf("DW_OP_APPLE_extern(%" PRIu64 ")", - // m_data.GetULEB128(&offset)); - // break; - // case DW_OP_APPLE_array_ref: - // s->PutCString("DW_OP_APPLE_array_ref"); - // break; case DW_OP_form_tls_address: s->PutCString("DW_OP_form_tls_address"); // 0x9b break; @@ -515,6 +455,10 @@ s->Printf("DW_OP_GNU_addr_index(0x%" PRIx64 ")", m_data.GetULEB128(&offset)); break; + case DW_OP_addrx: + s->Printf("DW_OP_addrx(0x%" PRIx64 ")", + m_data.GetULEB128(&offset)); + break; case DW_OP_GNU_const_index: // 0xfc s->Printf("DW_OP_GNU_const_index(0x%" PRIx64 ")", m_data.GetULEB128(&offset)); @@ -525,62 +469,6 @@ case DW_OP_APPLE_uninit: s->PutCString("DW_OP_APPLE_uninit"); // 0xF0 break; - // case DW_OP_APPLE_assign: // 0xF1 - pops value off and - // assigns it to second item on stack (2nd item must have - // assignable context) - // s->PutCString("DW_OP_APPLE_assign"); - // break; - // case DW_OP_APPLE_address_of: // 0xF2 - gets the address of - // the top stack item (top item must be a variable, or have - // value_type that is an address already) - // s->PutCString("DW_OP_APPLE_address_of"); - // break; - // case DW_OP_APPLE_value_of: // 0xF3 - pops the value off the - // stack and pushes the value of that object (top item must be a - // variable, or expression local) - // s->PutCString("DW_OP_APPLE_value_of"); - // break; - // case DW_OP_APPLE_deref_type: // 0xF4 - gets the address of - // the top stack item (top item must be a variable, or a clang - // type) - // s->PutCString("DW_OP_APPLE_deref_type"); - // break; - // case DW_OP_APPLE_expr_local: // 0xF5 - ULEB128 expression - // local index - // s->Printf("DW_OP_APPLE_expr_local(%" PRIu64 ")", - // m_data.GetULEB128(&offset)); - // break; - // case DW_OP_APPLE_constf: // 0xF6 - 1 byte float size, - // followed by constant float data - // { - // uint8_t float_length = m_data.GetU8(&offset); - // s->Printf("DW_OP_APPLE_constf(<%u> ", float_length); - // m_data.Dump(s, offset, eFormatHex, float_length, 1, - // UINT32_MAX, DW_INVALID_ADDRESS, 0, 0); - // s->PutChar(')'); - // // Consume the float data - // m_data.GetData(&offset, float_length); - // } - // break; - // case DW_OP_APPLE_scalar_cast: - // s->Printf("DW_OP_APPLE_scalar_cast(%s)", - // Scalar::GetValueTypeAsCString - // ((Scalar::Type)m_data.GetU8(&offset))); - // break; - // case DW_OP_APPLE_clang_cast: - // { - // clang::Type *clang_type = (clang::Type - // *)m_data.GetMaxU64(&offset, sizeof(void*)); - // s->Printf("DW_OP_APPLE_clang_cast(%p)", clang_type); - // } - // break; - // case DW_OP_APPLE_clear: - // s->PutCString("DW_OP_APPLE_clear"); - // break; - // case DW_OP_APPLE_error: // 0xFF - Stops expression - // evaluation and returns an error (no args) - // s->PutCString("DW_OP_APPLE_error"); - // break; } } } @@ -653,7 +541,7 @@ lldb::RegisterKind reg_kind, uint32_t reg_num, Status *error_ptr, Value &value) { - if (reg_ctx == NULL) { + if (reg_ctx == nullptr) { if (error_ptr) error_ptr->SetErrorStringWithFormat("No register context in frame.\n"); } else { @@ -695,52 +583,6 @@ return false; } -// bool -// DWARFExpression::LocationListContainsLoadAddress (Process* process, const -// Address &addr) const -//{ -// return LocationListContainsLoadAddress(process, -// addr.GetLoadAddress(process)); -//} -// -// bool -// DWARFExpression::LocationListContainsLoadAddress (Process* process, addr_t -// load_addr) const -//{ -// if (load_addr == LLDB_INVALID_ADDRESS) -// return false; -// -// if (IsLocationList()) -// { -// lldb::offset_t offset = 0; -// -// addr_t loc_list_base_addr = m_loclist_slide.GetLoadAddress(process); -// -// if (loc_list_base_addr == LLDB_INVALID_ADDRESS) -// return false; -// -// while (m_data.ValidOffset(offset)) -// { -// // We need to figure out what the value is for the location. -// addr_t lo_pc = m_data.GetAddress(&offset); -// addr_t hi_pc = m_data.GetAddress(&offset); -// if (lo_pc == 0 && hi_pc == 0) -// break; -// else -// { -// lo_pc += loc_list_base_addr; -// hi_pc += loc_list_base_addr; -// -// if (lo_pc <= load_addr && load_addr < hi_pc) -// return true; -// -// offset += m_data.GetU16(&offset); -// } -// } -// } -// return false; -//} - static offset_t GetOpcodeDataSize(const DataExtractor &data, const lldb::offset_t data_offset, const uint8_t op) { @@ -878,6 +720,7 @@ return 8; // All opcodes that have a single ULEB (signed or unsigned) argument + case DW_OP_addrx: // 0xa1 1 ULEB128 index case DW_OP_constu: // 0x10 1 ULEB128 constant case DW_OP_consts: // 0x11 1 SLEB128 constant case DW_OP_plus_uconst: // 0x23 1 ULEB128 addend @@ -958,7 +801,7 @@ return op_file_addr; else ++curr_op_addr_idx; - } else if (op == DW_OP_GNU_addr_index) { + } else if (op == DW_OP_GNU_addr_index || op == DW_OP_addrx) { uint64_t index = m_data.GetULEB128(&offset); if (curr_op_addr_idx == op_addr_idx) { if (!m_dwarf_cu) { @@ -996,12 +839,12 @@ // for this expression // So first we copy the data into a heap buffer - std::unique_ptr<DataBufferHeap> head_data_ap( + std::unique_ptr<DataBufferHeap> head_data_up( new DataBufferHeap(m_data.GetDataStart(), m_data.GetByteSize())); // Make en encoder so we can write the address into the buffer using the // correct byte order (endianness) - DataEncoder encoder(head_data_ap->GetBytes(), head_data_ap->GetByteSize(), + DataEncoder encoder(head_data_up->GetBytes(), head_data_up->GetByteSize(), m_data.GetByteOrder(), addr_byte_size); // Replace the address in the new buffer @@ -1010,7 +853,7 @@ // All went well, so now we can reset the data using a shared pointer to // the heap data so "m_data" will now correctly manage the heap data. - m_data.SetData(DataBufferSP(head_data_ap.release())); + m_data.SetData(DataBufferSP(head_data_up.release())); return true; } else { const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op); @@ -1252,7 +1095,7 @@ if (IsLocationList()) { lldb::offset_t offset = 0; addr_t pc; - StackFrame *frame = NULL; + StackFrame *frame = nullptr; if (reg_ctx) pc = reg_ctx->GetPC(); else { @@ -1313,7 +1156,7 @@ bool DWARFExpression::Evaluate( ExecutionContext *exe_ctx, RegisterContext *reg_ctx, lldb::ModuleSP module_sp, const DataExtractor &opcodes, - DWARFUnit *dwarf_cu, const lldb::offset_t opcodes_offset, + const DWARFUnit *dwarf_cu, const lldb::offset_t opcodes_offset, const lldb::offset_t opcodes_length, const lldb::RegisterKind reg_kind, const Value *initial_value_ptr, const Value *object_address_ptr, Value &result, Status *error_ptr) { @@ -1326,14 +1169,14 @@ } std::vector<Value> stack; - Process *process = NULL; - StackFrame *frame = NULL; + Process *process = nullptr; + StackFrame *frame = nullptr; if (exe_ctx) { process = exe_ctx->GetProcessPtr(); frame = exe_ctx->GetFramePtr(); } - if (reg_ctx == NULL && frame) + if (reg_ctx == nullptr && frame) reg_ctx = frame->GetRegisterContext().get(); if (initial_value_ptr) @@ -1375,10 +1218,8 @@ } switch (op) { - //---------------------------------------------------------------------- // The DW_OP_addr operation has a single operand that encodes a machine // address and whose size is the size of an address on the target machine. - //---------------------------------------------------------------------- case DW_OP_addr: stack.push_back(Scalar(opcodes.GetAddress(&offset))); stack.back().SetValueType(Value::eValueTypeFileAddress); @@ -1389,7 +1230,6 @@ frame->CalculateTarget().get()); break; - //---------------------------------------------------------------------- // The DW_OP_addr_sect_offset4 is used for any location expressions in // shared libraries that have a location like: // DW_OP_addr(0x1000) @@ -1398,7 +1238,6 @@ // process where shared libraries have been slid. To account for this, this // new address type where we can store the section pointer and a 4 byte // offset. - //---------------------------------------------------------------------- // case DW_OP_addr_sect_offset4: // { // result_type = eResultTypeFileAddress; @@ -1428,14 +1267,12 @@ // } // break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_deref // OPERANDS: none // DESCRIPTION: Pops the top stack entry and treats it as an address. // The value retrieved from that address is pushed. The size of the data // retrieved from the dereferenced address is the size of an address on the // target machine. - //---------------------------------------------------------------------- case DW_OP_deref: { if (stack.empty()) { if (error_ptr) @@ -1517,7 +1354,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_deref_size // OPERANDS: 1 // 1 - uint8_t that specifies the size of the data to dereference. @@ -1530,7 +1366,6 @@ // address on the target machine. The data retrieved is zero extended to // the size of an address on the target machine before being pushed on the // expression stack. - //---------------------------------------------------------------------- case DW_OP_deref_size: { if (stack.empty()) { if (error_ptr) @@ -1639,7 +1474,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_xderef_size // OPERANDS: 1 // 1 - uint8_t that specifies the size of the data to dereference. @@ -1655,12 +1489,10 @@ // the size of an address on the target machine. The data retrieved is zero // extended to the size of an address on the target machine before being // pushed on the expression stack. - //---------------------------------------------------------------------- case DW_OP_xderef_size: if (error_ptr) error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef_size."); return false; - //---------------------------------------------------------------------- // OPCODE: DW_OP_xderef // OPERANDS: none // DESCRIPTION: Provides an extended dereference mechanism. The entry at @@ -1671,17 +1503,14 @@ // calculation and pushed as the new stack top. The size of the data // retrieved from the dereferenced address is the size of an address on the // target machine. - //---------------------------------------------------------------------- case DW_OP_xderef: if (error_ptr) error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef."); return false; - //---------------------------------------------------------------------- // All DW_OP_constXXX opcodes have a single operand as noted below: // // Opcode Operand 1 - // --------------- ---------------------------------------------------- // DW_OP_const1u 1-byte unsigned integer constant DW_OP_const1s // 1-byte signed integer constant DW_OP_const2u 2-byte unsigned integer // constant DW_OP_const2s 2-byte signed integer constant DW_OP_const4u @@ -1689,7 +1518,6 @@ // constant DW_OP_const8u 8-byte unsigned integer constant DW_OP_const8s // 8-byte signed integer constant DW_OP_constu unsigned LEB128 integer // constant DW_OP_consts signed LEB128 integer constant - //---------------------------------------------------------------------- case DW_OP_const1u: stack.push_back(Scalar((uint8_t)opcodes.GetU8(&offset))); break; @@ -1721,11 +1549,9 @@ stack.push_back(Scalar(opcodes.GetSLEB128(&offset))); break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_dup // OPERANDS: none // DESCRIPTION: duplicates the value at the top of the stack - //---------------------------------------------------------------------- case DW_OP_dup: if (stack.empty()) { if (error_ptr) @@ -1735,11 +1561,9 @@ stack.push_back(stack.back()); break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_drop // OPERANDS: none // DESCRIPTION: pops the value at the top of the stack - //---------------------------------------------------------------------- case DW_OP_drop: if (stack.empty()) { if (error_ptr) @@ -1749,12 +1573,10 @@ stack.pop_back(); break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_over // OPERANDS: none // DESCRIPTION: Duplicates the entry currently second in the stack at // the top of the stack. - //---------------------------------------------------------------------- case DW_OP_over: if (stack.size() < 2) { if (error_ptr) @@ -1765,16 +1587,14 @@ stack.push_back(stack[stack.size() - 2]); break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_pick // OPERANDS: uint8_t index into the current stack // DESCRIPTION: The stack entry with the specified index (0 through 255, // inclusive) is pushed on the stack - //---------------------------------------------------------------------- case DW_OP_pick: { uint8_t pick_idx = opcodes.GetU8(&offset); if (pick_idx < stack.size()) - stack.push_back(stack[pick_idx]); + stack.push_back(stack[stack.size() - 1 - pick_idx]); else { if (error_ptr) error_ptr->SetErrorStringWithFormat( @@ -1783,13 +1603,11 @@ } } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_swap // OPERANDS: none // DESCRIPTION: swaps the top two stack entries. The entry at the top // of the stack becomes the second stack entry, and the second entry // becomes the top of the stack - //---------------------------------------------------------------------- case DW_OP_swap: if (stack.size() < 2) { if (error_ptr) @@ -1803,14 +1621,12 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_rot // OPERANDS: none // DESCRIPTION: Rotates the first three stack entries. The entry at // the top of the stack becomes the third stack entry, the second entry // becomes the top of the stack, and the third entry becomes the second // entry. - //---------------------------------------------------------------------- case DW_OP_rot: if (stack.size() < 3) { if (error_ptr) @@ -1826,13 +1642,11 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_abs // OPERANDS: none // DESCRIPTION: pops the top stack entry, interprets it as a signed // value and pushes its absolute value. If the absolute value can not be // represented, the result is undefined. - //---------------------------------------------------------------------- case DW_OP_abs: if (stack.empty()) { if (error_ptr) @@ -1847,12 +1661,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_and // OPERANDS: none // DESCRIPTION: pops the top two stack values, performs a bitwise and // operation on the two, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_and: if (stack.size() < 2) { if (error_ptr) @@ -1867,13 +1679,11 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_div // OPERANDS: none // DESCRIPTION: pops the top two stack values, divides the former second // entry by the former top of the stack using signed division, and pushes // the result. - //---------------------------------------------------------------------- case DW_OP_div: if (stack.size() < 2) { if (error_ptr) @@ -1899,12 +1709,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_minus // OPERANDS: none // DESCRIPTION: pops the top two stack values, subtracts the former top // of the stack from the former second entry, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_minus: if (stack.size() < 2) { if (error_ptr) @@ -1919,13 +1727,11 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_mod // OPERANDS: none // DESCRIPTION: pops the top two stack values and pushes the result of // the calculation: former second stack entry modulo the former top of the // stack. - //---------------------------------------------------------------------- case DW_OP_mod: if (stack.size() < 2) { if (error_ptr) @@ -1940,12 +1746,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_mul // OPERANDS: none // DESCRIPTION: pops the top two stack entries, multiplies them // together, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_mul: if (stack.size() < 2) { if (error_ptr) @@ -1960,11 +1764,9 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_neg // OPERANDS: none // DESCRIPTION: pops the top stack entry, and pushes its negation. - //---------------------------------------------------------------------- case DW_OP_neg: if (stack.empty()) { if (error_ptr) @@ -1980,12 +1782,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_not // OPERANDS: none // DESCRIPTION: pops the top stack entry, and pushes its bitwise // complement - //---------------------------------------------------------------------- case DW_OP_not: if (stack.empty()) { if (error_ptr) @@ -2001,12 +1801,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_or // OPERANDS: none // DESCRIPTION: pops the top two stack entries, performs a bitwise or // operation on the two, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_or: if (stack.size() < 2) { if (error_ptr) @@ -2021,12 +1819,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_plus // OPERANDS: none // DESCRIPTION: pops the top two stack entries, adds them together, and // pushes the result. - //---------------------------------------------------------------------- case DW_OP_plus: if (stack.size() < 2) { if (error_ptr) @@ -2040,12 +1836,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_plus_uconst // OPERANDS: none // DESCRIPTION: pops the top stack entry, adds it to the unsigned LEB128 // constant operand and pushes the result. - //---------------------------------------------------------------------- case DW_OP_plus_uconst: if (stack.empty()) { if (error_ptr) @@ -2064,13 +1858,11 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_shl // OPERANDS: none // DESCRIPTION: pops the top two stack entries, shifts the former // second entry left by the number of bits specified by the former top of // the stack, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_shl: if (stack.size() < 2) { if (error_ptr) @@ -2084,13 +1876,11 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_shr // OPERANDS: none // DESCRIPTION: pops the top two stack entries, shifts the former second // entry right logically (filling with zero bits) by the number of bits // specified by the former top of the stack, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_shr: if (stack.size() < 2) { if (error_ptr) @@ -2109,14 +1899,12 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_shra // OPERANDS: none // DESCRIPTION: pops the top two stack entries, shifts the former second // entry right arithmetically (divide the magnitude by 2, keep the same // sign for the result) by the number of bits specified by the former top // of the stack, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_shra: if (stack.size() < 2) { if (error_ptr) @@ -2130,12 +1918,10 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_xor // OPERANDS: none // DESCRIPTION: pops the top two stack entries, performs the bitwise // exclusive-or operation on the two, and pushes the result. - //---------------------------------------------------------------------- case DW_OP_xor: if (stack.size() < 2) { if (error_ptr) @@ -2150,14 +1936,12 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_skip // OPERANDS: int16_t // DESCRIPTION: An unconditional branch. Its single operand is a 2-byte // signed integer constant. The 2-byte constant is the number of bytes of // the DWARF expression to skip forward or backward from the current // operation, beginning after the 2-byte constant. - //---------------------------------------------------------------------- case DW_OP_skip: { int16_t skip_offset = (int16_t)opcodes.GetU16(&offset); lldb::offset_t new_offset = offset + skip_offset; @@ -2170,7 +1954,6 @@ } } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_bra // OPERANDS: int16_t // DESCRIPTION: A conditional branch. Its single operand is a 2-byte @@ -2178,7 +1961,6 @@ // value popped is not the constant 0, the 2-byte constant operand is the // number of bytes of the DWARF expression to skip forward or backward from // the current operation, beginning after the 2-byte constant. - //---------------------------------------------------------------------- case DW_OP_bra: if (stack.empty()) { if (error_ptr) @@ -2203,7 +1985,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_eq // OPERANDS: none // DESCRIPTION: pops the top two stack values, compares using the @@ -2211,7 +1992,6 @@ // STACK RESULT: push the constant value 1 onto the stack if the result // of the operation is true or the constant value 0 if the result of the // operation is false. - //---------------------------------------------------------------------- case DW_OP_eq: if (stack.size() < 2) { if (error_ptr) @@ -2226,7 +2006,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_ge // OPERANDS: none // DESCRIPTION: pops the top two stack values, compares using the @@ -2234,7 +2013,6 @@ // STACK RESULT: push the constant value 1 onto the stack if the result // of the operation is true or the constant value 0 if the result of the // operation is false. - //---------------------------------------------------------------------- case DW_OP_ge: if (stack.size() < 2) { if (error_ptr) @@ -2249,7 +2027,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_gt // OPERANDS: none // DESCRIPTION: pops the top two stack values, compares using the @@ -2257,7 +2034,6 @@ // STACK RESULT: push the constant value 1 onto the stack if the result // of the operation is true or the constant value 0 if the result of the // operation is false. - //---------------------------------------------------------------------- case DW_OP_gt: if (stack.size() < 2) { if (error_ptr) @@ -2272,7 +2048,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_le // OPERANDS: none // DESCRIPTION: pops the top two stack values, compares using the @@ -2280,7 +2055,6 @@ // STACK RESULT: push the constant value 1 onto the stack if the result // of the operation is true or the constant value 0 if the result of the // operation is false. - //---------------------------------------------------------------------- case DW_OP_le: if (stack.size() < 2) { if (error_ptr) @@ -2295,7 +2069,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_lt // OPERANDS: none // DESCRIPTION: pops the top two stack values, compares using the @@ -2303,7 +2076,6 @@ // STACK RESULT: push the constant value 1 onto the stack if the result // of the operation is true or the constant value 0 if the result of the // operation is false. - //---------------------------------------------------------------------- case DW_OP_lt: if (stack.size() < 2) { if (error_ptr) @@ -2318,7 +2090,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_ne // OPERANDS: none // DESCRIPTION: pops the top two stack values, compares using the @@ -2326,7 +2097,6 @@ // STACK RESULT: push the constant value 1 onto the stack if the result // of the operation is true or the constant value 0 if the result of the // operation is false. - //---------------------------------------------------------------------- case DW_OP_ne: if (stack.size() < 2) { if (error_ptr) @@ -2341,13 +2111,11 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_litn // OPERANDS: none // DESCRIPTION: encode the unsigned literal values from 0 through 31. // STACK RESULT: push the unsigned literal constant value onto the top // of the stack. - //---------------------------------------------------------------------- case DW_OP_lit0: case DW_OP_lit1: case DW_OP_lit2: @@ -2383,11 +2151,9 @@ stack.push_back(Scalar((uint64_t)(op - DW_OP_lit0))); break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_regN // OPERANDS: none // DESCRIPTION: Push the value in register n on the top of the stack. - //---------------------------------------------------------------------- case DW_OP_reg0: case DW_OP_reg1: case DW_OP_reg2: @@ -2427,12 +2193,10 @@ else return false; } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_regx // OPERANDS: // ULEB128 literal operand that encodes the register. // DESCRIPTION: Push the value in register on the top of the stack. - //---------------------------------------------------------------------- case DW_OP_regx: { reg_num = opcodes.GetULEB128(&offset); if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr, tmp)) @@ -2441,13 +2205,11 @@ return false; } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_bregN // OPERANDS: // SLEB128 offset from register N // DESCRIPTION: Value is in memory at the address specified by register // N plus an offset. - //---------------------------------------------------------------------- case DW_OP_breg0: case DW_OP_breg1: case DW_OP_breg2: @@ -2492,14 +2254,12 @@ } else return false; } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_bregx // OPERANDS: 2 // ULEB128 literal operand that encodes the register. // SLEB128 offset from register N // DESCRIPTION: Value is in memory at the address specified by register // N plus an offset. - //---------------------------------------------------------------------- case DW_OP_bregx: { reg_num = opcodes.GetULEB128(&offset); @@ -2540,16 +2300,13 @@ break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_nop // OPERANDS: none // DESCRIPTION: A place holder. It has no effect on the location stack // or any of its values. - //---------------------------------------------------------------------- case DW_OP_nop: break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_piece // OPERANDS: 1 // ULEB128: byte size of the piece @@ -2563,7 +2320,6 @@ // variable partially in memory and partially in registers. DW_OP_piece // provides a way of describing how large a part of a variable a particular // DWARF expression refers to. - //---------------------------------------------------------------------- case DW_OP_piece: { const uint64_t piece_byte_size = opcodes.GetULEB128(&offset); @@ -2740,7 +2496,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_push_object_address // OPERANDS: none // DESCRIPTION: Pushes the address of the object currently being @@ -2749,7 +2504,6 @@ // DIE or it may be a component of an array, structure, or class whose // address has been dynamically determined by an earlier step during user // expression evaluation. - //---------------------------------------------------------------------- case DW_OP_push_object_address: if (object_address_ptr) stack.push_back(*object_address_ptr); @@ -2761,7 +2515,6 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_call2 // OPERANDS: // uint16_t compile unit relative offset of a DIE @@ -2780,12 +2533,10 @@ // may be used as parameters by the called expression and values left on // the stack by the called expression may be used as return values by prior // agreement between the calling and called expressions. - //---------------------------------------------------------------------- case DW_OP_call2: if (error_ptr) error_ptr->SetErrorString("Unimplemented opcode DW_OP_call2."); return false; - //---------------------------------------------------------------------- // OPCODE: DW_OP_call4 // OPERANDS: 1 // uint32_t compile unit relative offset of a DIE @@ -2805,30 +2556,25 @@ // may be used as parameters by the called expression and values left on // the stack by the called expression may be used as return values by prior // agreement between the calling and called expressions. - //---------------------------------------------------------------------- case DW_OP_call4: if (error_ptr) error_ptr->SetErrorString("Unimplemented opcode DW_OP_call4."); return false; - //---------------------------------------------------------------------- // OPCODE: DW_OP_stack_value // OPERANDS: None // DESCRIPTION: Specifies that the object does not exist in memory but // rather is a constant value. The value from the top of the stack is the // value to be used. This is the actual object value and not the location. - //---------------------------------------------------------------------- case DW_OP_stack_value: stack.back().SetValueType(Value::eValueTypeScalar); break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_call_frame_cfa // OPERANDS: None // DESCRIPTION: Specifies a DWARF expression that pushes the value of // the canonical frame address consistent with the call frame information // located in .debug_frame (or in the FDEs of the eh_frame section). - //---------------------------------------------------------------------- case DW_OP_call_frame_cfa: if (frame) { // Note that we don't have to parse FDEs because this DWARF expression @@ -2850,14 +2596,12 @@ } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_form_tls_address (or the old pre-DWARFv3 vendor extension // opcode, DW_OP_GNU_push_tls_address) // OPERANDS: none // DESCRIPTION: Pops a TLS offset from the stack, converts it to // an address in the current thread's thread-local storage block, and // pushes it on the stack. - //---------------------------------------------------------------------- case DW_OP_form_tls_address: case DW_OP_GNU_push_tls_address: { if (stack.size() < 1) { @@ -2902,14 +2646,13 @@ stack.back().SetValueType(Value::eValueTypeLoadAddress); } break; - //---------------------------------------------------------------------- - // OPCODE: DW_OP_GNU_addr_index + // OPCODE: DW_OP_addrx (DW_OP_GNU_addr_index is the legacy name.) // OPERANDS: 1 // ULEB128: index to the .debug_addr section // DESCRIPTION: Pushes an address to the stack from the .debug_addr // section with the base address specified by the DW_AT_addr_base attribute // and the 0 based index is the ULEB128 encoded index. - //---------------------------------------------------------------------- + case DW_OP_addrx: case DW_OP_GNU_addr_index: { if (!dwarf_cu) { if (error_ptr) @@ -2918,17 +2661,11 @@ return false; } uint64_t index = opcodes.GetULEB128(&offset); - uint32_t index_size = dwarf_cu->GetAddressByteSize(); - dw_offset_t addr_base = dwarf_cu->GetAddrBase(); - lldb::offset_t offset = addr_base + index * index_size; - uint64_t value = - dwarf_cu->GetSymbolFileDWARF()->get_debug_addr_data().GetMaxU64( - &offset, index_size); + lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index); stack.push_back(Scalar(value)); stack.back().SetValueType(Value::eValueTypeFileAddress); } break; - //---------------------------------------------------------------------- // OPCODE: DW_OP_GNU_const_index // OPERANDS: 1 // ULEB128: index to the .debug_addr section @@ -2936,7 +2673,6 @@ // the stack from the .debug_addr section with the base address specified // by the DW_AT_addr_base attribute and the 0 based index is the ULEB128 // encoded index. - //---------------------------------------------------------------------- case DW_OP_GNU_const_index: { if (!dwarf_cu) { if (error_ptr) @@ -2945,22 +2681,8 @@ return false; } uint64_t index = opcodes.GetULEB128(&offset); - uint32_t index_size = dwarf_cu->GetAddressByteSize(); - dw_offset_t addr_base = dwarf_cu->GetAddrBase(); - lldb::offset_t offset = addr_base + index * index_size; - const DWARFDataExtractor &debug_addr = - dwarf_cu->GetSymbolFileDWARF()->get_debug_addr_data(); - switch (index_size) { - case 4: - stack.push_back(Scalar(debug_addr.GetU32(&offset))); - break; - case 8: - stack.push_back(Scalar(debug_addr.GetU64(&offset))); - break; - default: - assert(false && "Unhandled index size"); - return false; - } + lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index); + stack.push_back(Scalar(value)); } break; default: @@ -3028,7 +2750,7 @@ return false; DWARFExpression::LocationListFormat format = - dwarf_cu->GetSymbolFileDWARF()->GetLocationListFormat(); + dwarf_cu->GetSymbolFileDWARF().GetLocationListFormat(); switch (format) { case NonLocationList: return false; @@ -3195,6 +2917,7 @@ case DW_OP_call_ref: size = dwarf_ref_size; break; + case DW_OP_addrx: case DW_OP_piece: case DW_OP_plus_uconst: case DW_OP_regx: @@ -3204,7 +2927,7 @@ break; default: s.Printf("UNKNOWN ONE-OPERAND OPCODE, #%u", opcode); - return true; + return false; } switch (size) { @@ -3250,7 +2973,7 @@ break; } - return false; + return true; } bool DWARFExpression::PrintDWARFExpression(Stream &s, const DataExtractor &data, @@ -3289,7 +3012,7 @@ s.Indent(); if (cu) s.AddressRange(start_addr + base_addr, end_addr + base_addr, - cu->GetAddressByteSize(), NULL, ": "); + cu->GetAddressByteSize(), nullptr, ": "); uint32_t loc_length = debug_loc_data.GetU16(&offset); DataExtractor locationData(debug_loc_data, offset, loc_length);
diff --git a/src/llvm-project/lldb/source/Expression/DiagnosticManager.cpp b/src/llvm-project/lldb/source/Expression/DiagnosticManager.cpp index a98d303..53d85f8 100644 --- a/src/llvm-project/lldb/source/Expression/DiagnosticManager.cpp +++ b/src/llvm-project/lldb/source/Expression/DiagnosticManager.cpp
@@ -1,9 +1,8 @@ //===-- DiagnosticManager.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Expression/Expression.cpp b/src/llvm-project/lldb/source/Expression/Expression.cpp index 285079a..8e1ef69 100644 --- a/src/llvm-project/lldb/source/Expression/Expression.cpp +++ b/src/llvm-project/lldb/source/Expression/Expression.cpp
@@ -1,9 +1,8 @@ //===-- Expression.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,16 +12,18 @@ using namespace lldb_private; -Expression::Expression(Target &target) - : m_target_wp(target.shared_from_this()), +Expression::Expression(Target &target, ExpressionKind kind) + : m_kind(kind), + m_target_wp(target.shared_from_this()), m_jit_start_addr(LLDB_INVALID_ADDRESS), m_jit_end_addr(LLDB_INVALID_ADDRESS) { // Can't make any kind of expression without a target. assert(m_target_wp.lock()); } -Expression::Expression(ExecutionContextScope &exe_scope) - : m_target_wp(exe_scope.CalculateTarget()), +Expression::Expression(ExecutionContextScope &exe_scope, ExpressionKind kind) + : m_kind(kind), + m_target_wp(exe_scope.CalculateTarget()), m_jit_start_addr(LLDB_INVALID_ADDRESS), m_jit_end_addr(LLDB_INVALID_ADDRESS) { assert(m_target_wp.lock());
diff --git a/src/llvm-project/lldb/source/Expression/ExpressionVariable.cpp b/src/llvm-project/lldb/source/Expression/ExpressionVariable.cpp index bce9a87..97305dc 100644 --- a/src/llvm-project/lldb/source/Expression/ExpressionVariable.cpp +++ b/src/llvm-project/lldb/source/Expression/ExpressionVariable.cpp
@@ -1,9 +1,8 @@ //===-- ExpressionVariable.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,12 +25,12 @@ return const_cast<uint8_t *>( m_frozen_sp->GetDataExtractor().GetDataStart()); } - return NULL; + return nullptr; } PersistentExpressionState::~PersistentExpressionState() {} -lldb::addr_t PersistentExpressionState::LookupSymbol(const ConstString &name) { +lldb::addr_t PersistentExpressionState::LookupSymbol(ConstString name) { SymbolMap::iterator si = m_symbol_map.find(name.GetCString()); if (si != m_symbol_map.end())
diff --git a/src/llvm-project/lldb/source/Expression/FunctionCaller.cpp b/src/llvm-project/lldb/source/Expression/FunctionCaller.cpp index 97f4f51..618c1a1 100644 --- a/src/llvm-project/lldb/source/Expression/FunctionCaller.cpp +++ b/src/llvm-project/lldb/source/Expression/FunctionCaller.cpp
@@ -1,9 +1,8 @@ //===-- FunctionCaller.cpp ---------------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,17 +29,15 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // FunctionCaller constructor -//---------------------------------------------------------------------- FunctionCaller::FunctionCaller(ExecutionContextScope &exe_scope, const CompilerType &return_type, const Address &functionAddress, const ValueList &arg_value_list, const char *name) - : Expression(exe_scope), m_execution_unit_sp(), m_parser(), - m_jit_module_wp(), m_name(name ? name : "<unknown>"), - m_function_ptr(NULL), m_function_addr(functionAddress), + : Expression(exe_scope, eKindFunctionCaller), m_execution_unit_sp(), + m_parser(), m_jit_module_wp(), m_name(name ? name : "<unknown>"), + m_function_ptr(nullptr), m_function_addr(functionAddress), m_function_return_type(return_type), m_wrapper_function_name("__lldb_caller_function"), m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(), @@ -51,9 +48,7 @@ assert(m_jit_process_wp.lock()); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- FunctionCaller::~FunctionCaller() { lldb::ProcessSP process_sp(m_jit_process_wp.lock()); if (process_sp) { @@ -103,7 +98,8 @@ jit_file.GetFilename() = const_func_name; jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString()); m_jit_module_wp = jit_module_sp; - process->GetTarget().GetImages().Append(jit_module_sp); + process->GetTarget().GetImages().Append(jit_module_sp, + true /* notify */); } } if (process && m_jit_start_addr) @@ -141,7 +137,7 @@ Process *process = exe_ctx.GetProcessPtr(); - if (process == NULL) + if (process == nullptr) return return_value; lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); @@ -242,11 +238,11 @@ // FIXME: Use the errors Stream for better error reporting. Thread *thread = exe_ctx.GetThreadPtr(); - if (thread == NULL) { + if (thread == nullptr) { diagnostic_manager.PutString( eDiagnosticSeverityError, "Can't call a function without a valid thread."); - return NULL; + return nullptr; } // Okay, now run the function: @@ -282,7 +278,7 @@ Process *process = exe_ctx.GetProcessPtr(); - if (process == NULL) + if (process == nullptr) return false; lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); @@ -329,7 +325,7 @@ lldb::addr_t args_addr; - if (args_addr_ptr != NULL) + if (args_addr_ptr != nullptr) args_addr = *args_addr_ptr; else args_addr = LLDB_INVALID_ADDRESS; @@ -379,7 +375,7 @@ if (exe_ctx.GetProcessPtr()) exe_ctx.GetProcessPtr()->SetRunningUserExpression(false); - if (args_addr_ptr != NULL) + if (args_addr_ptr != nullptr) *args_addr_ptr = args_addr; if (return_value != lldb::eExpressionCompleted) @@ -387,7 +383,7 @@ FetchFunctionResults(exe_ctx, args_addr, results); - if (args_addr_ptr == NULL) + if (args_addr_ptr == nullptr) DeallocateFunctionResults(exe_ctx, args_addr); return lldb::eExpressionCompleted;
diff --git a/src/llvm-project/lldb/source/Expression/IRExecutionUnit.cpp b/src/llvm-project/lldb/source/Expression/IRExecutionUnit.cpp index ec6ceea..25404ad 100644 --- a/src/llvm-project/lldb/source/Expression/IRExecutionUnit.cpp +++ b/src/llvm-project/lldb/source/Expression/IRExecutionUnit.cpp
@@ -1,9 +1,8 @@ //===-- IRExecutionUnit.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,7 +24,7 @@ #include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/SymbolVendor.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" +#include "lldb/Target/LanguageRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" @@ -37,14 +36,14 @@ using namespace lldb_private; -IRExecutionUnit::IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_ap, - std::unique_ptr<llvm::Module> &module_ap, +IRExecutionUnit::IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_up, + std::unique_ptr<llvm::Module> &module_up, ConstString &name, const lldb::TargetSP &target_sp, const SymbolContext &sym_ctx, std::vector<std::string> &cpu_features) - : IRMemoryMap(target_sp), m_context_ap(context_ap.release()), - m_module_ap(module_ap.release()), m_module(m_module_ap.get()), + : IRMemoryMap(target_sp), m_context_up(context_up.release()), + m_module_up(module_up.release()), m_module(m_module_up.get()), m_cpu_features(cpu_features), m_name(name), m_sym_ctx(sym_ctx), m_did_jit(false), m_function_load_addr(LLDB_INVALID_ADDRESS), m_function_end_load_addr(LLDB_INVALID_ADDRESS), @@ -166,8 +165,8 @@ ArchSpec arch(target->GetArchitecture()); - const char *plugin_name = NULL; - const char *flavor_string = NULL; + const char *plugin_name = nullptr; + const char *flavor_string = nullptr; lldb::DisassemblerSP disassembler_sp = Disassembler::FindPlugin(arch, flavor_string, plugin_name); @@ -213,7 +212,7 @@ } } -void IRExecutionUnit::ReportSymbolLookupError(const ConstString &name) { +void IRExecutionUnit::ReportSymbolLookupError(ConstString name) { m_failed_lookups.push_back(name); } @@ -252,30 +251,24 @@ std::string s; llvm::raw_string_ostream oss(s); - m_module->print(oss, NULL); + m_module->print(oss, nullptr); oss.flush(); log->Printf("Module being sent to JIT: \n%s", s.c_str()); } - llvm::Triple triple(m_module->getTargetTriple()); - llvm::Reloc::Model relocModel; - - if (triple.isOSBinFormatELF()) { - relocModel = llvm::Reloc::Static; - } else { - relocModel = llvm::Reloc::PIC_; - } - - m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, + m_module_up->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, &error); - llvm::EngineBuilder builder(std::move(m_module_ap)); + llvm::EngineBuilder builder(std::move(m_module_up)); + llvm::Triple triple(m_module->getTargetTriple()); builder.setEngineKind(llvm::EngineKind::JIT) .setErrorStr(&error_string) - .setRelocationModel(relocModel) + .setRelocationModel(triple.isOSBinFormatMachO() + ? llvm::Reloc::PIC_ + : llvm::Reloc::Static) .setMCJITMemoryManager( std::unique_ptr<MemoryManager>(new MemoryManager(*this))) .setOptLevel(llvm::CodeGenOpt::Less); @@ -290,18 +283,18 @@ llvm::TargetMachine *target_machine = builder.selectTarget(triple, mArch, mCPU, mAttrs); - m_execution_engine_ap.reset(builder.create(target_machine)); + m_execution_engine_up.reset(builder.create(target_machine)); - m_strip_underscore = - (m_execution_engine_ap->getDataLayout().getGlobalPrefix() == '_'); - - if (!m_execution_engine_ap.get()) { + if (!m_execution_engine_up) { error.SetErrorToGenericError(); error.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str()); return; } + m_strip_underscore = + (m_execution_engine_up->getDataLayout().getGlobalPrefix() == '_'); + class ObjectDumper : public llvm::ObjectCache { public: void notifyObjectCompiled(const llvm::Module *module, @@ -324,15 +317,15 @@ }; if (process_sp->GetTarget().GetEnableSaveObjects()) { - m_object_cache_ap = llvm::make_unique<ObjectDumper>(); - m_execution_engine_ap->setObjectCache(m_object_cache_ap.get()); + m_object_cache_up = llvm::make_unique<ObjectDumper>(); + m_execution_engine_up->setObjectCache(m_object_cache_up.get()); } // Make sure we see all sections, including ones that don't have // relocations... - m_execution_engine_ap->setProcessAllSections(true); + m_execution_engine_up->setProcessAllSections(true); - m_execution_engine_ap->DisableLazyCompilation(); + m_execution_engine_up->DisableLazyCompilation(); for (llvm::Function &function : *m_module) { if (function.isDeclaration() || function.hasPrivateLinkage()) @@ -341,7 +334,7 @@ const bool external = function.hasExternalLinkage() || function.hasLinkOnceODRLinkage(); - void *fun_ptr = m_execution_engine_ap->getPointerToFunction(&function); + void *fun_ptr = m_execution_engine_up->getPointerToFunction(&function); if (!error.Success()) { // We got an error through our callback! @@ -360,7 +353,7 @@ } CommitAllocations(process_sp); - ReportAllocations(*m_execution_engine_ap); + ReportAllocations(*m_execution_engine_up); // We have to do this after calling ReportAllocations because for the MCJIT, // getGlobalValueAddress will cause the JIT to perform all relocations. That @@ -372,7 +365,7 @@ llvm::GlobalValue &val) { if (val.hasExternalLinkage() && !val.isDeclaration()) { uint64_t var_ptr_addr = - m_execution_engine_ap->getGlobalValueAddress(val.getName().str()); + m_execution_engine_up->getGlobalValueAddress(val.getName().str()); lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr); @@ -407,7 +400,7 @@ bool emitNewLine = false; - for (const ConstString &failed_lookup : m_failed_lookups) { + for (ConstString failed_lookup : m_failed_lookups) { if (emitNewLine) ss.PutCString("\n"); emitNewLine = true; @@ -489,13 +482,13 @@ } IRExecutionUnit::~IRExecutionUnit() { - m_module_ap.reset(); - m_execution_engine_ap.reset(); - m_context_ap.reset(); + m_module_up.reset(); + m_execution_engine_up.reset(); + m_context_up.reset(); } IRExecutionUnit::MemoryManager::MemoryManager(IRExecutionUnit &parent) - : m_default_mm_ap(new llvm::SectionMemoryManager()), m_parent(parent) {} + : m_default_mm_up(new llvm::SectionMemoryManager()), m_parent(parent) {} IRExecutionUnit::MemoryManager::~MemoryManager() {} @@ -597,7 +590,7 @@ llvm::StringRef SectionName) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); - uint8_t *return_value = m_default_mm_ap->allocateCodeSection( + uint8_t *return_value = m_default_mm_up->allocateCodeSection( Size, Alignment, SectionID, SectionName); m_parent.m_records.push_back(AllocationRecord( @@ -628,7 +621,7 @@ llvm::StringRef SectionName, bool IsReadOnly) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); - uint8_t *return_value = m_default_mm_ap->allocateDataSection( + uint8_t *return_value = m_default_mm_up->allocateDataSection( Size, Alignment, SectionID, SectionName, IsReadOnly); uint32_t permissions = lldb::ePermissionsReadable; @@ -656,7 +649,7 @@ } static ConstString -FindBestAlternateMangledName(const ConstString &demangled, +FindBestAlternateMangledName(ConstString demangled, const lldb::LanguageType &lang_type, const SymbolContext &sym_ctx) { CPlusPlusLanguage::MethodName cpp_name(demangled); @@ -718,7 +711,7 @@ void IRExecutionUnit::CollectCandidateCNames( std::vector<IRExecutionUnit::SearchSpec> &C_specs, - const ConstString &name) { + ConstString name) { if (m_strip_underscore && name.AsCString()[0] == '_') C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1])); C_specs.push_back(SearchSpec(name)); @@ -728,7 +721,7 @@ std::vector<IRExecutionUnit::SearchSpec> &CPP_specs, const std::vector<SearchSpec> &C_specs, const SymbolContext &sc) { for (const SearchSpec &C_spec : C_specs) { - const ConstString &name = C_spec.name; + ConstString name = C_spec.name; if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) { Mangled mangled(name, true); @@ -760,7 +753,7 @@ // but the DWARF doesn't always encode "extern C" correctly. for (const SearchSpec &C_spec : C_specs) { - const ConstString &name = C_spec.name; + ConstString name = C_spec.name; if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) { Mangled mangled_name(name); @@ -781,7 +774,9 @@ lldb::addr_t IRExecutionUnit::FindInSymbols( const std::vector<IRExecutionUnit::SearchSpec> &specs, - const lldb_private::SymbolContext &sc) { + const lldb_private::SymbolContext &sc, + bool &symbol_was_missing_weak) { + symbol_was_missing_weak = false; Target *target = sc.target_sp.get(); if (!target) { @@ -796,16 +791,26 @@ std::function<bool(lldb::addr_t &, SymbolContextList &, const lldb_private::SymbolContext &)> - get_external_load_address = [&best_internal_load_address, target]( + get_external_load_address = [&best_internal_load_address, target, + &symbol_was_missing_weak]( lldb::addr_t &load_address, SymbolContextList &sc_list, const lldb_private::SymbolContext &sc) -> lldb::addr_t { load_address = LLDB_INVALID_ADDRESS; - for (size_t si = 0, se = sc_list.GetSize(); si < se; ++si) { - SymbolContext candidate_sc; + if (sc_list.GetSize() == 0) + return false; - sc_list.GetContextAtIndex(si, candidate_sc); - + // missing_weak_symbol will be true only if we found only weak undefined + // references to this symbol. + symbol_was_missing_weak = true; + for (auto candidate_sc : sc_list.SymbolContexts()) { + // Only symbols can be weak undefined: + if (!candidate_sc.symbol) + symbol_was_missing_weak = false; + else if (candidate_sc.symbol->GetType() != lldb::eSymbolTypeUndefined + || !candidate_sc.symbol->IsWeak()) + symbol_was_missing_weak = false; + const bool is_external = (candidate_sc.function) || (candidate_sc.symbol && candidate_sc.symbol->IsExternal()); @@ -842,11 +847,18 @@ } } + // You test the address of a weak symbol against NULL to see if it is + // present. So we should return 0 for a missing weak symbol. + if (symbol_was_missing_weak) { + load_address = 0; + return true; + } + return false; }; if (sc.module_sp) { - sc.module_sp->FindFunctions(spec.name, NULL, spec.mask, + sc.module_sp->FindFunctions(spec.name, nullptr, spec.mask, true, // include_symbols false, // include_inlines true, // append @@ -909,10 +921,8 @@ return LLDB_INVALID_ADDRESS; } - ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime(); - - if (runtime) { - for (const SearchSpec &spec : specs) { + for (const SearchSpec &spec : specs) { + for (LanguageRuntime *runtime : process_sp->GetLanguageRuntimes()) { lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name); if (symbol_load_addr != LLDB_INVALID_ADDRESS) @@ -939,31 +949,37 @@ } lldb::addr_t -IRExecutionUnit::FindSymbol(const lldb_private::ConstString &name) { +IRExecutionUnit::FindSymbol(lldb_private::ConstString name, bool &missing_weak) { std::vector<SearchSpec> candidate_C_names; std::vector<SearchSpec> candidate_CPlusPlus_names; CollectCandidateCNames(candidate_C_names, name); + + lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx, missing_weak); + if (ret != LLDB_INVALID_ADDRESS) + return ret; + + // If we find the symbol in runtimes or user defined symbols it can't be + // a missing weak symbol. + missing_weak = false; + ret = FindInRuntimes(candidate_C_names, m_sym_ctx); + if (ret != LLDB_INVALID_ADDRESS) + return ret; - lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx); - if (ret == LLDB_INVALID_ADDRESS) - ret = FindInRuntimes(candidate_C_names, m_sym_ctx); + ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx); + if (ret != LLDB_INVALID_ADDRESS) + return ret; - if (ret == LLDB_INVALID_ADDRESS) - ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx); + CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names, + m_sym_ctx); + ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx, missing_weak); + if (ret != LLDB_INVALID_ADDRESS) + return ret; - if (ret == LLDB_INVALID_ADDRESS) { - CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names, - m_sym_ctx); - ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx); - } + std::vector<SearchSpec> candidate_fallback_names; - if (ret == LLDB_INVALID_ADDRESS) { - std::vector<SearchSpec> candidate_fallback_names; - - CollectFallbackNames(candidate_fallback_names, candidate_C_names); - ret = FindInSymbols(candidate_fallback_names, m_sym_ctx); - } + CollectFallbackNames(candidate_fallback_names, candidate_C_names); + ret = FindInSymbols(candidate_fallback_names, m_sym_ctx, missing_weak); return ret; } @@ -998,13 +1014,32 @@ } } +llvm::JITSymbol +IRExecutionUnit::MemoryManager::findSymbol(const std::string &Name) { + bool missing_weak = false; + uint64_t addr = GetSymbolAddressAndPresence(Name, missing_weak); + // This is a weak symbol: + if (missing_weak) + return llvm::JITSymbol(addr, + llvm::JITSymbolFlags::Exported | llvm::JITSymbolFlags::Weak); + else + return llvm::JITSymbol(addr, llvm::JITSymbolFlags::Exported); +} + uint64_t IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) { + bool missing_weak = false; + return GetSymbolAddressAndPresence(Name, missing_weak); +} + +uint64_t +IRExecutionUnit::MemoryManager::GetSymbolAddressAndPresence( + const std::string &Name, bool &missing_weak) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); ConstString name_cs(Name.c_str()); - lldb::addr_t ret = m_parent.FindSymbol(name_cs); + lldb::addr_t ret = m_parent.FindSymbol(name_cs, missing_weak); if (ret == LLDB_INVALID_ADDRESS) { if (log) @@ -1024,8 +1059,6 @@ void *IRExecutionUnit::MemoryManager::getPointerToNamedFunction( const std::string &Name, bool AbortOnFailure) { - assert(sizeof(void *) == 8); - return (void *)getSymbolAddress(Name); }
diff --git a/src/llvm-project/lldb/source/Expression/IRInterpreter.cpp b/src/llvm-project/lldb/source/Expression/IRInterpreter.cpp index 457eaef..5a9814d 100644 --- a/src/llvm-project/lldb/source/Expression/IRInterpreter.cpp +++ b/src/llvm-project/lldb/source/Expression/IRInterpreter.cpp
@@ -1,9 +1,8 @@ //===-- IRInterpreter.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -234,8 +233,9 @@ case Value::FunctionVal: if (const Function *constant_func = dyn_cast<Function>(constant)) { lldb_private::ConstString name(constant_func->getName()); - lldb::addr_t addr = m_execution_unit.FindSymbol(name); - if (addr == LLDB_INVALID_ADDRESS) + bool missing_weak = false; + lldb::addr_t addr = m_execution_unit.FindSymbol(name, missing_weak); + if (addr == LLDB_INVALID_ADDRESS || missing_weak) return false; value = APInt(m_target_data.getPointerSizeInBits(), addr); return true; @@ -655,7 +655,7 @@ std::string s; raw_string_ostream oss(s); - module.print(oss, NULL); + module.print(oss, nullptr); oss.flush(); @@ -1601,16 +1601,16 @@ "unable to locate host data for transfer to device"); // Create the required buffer rawArgs[i].size = dataSize; - rawArgs[i].data_ap.reset(new uint8_t[dataSize + 1]); + rawArgs[i].data_up.reset(new uint8_t[dataSize + 1]); // Read string from host memory - execution_unit.ReadMemory(rawArgs[i].data_ap.get(), addr, dataSize, + execution_unit.ReadMemory(rawArgs[i].data_up.get(), addr, dataSize, error); assert(!error.Fail() && "we have failed to read the string from memory"); // Add null terminator - rawArgs[i].data_ap[dataSize] = '\0'; + rawArgs[i].data_up[dataSize] = '\0'; rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer; } else /* if ( arg_ty->isPointerTy() ) */ {
diff --git a/src/llvm-project/lldb/source/Expression/IRMemoryMap.cpp b/src/llvm-project/lldb/source/Expression/IRMemoryMap.cpp index e4c85d6..70e62ac 100644 --- a/src/llvm-project/lldb/source/Expression/IRMemoryMap.cpp +++ b/src/llvm-project/lldb/source/Expression/IRMemoryMap.cpp
@@ -1,9 +1,8 @@ //===-- IRMemoryMap.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -264,7 +263,7 @@ if (target_sp) return target_sp.get(); - return NULL; + return nullptr; } IRMemoryMap::Allocation::Allocation(lldb::addr_t process_alloc, @@ -276,7 +275,7 @@ m_alignment(alignment) { switch (policy) { default: - assert(0 && "We cannot reach this!"); + llvm_unreachable("Invalid AllocationPolicy"); case eAllocationPolicyHostOnly: case eAllocationPolicyMirror: m_data.SetByteSize(size);
diff --git a/src/llvm-project/lldb/source/Expression/LLVMUserExpression.cpp b/src/llvm-project/lldb/source/Expression/LLVMUserExpression.cpp index edf1e69..5a1b750 100644 --- a/src/llvm-project/lldb/source/Expression/LLVMUserExpression.cpp +++ b/src/llvm-project/lldb/source/Expression/LLVMUserExpression.cpp
@@ -1,9 +1,8 @@ //===-- LLVMUserExpression.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,7 +12,6 @@ #include "lldb/Core/StreamFile.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Expression/ExpressionSourceCode.h" #include "lldb/Expression/IRExecutionUnit.h" #include "lldb/Expression/IRInterpreter.h" #include "lldb/Expression/Materializer.h" @@ -43,18 +41,17 @@ llvm::StringRef prefix, lldb::LanguageType language, ResultType desired_type, - const EvaluateExpressionOptions &options) - : UserExpression(exe_scope, expr, prefix, language, desired_type, options), + const EvaluateExpressionOptions &options, + ExpressionKind kind) + : UserExpression(exe_scope, expr, prefix, language, desired_type, options, + kind), m_stack_frame_bottom(LLDB_INVALID_ADDRESS), - m_stack_frame_top(LLDB_INVALID_ADDRESS), - m_allow_cxx(false), - m_allow_objc(false), - m_transformed_text(), - m_execution_unit_sp(), m_materializer_ap(), m_jit_module_wp(), - m_enforce_valid_object(true), m_in_cplusplus_method(false), - m_in_objectivec_method(false), m_in_static_method(false), - m_needs_object_ptr(false), m_target(NULL), m_can_interpret(false), - m_materialized_address(LLDB_INVALID_ADDRESS) {} + m_stack_frame_top(LLDB_INVALID_ADDRESS), m_allow_cxx(false), + m_allow_objc(false), m_transformed_text(), m_execution_unit_sp(), + m_materializer_up(), m_jit_module_wp(), m_enforce_valid_object(true), + m_in_cplusplus_method(false), m_in_objectivec_method(false), + m_in_static_method(false), m_needs_object_ptr(false), m_target(nullptr), + m_can_interpret(false), m_materialized_address(LLDB_INVALID_ADDRESS) {} LLVMUserExpression::~LLVMUserExpression() { if (m_target) { @@ -116,10 +113,9 @@ function_stack_bottom = m_stack_frame_bottom; function_stack_top = m_stack_frame_top; - IRInterpreter::Interpret(*module, *function, args, - *m_execution_unit_sp.get(), interpreter_error, - function_stack_bottom, function_stack_top, - exe_ctx); + IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp, + interpreter_error, function_stack_bottom, + function_stack_top, exe_ctx); if (!interpreter_error.Success()) { diagnostic_manager.Printf(eDiagnosticSeverityError, @@ -185,7 +181,7 @@ if (execution_result == lldb::eExpressionInterrupted || execution_result == lldb::eExpressionHitBreakpoint) { - const char *error_desc = NULL; + const char *error_desc = nullptr; if (call_plan_sp) { lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo(); @@ -314,8 +310,8 @@ const bool zero_memory = false; m_materialized_address = m_execution_unit_sp->Malloc( - m_materializer_ap->GetStructByteSize(), - m_materializer_ap->GetStructAlignment(), + m_materializer_up->GetStructByteSize(), + m_materializer_up->GetStructAlignment(), lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy, zero_memory, alloc_error); @@ -355,7 +351,7 @@ Status materialize_error; - m_dematerializer_sp = m_materializer_ap->Materialize( + m_dematerializer_sp = m_materializer_up->Materialize( frame, *m_execution_unit_sp, struct_address, materialize_error); if (!materialize_error.Success()) {
diff --git a/src/llvm-project/lldb/source/Expression/Materializer.cpp b/src/llvm-project/lldb/source/Expression/Materializer.cpp index 4d4e5e2..0f871fc 100644 --- a/src/llvm-project/lldb/source/Expression/Materializer.cpp +++ b/src/llvm-project/lldb/source/Expression/Materializer.cpp
@@ -1,9 +1,8 @@ //===-- Materializer.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,6 +23,8 @@ #include "lldb/Utility/Log.h" #include "lldb/Utility/RegisterValue.h" +#include <memory> + using namespace lldb_private; uint32_t Materializer::AddStructMember(Entity &entity) { @@ -538,7 +539,8 @@ "size of variable %s (%" PRIu64 ") is larger than the ValueObject's size (%" PRIu64 ")", m_variable_sp->GetName().AsCString(), - m_variable_sp->GetType()->GetByteSize(), data.GetByteSize()); + m_variable_sp->GetType()->GetByteSize().getValueOr(0), + data.GetByteSize()); } return; } @@ -560,8 +562,8 @@ m_temporary_allocation_size = data.GetByteSize(); - m_original_data.reset( - new DataBufferHeap(data.GetDataStart(), data.GetByteSize())); + m_original_data = std::make_shared<DataBufferHeap>(data.GetDataStart(), + data.GetByteSize()); if (!alloc_error.Success()) { err.SetErrorStringWithFormat( @@ -1215,8 +1217,8 @@ return; } - m_register_contents.reset(new DataBufferHeap(register_data.GetDataStart(), - register_data.GetByteSize())); + m_register_contents = std::make_shared<DataBufferHeap>( + register_data.GetDataStart(), register_data.GetByteSize()); Status write_error;
diff --git a/src/llvm-project/lldb/source/Expression/REPL.cpp b/src/llvm-project/lldb/source/Expression/REPL.cpp index 943385b..f4ed887 100644 --- a/src/llvm-project/lldb/source/Expression/REPL.cpp +++ b/src/llvm-project/lldb/source/Expression/REPL.cpp
@@ -1,9 +1,8 @@ //===-- REPL.cpp ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,10 +15,11 @@ #include "lldb/Host/HostInfo.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/AnsiTerminal.h" +#include <memory> + using namespace lldb_private; REPL::REPL(LLVMCastKind kind, Target &target) : m_target(target), m_kind(kind) { @@ -28,12 +28,6 @@ auto exe_ctx = debugger.GetCommandInterpreter().GetExecutionContext(); m_format_options.OptionParsingStarting(&exe_ctx); m_varobj_options.OptionParsingStarting(&exe_ctx); - m_command_options.OptionParsingStarting(&exe_ctx); - - // Default certain settings for REPL regardless of the global settings. - m_command_options.unwind_on_error = false; - m_command_options.ignore_breakpoints = false; - m_command_options.debug = false; } REPL::~REPL() = default; @@ -72,15 +66,15 @@ lldb::IOHandlerSP REPL::GetIOHandler() { if (!m_io_handler_sp) { Debugger &debugger = m_target.GetDebugger(); - m_io_handler_sp.reset( - new IOHandlerEditline(debugger, IOHandler::Type::REPL, - "lldb-repl", // Name of input reader for history - llvm::StringRef("> "), // prompt - llvm::StringRef(". "), // Continuation prompt - true, // Multi-line - true, // The REPL prompt is always colored - 1, // Line number - *this)); + m_io_handler_sp = std::make_shared<IOHandlerEditline>( + debugger, IOHandler::Type::REPL, + "lldb-repl", // Name of input reader for history + llvm::StringRef("> "), // prompt + llvm::StringRef(". "), // Continuation prompt + true, // Multi-line + true, // The REPL prompt is always colored + 1, // Line number + *this, nullptr); // Don't exit if CTRL+C is pressed static_cast<IOHandlerEditline *>(m_io_handler_sp.get()) @@ -98,7 +92,7 @@ return m_io_handler_sp; } -void REPL::IOHandlerActivated(IOHandler &io_handler) { +void REPL::IOHandlerActivated(IOHandler &io_handler, bool interactive) { lldb::ProcessSP process_sp = m_target.GetProcessSP(); if (process_sp && process_sp->IsAlive()) return; @@ -275,22 +269,15 @@ const bool colorize_err = error_sp->GetFile().GetIsTerminalWithColors(); - EvaluateExpressionOptions expr_options; + EvaluateExpressionOptions expr_options = m_expr_options; expr_options.SetCoerceToId(m_varobj_options.use_objc); - expr_options.SetUnwindOnError(m_command_options.unwind_on_error); - expr_options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints); expr_options.SetKeepInMemory(true); expr_options.SetUseDynamic(m_varobj_options.use_dynamic); - expr_options.SetTryAllThreads(m_command_options.try_all_threads); expr_options.SetGenerateDebugInfo(true); expr_options.SetREPLEnabled(true); expr_options.SetColorizeErrors(colorize_err); expr_options.SetPoundLine(m_repl_source_path.c_str(), m_code.GetSize() + 1); - if (m_command_options.timeout > 0) - expr_options.SetTimeout(std::chrono::microseconds(m_command_options.timeout)); - else - expr_options.SetTimeout(llvm::None); expr_options.SetLanguage(GetLanguage()); @@ -306,7 +293,6 @@ lldb::ExpressionResults execution_results = UserExpression::Evaluate(exe_ctx, expr_options, code.c_str(), expr_prefix, result_valobj_sp, error, - 0, // Line offset nullptr, // Fixed Expression &jit_module_sp);
diff --git a/src/llvm-project/lldb/source/Expression/UserExpression.cpp b/src/llvm-project/lldb/source/Expression/UserExpression.cpp index 34945fd..a72e2a0 100644 --- a/src/llvm-project/lldb/source/Expression/UserExpression.cpp +++ b/src/llvm-project/lldb/source/Expression/UserExpression.cpp
@@ -1,9 +1,8 @@ //===-- UserExpression.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,12 +15,11 @@ #include <map> #include <string> -#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "lldb/Core/Module.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Expression/ExpressionSourceCode.h" +#include "lldb/Expression/ExpressionVariable.h" #include "lldb/Expression/IRExecutionUnit.h" #include "lldb/Expression/IRInterpreter.h" #include "lldb/Expression/Materializer.h" @@ -50,8 +48,9 @@ llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, ResultType desired_type, - const EvaluateExpressionOptions &options) - : Expression(exe_scope), m_expr_text(expr), m_expr_prefix(prefix), + const EvaluateExpressionOptions &options, + ExpressionKind kind) + : Expression(exe_scope, kind), m_expr_text(expr), m_expr_prefix(prefix), m_language(language), m_desired_type(desired_type), m_options(options) {} UserExpression::~UserExpression() {} @@ -140,11 +139,23 @@ lldb::ExpressionResults UserExpression::Evaluate( ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr, llvm::StringRef prefix, - lldb::ValueObjectSP &result_valobj_sp, Status &error, uint32_t line_offset, - std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr) { + lldb::ValueObjectSP &result_valobj_sp, Status &error, + std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr, + ValueObject *ctx_obj) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP)); + if (ctx_obj) { + static unsigned const ctx_type_mask = + lldb::TypeFlags::eTypeIsClass | lldb::TypeFlags::eTypeIsStructUnion; + if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) { + LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of " + "an invalid type, can't run expressions."); + error.SetErrorString("a context object of an invalid type passed"); + return lldb::eExpressionSetupError; + } + } + lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy(); lldb::LanguageType language = options.GetLanguage(); const ResultType desired_type = options.DoesCoerceToId() @@ -163,7 +174,7 @@ Process *process = exe_ctx.GetProcessPtr(); - if (process == NULL || process->GetState() != lldb::eStateStopped) { + if (process == nullptr || process->GetState() != lldb::eStateStopped) { if (execution_policy == eExecutionPolicyAlways) { if (log) log->Printf("== [UserExpression::Evaluate] Expression may not run, but " @@ -175,7 +186,7 @@ } } - if (process == NULL || !process->CanJIT()) + if (process == nullptr || !process->CanJIT()) execution_policy = eExecutionPolicyNever; // We need to set the expression execution thread here, turns out parse can @@ -209,7 +220,8 @@ lldb::UserExpressionSP user_expression_sp( target->GetUserExpressionForLanguage(expr, full_prefix, language, - desired_type, options, error)); + desired_type, options, ctx_obj, + error)); if (error.Fail()) { if (log) log->Printf("== [UserExpression::Evaluate] Getting expression: %s ==", @@ -254,7 +266,8 @@ lldb::UserExpressionSP fixed_expression_sp( target->GetUserExpressionForLanguage(fixed_expression->c_str(), full_prefix, language, - desired_type, options, error)); + desired_type, options, ctx_obj, + error)); DiagnosticManager fixed_diagnostic_manager; parse_success = fixed_expression_sp->Parse( fixed_diagnostic_manager, exe_ctx, execution_policy, @@ -362,7 +375,7 @@ return lldb::eExpressionInterrupted; } - if (result_valobj_sp.get() == NULL) { + if (result_valobj_sp.get() == nullptr) { result_valobj_sp = ValueObjectConstResult::Create( exe_ctx.GetBestExecutionContextScope(), error); }
diff --git a/src/llvm-project/lldb/source/Expression/UtilityFunction.cpp b/src/llvm-project/lldb/source/Expression/UtilityFunction.cpp index a0a1e4e..eeaeca1 100644 --- a/src/llvm-project/lldb/source/Expression/UtilityFunction.cpp +++ b/src/llvm-project/lldb/source/Expression/UtilityFunction.cpp
@@ -1,9 +1,8 @@ //===-- UtilityFunction.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,7 +15,6 @@ #include "lldb/Core/Module.h" #include "lldb/Core/StreamFile.h" #include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Expression/ExpressionSourceCode.h" #include "lldb/Expression/FunctionCaller.h" #include "lldb/Expression/IRExecutionUnit.h" #include "lldb/Expression/UtilityFunction.h" @@ -31,23 +29,20 @@ using namespace lldb_private; using namespace lldb; -//------------------------------------------------------------------ /// Constructor /// -/// @param[in] text +/// \param[in] text /// The text of the function. Must be a full translation unit. /// -/// @param[in] name +/// \param[in] name /// The name of the function, as used in the text. -//------------------------------------------------------------------ UtilityFunction::UtilityFunction(ExecutionContextScope &exe_scope, - const char *text, const char *name) - : Expression(exe_scope), m_execution_unit_sp(), m_jit_module_wp(), - m_function_text(ExpressionSourceCode::g_expression_prefix), - m_function_name(name) { - if (text && text[0]) - m_function_text.append(text); -} + const char *text, const char *name, + ExpressionKind kind) + : Expression(exe_scope, kind), + m_execution_unit_sp(), m_jit_module_wp(), + m_function_text(), + m_function_name(name) {} UtilityFunction::~UtilityFunction() { lldb::ProcessSP process_sp(m_jit_process_wp.lock());
diff --git a/src/llvm-project/lldb/source/Host/CMakeLists.txt b/src/llvm-project/lldb/source/Host/CMakeLists.txt index 333f109..4bb8d36 100644 --- a/src/llvm-project/lldb/source/Host/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Host/CMakeLists.txt
@@ -18,8 +18,9 @@ endmacro() add_host_subdirectory(common - common/File.cpp + common/FileAction.cpp common/FileCache.cpp + common/File.cpp common/FileSystem.cpp common/GetOptInc.cpp common/Host.cpp @@ -30,24 +31,24 @@ common/LockFileBase.cpp common/MainLoop.cpp common/MonitoringProcessLauncher.cpp - common/NativeWatchpointList.cpp common/NativeProcessProtocol.cpp common/NativeRegisterContext.cpp common/NativeThreadProtocol.cpp + common/NativeWatchpointList.cpp common/OptionParser.cpp common/PipeBase.cpp + common/ProcessLaunchInfo.cpp common/ProcessRunLock.cpp common/PseudoTerminal.cpp - common/Socket.cpp common/SocketAddress.cpp + common/Socket.cpp common/StringConvert.cpp - common/Symbols.cpp common/TaskPool.cpp common/TCPSocket.cpp common/Terminal.cpp common/ThreadLauncher.cpp - common/XML.cpp common/UDPSocket.cpp + common/XML.cpp ) if (NOT LLDB_DISABLE_LIBEDIT) @@ -92,7 +93,6 @@ add_subdirectory(macosx/objcxx) set(LLDBObjCLibs lldbHostMacOSXObjCXX) add_host_subdirectory(macosx - macosx/Symbols.cpp macosx/cfcpp/CFCBundle.cpp macosx/cfcpp/CFCData.cpp macosx/cfcpp/CFCMutableArray.cpp @@ -101,7 +101,7 @@ macosx/cfcpp/CFCString.cpp ) if(IOS) - set_property(SOURCE macosx/Host.mm APPEND PROPERTY + set_property(SOURCE macosx/Host.mm APPEND PROPERTY COMPILE_DEFINITIONS "NO_XPC_SERVICES=1") endif() @@ -158,16 +158,21 @@ list(APPEND EXTRA_LIBS ${libedit_LIBRARIES}) endif() +if (NOT LLDB_DISABLE_LIBEDIT) + list(APPEND LLDB_LIBEDIT_LIBS ${libedit_LIBRARIES}) + if (LLVM_BUILD_STATIC) + list(APPEND LLDB_SYSTEM_LIBS gpm) + endif() +endif() + add_lldb_library(lldbHost ${HOST_SOURCES} LINK_LIBS - lldbCore - lldbSymbol - lldbTarget lldbUtility ${EXTRA_LIBS} ${LLDBObjCLibs} + ${LLDB_LIBEDIT_LIBS} LINK_COMPONENTS Object
diff --git a/src/llvm-project/lldb/source/Host/android/HostInfoAndroid.cpp b/src/llvm-project/lldb/source/Host/android/HostInfoAndroid.cpp index 3dea01f..9619ec1 100644 --- a/src/llvm-project/lldb/source/Host/android/HostInfoAndroid.cpp +++ b/src/llvm-project/lldb/source/Host/android/HostInfoAndroid.cpp
@@ -1,9 +1,8 @@ //===-- HostInfoAndroid.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/android/LibcGlue.cpp b/src/llvm-project/lldb/source/Host/android/LibcGlue.cpp index 13437f9..6eac87b 100644 --- a/src/llvm-project/lldb/source/Host/android/LibcGlue.cpp +++ b/src/llvm-project/lldb/source/Host/android/LibcGlue.cpp
@@ -1,9 +1,8 @@ //===-- LibcGlue.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/Editline.cpp b/src/llvm-project/lldb/source/Host/common/Editline.cpp index f7ba4b5..d3a70ae 100644 --- a/src/llvm-project/lldb/source/Host/common/Editline.cpp +++ b/src/llvm-project/lldb/source/Host/common/Editline.cpp
@@ -1,9 +1,8 @@ //===-- Editline.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -164,7 +163,7 @@ // Use static GetHistory() function to get a EditlineHistorySP to one of // these objects EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries) - : m_history(NULL), m_event(), m_prefix(prefix), m_path() { + : m_history(nullptr), m_event(), m_prefix(prefix), m_path() { m_history = history_winit(); history_w(m_history, &m_event, H_SETSIZE, size); if (unique_entries) @@ -172,23 +171,28 @@ } const char *GetHistoryFilePath() { + // Compute the history path lazily. if (m_path.empty() && m_history && !m_prefix.empty()) { - FileSpec parent_path("~/.lldb"); - FileSystem::Instance().Resolve(parent_path); - char history_path[PATH_MAX]; - if (!llvm::sys::fs::create_directory(parent_path.GetPath())) { - snprintf(history_path, sizeof(history_path), "~/.lldb/%s-history", - m_prefix.c_str()); - } else { - snprintf(history_path, sizeof(history_path), "~/%s-widehistory", - m_prefix.c_str()); + llvm::SmallString<128> lldb_history_file; + llvm::sys::path::home_directory(lldb_history_file); + llvm::sys::path::append(lldb_history_file, ".lldb"); + + // LLDB stores its history in ~/.lldb/. If for some reason this directory + // isn't writable or cannot be created, history won't be available. + if (!llvm::sys::fs::create_directory(lldb_history_file)) { +#if LLDB_EDITLINE_USE_WCHAR + std::string filename = m_prefix + "-widehistory"; +#else + std::string filename = m_prefix + "-history"; +#endif + llvm::sys::path::append(lldb_history_file, filename); + m_path = lldb_history_file.str(); } - auto file_spec = FileSpec(history_path); - FileSystem::Instance().Resolve(file_spec); - m_path = file_spec.GetPath(); } + if (m_path.empty()) - return NULL; + return nullptr; + return m_path.c_str(); } @@ -198,7 +202,7 @@ if (m_history) { history_wend(m_history); - m_history = NULL; + m_history = nullptr; } } @@ -220,7 +224,7 @@ return history_sp; } - bool IsValid() const { return m_history != NULL; } + bool IsValid() const { return m_history != nullptr; } HistoryW *GetHistoryPtr() { return m_history; } @@ -261,9 +265,7 @@ } } -//------------------------------------------------------------------ // Editline private methods -//------------------------------------------------------------------ void Editline::SetBaseLineNumber(int line_number) { std::stringstream line_number_stream; @@ -512,11 +514,13 @@ // Read returns, immediately lock the mutex again and check if we were // interrupted. m_output_mutex.unlock(); - int read_count = m_input_connection.Read(&ch, 1, llvm::None, status, NULL); + int read_count = + m_input_connection.Read(&ch, 1, llvm::None, status, nullptr); m_output_mutex.lock(); if (m_editor_status == EditorStatus::Interrupted) { while (read_count > 0 && status == lldb::eConnectionStatusSuccess) - read_count = m_input_connection.Read(&ch, 1, llvm::None, status, NULL); + read_count = + m_input_connection.Read(&ch, 1, llvm::None, status, nullptr); lldbassert(status == lldb::eConnectionStatusInterrupted); return 0; } @@ -857,10 +861,8 @@ return CC_NEWLINE; } -//------------------------------------------------------------------------------ /// Prints completions and their descriptions to the given file. Only the /// completions in the interval [start, end) are printed. -//------------------------------------------------------------------------------ static void PrintCompletion(FILE *output_file, size_t start, size_t end, StringList &completions, StringList &descriptions) { // This is an 'int' because of printf. @@ -875,10 +877,11 @@ const char *completion_str = completions.GetStringAtIndex(i); const char *description_str = descriptions.GetStringAtIndex(i); - fprintf(output_file, "\n\t%-*s", max_len, completion_str); + if (completion_str) + fprintf(output_file, "\n\t%-*s", max_len, completion_str); // Print the description if we got one. - if (strlen(description_str)) + if (description_str && strlen(description_str)) fprintf(output_file, " -- %s", description_str); } } @@ -977,7 +980,9 @@ TerminalSizeChanged(); if (m_history_sp && m_history_sp->IsValid()) { - m_history_sp->Load(); + if (!m_history_sp->Load()) { + fputs("Could not load history file\n.", m_output_file); + } el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr()); } el_set(m_editline, EL_CLIENTDATA, this); @@ -1078,7 +1083,7 @@ // Allow user-specific customization prior to registering bindings we // absolutely require - el_source(m_editline, NULL); + el_source(m_editline, nullptr); // Register an internal binding that external developers shouldn't use el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"), @@ -1145,9 +1150,7 @@ } } -//------------------------------------------------------------------ // Editline public methods -//------------------------------------------------------------------ Editline *Editline::InstanceFor(EditLine *editline) { Editline *editor; @@ -1222,9 +1225,13 @@ if (m_editline != nullptr) { el_resize(m_editline); int columns; - // Despite the man page claiming non-zero indicates success, it's actually - // zero - if (el_get(m_editline, EL_GETTC, "co", &columns) == 0) { + // This function is documenting as taking (const char *, void *) for the + // vararg part, but in reality in was consuming arguments until the first + // null pointer. This was fixed in libedit in April 2019 + // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>, + // but we're keeping the workaround until a version with that fix is more + // widely available. + if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) { m_terminal_width = columns; if (m_current_line_rows != -1) { const LineInfoW *info = el_wline(m_editline);
diff --git a/src/llvm-project/lldb/source/Host/common/File.cpp b/src/llvm-project/lldb/source/Host/common/File.cpp index 810c155..c8c8d7a 100644 --- a/src/llvm-project/lldb/source/Host/common/File.cpp +++ b/src/llvm-project/lldb/source/Host/common/File.cpp
@@ -1,9 +1,8 @@ //===-- File.cpp ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -66,11 +65,11 @@ } else if (options & File::eOpenOptionWrite) { return "w"; } - return NULL; + return nullptr; } int File::kInvalidDescriptor = -1; -FILE *File::kInvalidStream = NULL; +FILE *File::kInvalidStream = nullptr; File::~File() { Close(); } @@ -179,7 +178,7 @@ void File::Clear() { m_stream = nullptr; - m_descriptor = -1; + m_descriptor = kInvalidDescriptor; m_options = 0; m_own_stream = false; m_is_interactive = m_supports_colors = m_is_real_terminal = @@ -504,6 +503,7 @@ error.SetErrorString("invalid file handle"); } #else + std::lock_guard<std::mutex> guard(offset_access_mutex); long cur = ::lseek(m_descriptor, 0, SEEK_CUR); SeekFromStart(offset); error = Read(buf, num_bytes); @@ -528,18 +528,18 @@ num_bytes = bytes_left; size_t num_bytes_plus_nul_char = num_bytes + (null_terminate ? 1 : 0); - std::unique_ptr<DataBufferHeap> data_heap_ap; - data_heap_ap.reset(new DataBufferHeap()); - data_heap_ap->SetByteSize(num_bytes_plus_nul_char); + std::unique_ptr<DataBufferHeap> data_heap_up; + data_heap_up.reset(new DataBufferHeap()); + data_heap_up->SetByteSize(num_bytes_plus_nul_char); - if (data_heap_ap.get()) { - error = Read(data_heap_ap->GetBytes(), num_bytes, offset); + if (data_heap_up) { + error = Read(data_heap_up->GetBytes(), num_bytes, offset); if (error.Success()) { // Make sure we read exactly what we asked for and if we got // less, adjust the array - if (num_bytes_plus_nul_char < data_heap_ap->GetByteSize()) - data_heap_ap->SetByteSize(num_bytes_plus_nul_char); - data_buffer_sp.reset(data_heap_ap.release()); + if (num_bytes_plus_nul_char < data_heap_up->GetByteSize()) + data_heap_up->SetByteSize(num_bytes_plus_nul_char); + data_buffer_sp.reset(data_heap_up.release()); return error; } } @@ -603,7 +603,9 @@ num_bytes = bytes_written; } #else + std::lock_guard<std::mutex> guard(offset_access_mutex); long cur = ::lseek(m_descriptor, 0, SEEK_CUR); + SeekFromStart(offset); error = Write(buf, num_bytes); long after = ::lseek(m_descriptor, 0, SEEK_CUR); @@ -619,9 +621,7 @@ return error; } -//------------------------------------------------------------------ // Print some formatted output to the stream. -//------------------------------------------------------------------ size_t File::Printf(const char *format, ...) { va_list args; va_start(args, format); @@ -630,15 +630,13 @@ return result; } -//------------------------------------------------------------------ // Print some formatted output to the stream. -//------------------------------------------------------------------ size_t File::PrintfVarArg(const char *format, va_list args) { size_t result = 0; if (DescriptorIsValid()) { - char *s = NULL; + char *s = nullptr; result = vasprintf(&s, format, args); - if (s != NULL) { + if (s != nullptr) { if (result > 0) { size_t s_len = result; Write(s, s_len);
diff --git a/src/llvm-project/lldb/source/Target/FileAction.cpp b/src/llvm-project/lldb/source/Host/common/FileAction.cpp similarity index 84% rename from src/llvm-project/lldb/source/Target/FileAction.cpp rename to src/llvm-project/lldb/source/Host/common/FileAction.cpp index c9cc325..3268d95 100644 --- a/src/llvm-project/lldb/source/Target/FileAction.cpp +++ b/src/llvm-project/lldb/source/Host/common/FileAction.cpp
@@ -1,23 +1,20 @@ //===-- FileAction.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <fcntl.h> +#include "lldb/Host/FileAction.h" #include "lldb/Host/PosixApi.h" -#include "lldb/Target/FileAction.h" #include "lldb/Utility/Stream.h" using namespace lldb_private; -//---------------------------------------------------------------------------- // FileAction member functions -//---------------------------------------------------------------------------- FileAction::FileAction() : m_action(eFileActionNone), m_fd(-1), m_arg(-1), m_file_spec() {}
diff --git a/src/llvm-project/lldb/source/Host/common/FileCache.cpp b/src/llvm-project/lldb/source/Host/common/FileCache.cpp index 17833ef..4bd3efd 100644 --- a/src/llvm-project/lldb/source/Host/common/FileCache.cpp +++ b/src/llvm-project/lldb/source/Host/common/FileCache.cpp
@@ -1,9 +1,8 @@ //===-- FileCache.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/FileSystem.cpp b/src/llvm-project/lldb/source/Host/common/FileSystem.cpp index 7191c9d..d5ac05b 100644 --- a/src/llvm-project/lldb/source/Host/common/FileSystem.cpp +++ b/src/llvm-project/lldb/source/Host/common/FileSystem.cpp
@@ -1,9 +1,8 @@ //===-- FileSystem.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,7 +11,9 @@ #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/TildeExpressionResolver.h" +#include "llvm/Support/Errc.h" #include "llvm/Support/Errno.h" +#include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Program.h" @@ -48,6 +49,27 @@ InstanceImpl().emplace(); } +void FileSystem::Initialize(FileCollector &collector) { + lldbassert(!InstanceImpl() && "Already initialized."); + InstanceImpl().emplace(collector); +} + +llvm::Error FileSystem::Initialize(const FileSpec &mapping) { + lldbassert(!InstanceImpl() && "Already initialized."); + + llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer = + llvm::vfs::getRealFileSystem()->getBufferForFile(mapping.GetPath()); + + if (!buffer) + return llvm::errorCodeToError(buffer.getError()); + + InstanceImpl().emplace(llvm::vfs::getVFSFromYAML(std::move(buffer.get()), + nullptr, mapping.GetPath()), + true); + + return llvm::Error::success(); +} + void FileSystem::Initialize(IntrusiveRefCntPtr<vfs::FileSystem> fs) { lldbassert(!InstanceImpl() && "Already initialized."); InstanceImpl().emplace(fs); @@ -220,17 +242,21 @@ if (path.empty()) return; - // Resolve tilde. - SmallString<128> original_path(path.begin(), path.end()); + // Resolve tilde in path. + SmallString<128> resolved(path.begin(), path.end()); StandardTildeExpressionResolver Resolver; - Resolver.ResolveFullPath(original_path, path); + Resolver.ResolveFullPath(llvm::StringRef(path.begin(), path.size()), + resolved); // Try making the path absolute if it exists. - SmallString<128> absolute_path(path.begin(), path.end()); - MakeAbsolute(path); - if (!Exists(path)) { - path.clear(); - path.append(original_path.begin(), original_path.end()); + SmallString<128> absolute(resolved.begin(), resolved.end()); + MakeAbsolute(absolute); + + path.clear(); + if (Exists(absolute)) { + path.append(absolute.begin(), absolute.end()); + } else { + path.append(resolved.begin(), resolved.end()); } } @@ -243,25 +269,35 @@ Resolve(path); // Update the FileSpec with the resolved path. - file_spec.SetPath(path); + if (file_spec.GetFilename().IsEmpty()) + file_spec.GetDirectory().SetString(path); + else + file_spec.SetPath(path); file_spec.SetIsResolved(true); } std::shared_ptr<DataBufferLLVM> FileSystem::CreateDataBuffer(const llvm::Twine &path, uint64_t size, uint64_t offset) { + if (m_collector) + m_collector->AddFile(path); + const bool is_volatile = !IsLocal(path); + const ErrorOr<std::string> external_path = GetExternalPath(path); + + if (!external_path) + return nullptr; std::unique_ptr<llvm::WritableMemoryBuffer> buffer; if (size == 0) { auto buffer_or_error = - llvm::WritableMemoryBuffer::getFile(path, -1, is_volatile); + llvm::WritableMemoryBuffer::getFile(*external_path, -1, is_volatile); if (!buffer_or_error) return nullptr; buffer = std::move(*buffer_or_error); } else { auto buffer_or_error = llvm::WritableMemoryBuffer::getFileSlice( - path, size, offset, is_volatile); + *external_path, size, offset, is_volatile); if (!buffer_or_error) return nullptr; buffer = std::move(*buffer_or_error); @@ -277,12 +313,12 @@ bool FileSystem::ResolveExecutableLocation(FileSpec &file_spec) { // If the directory is set there's nothing to do. - const ConstString &directory = file_spec.GetDirectory(); + ConstString directory = file_spec.GetDirectory(); if (directory) return false; // We cannot look for a file if there's no file name. - const ConstString &filename = file_spec.GetFilename(); + ConstString filename = file_spec.GetFilename(); if (!filename) return false; @@ -380,25 +416,56 @@ } Status FileSystem::Open(File &File, const FileSpec &file_spec, uint32_t options, - uint32_t permissions) { + uint32_t permissions, bool should_close_fd) { + if (m_collector) + m_collector->AddFile(file_spec); + if (File.IsValid()) File.Close(); const int open_flags = GetOpenFlags(options); const mode_t open_mode = (open_flags & O_CREAT) ? GetOpenMode(permissions) : 0; - const std::string path = file_spec.GetPath(); + + auto path = GetExternalPath(file_spec); + if (!path) + return Status(path.getError()); int descriptor = llvm::sys::RetryAfterSignal( - -1, OpenWithFS, *this, path.c_str(), open_flags, open_mode); + -1, OpenWithFS, *this, path->c_str(), open_flags, open_mode); Status error; if (!File::DescriptorIsValid(descriptor)) { File.SetDescriptor(descriptor, false); error.SetErrorToErrno(); } else { - File.SetDescriptor(descriptor, true); + File.SetDescriptor(descriptor, should_close_fd); File.SetOptions(options); } return error; } + +ErrorOr<std::string> FileSystem::GetExternalPath(const llvm::Twine &path) { + if (!m_mapped) + return path.str(); + + // If VFS mapped we know the underlying FS is a RedirectingFileSystem. + ErrorOr<vfs::RedirectingFileSystem::Entry *> E = + static_cast<vfs::RedirectingFileSystem &>(*m_fs).lookupPath(path); + if (!E) { + if (E.getError() == llvm::errc::no_such_file_or_directory) { + return path.str(); + } + return E.getError(); + } + + auto *F = dyn_cast<vfs::RedirectingFileSystem::RedirectingFileEntry>(*E); + if (!F) + return make_error_code(llvm::errc::not_supported); + + return F->getExternalContentsPath().str(); +} + +ErrorOr<std::string> FileSystem::GetExternalPath(const FileSpec &file_spec) { + return GetExternalPath(file_spec.GetPath()); +}
diff --git a/src/llvm-project/lldb/source/Host/common/GetOptInc.cpp b/src/llvm-project/lldb/source/Host/common/GetOptInc.cpp index 1d9b317..95a68c5 100644 --- a/src/llvm-project/lldb/source/Host/common/GetOptInc.cpp +++ b/src/llvm-project/lldb/source/Host/common/GetOptInc.cpp
@@ -1,9 +1,8 @@ //===-- GetOptInc.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -98,9 +97,9 @@ pos += nopts; swap = nargv[pos]; /* LINTED const cast */ - ((char **)nargv)[pos] = nargv[cstart]; + const_cast<char **>(nargv)[pos] = nargv[cstart]; /* LINTED const cast */ - ((char **)nargv)[cstart] = swap; + const_cast<char **>(nargv)[cstart] = swap; } } }
diff --git a/src/llvm-project/lldb/source/Host/common/Host.cpp b/src/llvm-project/lldb/source/Host/common/Host.cpp index 62b936a..3ba9ab7 100644 --- a/src/llvm-project/lldb/source/Host/common/Host.cpp +++ b/src/llvm-project/lldb/source/Host/common/Host.cpp
@@ -1,9 +1,8 @@ //===-- Host.cpp ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -47,17 +46,16 @@ #include <csignal> +#include "lldb/Host/FileAction.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Host/HostProcess.h" #include "lldb/Host/MonitoringProcessLauncher.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Host/ProcessLauncher.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" -#include "lldb/Target/FileAction.h" -#include "lldb/Target/ProcessLaunchInfo.h" -#include "lldb/Target/UnixSignals.h" #include "lldb/Utility/DataBufferLLVM.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" @@ -101,7 +99,7 @@ static thread_result_t MonitorChildProcessThreadFunction(void *arg); -HostThread Host::StartMonitoringChildProcess( +llvm::Expected<HostThread> Host::StartMonitoringChildProcess( const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid, bool monitor_signals) { MonitorInfo *info_ptr = new MonitorInfo(); @@ -114,14 +112,12 @@ ::snprintf(thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid); return ThreadLauncher::LaunchThread( - thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL); + thread_name, MonitorChildProcessThreadFunction, info_ptr, 0); } #ifndef __linux__ -//------------------------------------------------------------------ // Scoped class that will disable thread canceling when it is constructed, and // exception safely restore the previous value it when it goes out of scope. -//------------------------------------------------------------------ class ScopedPThreadCancelDisabler { public: ScopedPThreadCancelDisabler() { @@ -223,7 +219,7 @@ bool exited = false; int signal = 0; int exit_status = 0; - const char *status_cstr = NULL; + const char *status_cstr = nullptr; if (WIFSTOPPED(status)) { signal = WSTOPSIG(status); status_cstr = "STOPPED"; @@ -286,7 +282,7 @@ if (log) log->Printf("%s (arg = %p) thread exiting...", __FUNCTION__, arg); - return NULL; + return nullptr; } #endif // #if !defined (__APPLE__) && !defined (_WIN32) @@ -397,7 +393,7 @@ default: break; } - return NULL; + return nullptr; } #endif @@ -466,16 +462,19 @@ int *status_ptr, int *signo_ptr, std::string *command_output_ptr, const Timeout<std::micro> &timeout, - bool run_in_default_shell) { + bool run_in_default_shell, + bool hide_stderr) { return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, - command_output_ptr, timeout, run_in_default_shell); + command_output_ptr, timeout, run_in_default_shell, + hide_stderr); } Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output_ptr, const Timeout<std::micro> &timeout, - bool run_in_default_shell) { + bool run_in_default_shell, + bool hide_stderr) { Status error; ProcessLaunchInfo launch_info; launch_info.SetArchitecture(HostInfo::GetArchitecture()); @@ -513,16 +512,18 @@ } FileSpec output_file_spec(output_file_path.c_str()); - + // Set up file descriptors. launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false); - if (output_file_spec) { + if (output_file_spec) launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false, true); - launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO); - } else { + else launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true); + + if (output_file_spec && !hide_stderr) + launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO); + else launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true); - } std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo()); const bool monitor_signals = false; @@ -614,12 +615,6 @@ #endif -const UnixSignalsSP &Host::GetUnixSignals() { - static const auto s_unix_signals_sp = - UnixSignals::Create(HostInfo::GetArchitecture()); - return s_unix_signals_sp; -} - std::unique_ptr<Connection> Host::CreateDefaultConnection(llvm::StringRef url) { #if defined(_WIN32) if (url.startswith("file://"))
diff --git a/src/llvm-project/lldb/source/Host/common/HostInfoBase.cpp b/src/llvm-project/lldb/source/Host/common/HostInfoBase.cpp index 34c362e..130f0eb 100644 --- a/src/llvm-project/lldb/source/Host/common/HostInfoBase.cpp +++ b/src/llvm-project/lldb/source/Host/common/HostInfoBase.cpp
@@ -1,9 +1,8 @@ //===-- HostInfoBase.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,13 +31,11 @@ using namespace lldb_private; namespace { -//---------------------------------------------------------------------- // The HostInfoBaseFields is a work around for windows not supporting static // variables correctly in a thread safe way. Really each of the variables in // HostInfoBaseFields should live in the functions in which they are used and // each one should be static, but the work around is in place to avoid this // restriction. Ick. -//---------------------------------------------------------------------- struct HostInfoBaseFields { ~HostInfoBaseFields() { @@ -215,6 +212,38 @@ return ArchSpec(normalized_triple); } +bool HostInfoBase::ComputePathRelativeToLibrary(FileSpec &file_spec, + llvm::StringRef dir) { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); + + FileSpec lldb_file_spec = GetShlibDir(); + if (!lldb_file_spec) + return false; + + std::string raw_path = lldb_file_spec.GetPath(); + if (log) + log->Printf("HostInfo::%s() attempting to " + "derive the path %s relative to liblldb install path: %s", + __FUNCTION__, dir.data(), raw_path.c_str()); + + // Drop bin (windows) or lib + llvm::StringRef parent_path = llvm::sys::path::parent_path(raw_path); + if (parent_path.empty()) { + if (log) + log->Printf("HostInfo::%s() failed to find liblldb within the shared " + "lib path", + __FUNCTION__); + return false; + } + + raw_path = (parent_path + dir).str(); + if (log) + log->Printf("HostInfo::%s() derived the path as: %s", __FUNCTION__, + raw_path.c_str()); + file_spec.GetDirectory().SetString(raw_path); + return (bool)file_spec.GetDirectory(); +} + bool HostInfoBase::ComputeSharedLibraryDirectory(FileSpec &file_spec) { // To get paths related to LLDB we get the path to the executable that // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB".
diff --git a/src/llvm-project/lldb/source/Host/common/HostNativeThreadBase.cpp b/src/llvm-project/lldb/source/Host/common/HostNativeThreadBase.cpp index 25c8066..a5f876a 100644 --- a/src/llvm-project/lldb/source/Host/common/HostNativeThreadBase.cpp +++ b/src/llvm-project/lldb/source/Host/common/HostNativeThreadBase.cpp
@@ -1,9 +1,8 @@ //===-- HostNativeThreadBase.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/HostProcess.cpp b/src/llvm-project/lldb/source/Host/common/HostProcess.cpp index 1540333..e180687 100644 --- a/src/llvm-project/lldb/source/Host/common/HostProcess.cpp +++ b/src/llvm-project/lldb/source/Host/common/HostProcess.cpp
@@ -1,9 +1,8 @@ //===-- HostProcess.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,7 +32,7 @@ bool HostProcess::IsRunning() const { return m_native_process->IsRunning(); } -HostThread +llvm::Expected<HostThread> HostProcess::StartMonitoring(const Host::MonitorChildProcessCallback &callback, bool monitor_signals) { return m_native_process->StartMonitoring(callback, monitor_signals);
diff --git a/src/llvm-project/lldb/source/Host/common/HostThread.cpp b/src/llvm-project/lldb/source/Host/common/HostThread.cpp index 2bf6f0a..89cadce 100644 --- a/src/llvm-project/lldb/source/Host/common/HostThread.cpp +++ b/src/llvm-project/lldb/source/Host/common/HostThread.cpp
@@ -1,9 +1,8 @@ //===-- HostThread.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/LockFileBase.cpp b/src/llvm-project/lldb/source/Host/common/LockFileBase.cpp index a8d7881..744b1ea 100644 --- a/src/llvm-project/lldb/source/Host/common/LockFileBase.cpp +++ b/src/llvm-project/lldb/source/Host/common/LockFileBase.cpp
@@ -1,9 +1,8 @@ //===-- LockFileBase.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/MainLoop.cpp b/src/llvm-project/lldb/source/Host/common/MainLoop.cpp index 337ddd5..1ce09a8 100644 --- a/src/llvm-project/lldb/source/Host/common/MainLoop.cpp +++ b/src/llvm-project/lldb/source/Host/common/MainLoop.cpp
@@ -1,9 +1,8 @@ //===-- MainLoop.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -62,10 +61,12 @@ static sig_atomic_t g_signal_flags[NSIG]; +#ifndef SIGNAL_POLLING_UNSUPPORTED static void SignalHandler(int signo, siginfo_t *info, void *) { assert(signo < NSIG); g_signal_flags[signo] = 1; } +#endif class MainLoop::RunImpl { public: @@ -144,18 +145,20 @@ } sigset_t MainLoop::RunImpl::get_sigmask() { -#if SIGNAL_POLLING_UNSUPPORTED - return 0; -#else sigset_t sigmask; +#if defined(_WIN32) + sigmask = 0; +#elif SIGNAL_POLLING_UNSUPPORTED + sigemptyset(&sigmask); +#else int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask); assert(ret == 0); (void) ret; for (const auto &sig : loop.m_signals) sigdelset(&sigmask, sig.first); - return sigmask; #endif + return sigmask; } #ifdef __ANDROID__ @@ -387,9 +390,6 @@ return error; impl.ProcessEvents(); - - if (m_terminate_request) - return Status(); } return Status(); }
diff --git a/src/llvm-project/lldb/source/Host/common/MonitoringProcessLauncher.cpp b/src/llvm-project/lldb/source/Host/common/MonitoringProcessLauncher.cpp index f6f772c..55e9f69 100644 --- a/src/llvm-project/lldb/source/Host/common/MonitoringProcessLauncher.cpp +++ b/src/llvm-project/lldb/source/Host/common/MonitoringProcessLauncher.cpp
@@ -1,16 +1,15 @@ //===-- MonitoringProcessLauncher.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/MonitoringProcessLauncher.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/HostProcess.h" -#include "lldb/Target/ProcessLaunchInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Utility/Log.h" #include "llvm/Support/FileSystem.h" @@ -54,8 +53,12 @@ Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); assert(launch_info.GetMonitorProcessCallback()); - process.StartMonitoring(launch_info.GetMonitorProcessCallback(), - launch_info.GetMonitorSignals()); + llvm::Expected<HostThread> maybe_thread = + process.StartMonitoring(launch_info.GetMonitorProcessCallback(), + launch_info.GetMonitorSignals()); + if (!maybe_thread) + error.SetErrorStringWithFormatv("failed to launch host thread: {}", + llvm::toString(maybe_thread.takeError())); if (log) log->PutCString("started monitoring child process."); } else {
diff --git a/src/llvm-project/lldb/source/Host/common/NativeProcessProtocol.cpp b/src/llvm-project/lldb/source/Host/common/NativeProcessProtocol.cpp index e3c81f6..90272cb 100644 --- a/src/llvm-project/lldb/source/Host/common/NativeProcessProtocol.cpp +++ b/src/llvm-project/lldb/source/Host/common/NativeProcessProtocol.cpp
@@ -1,9 +1,8 @@ //===-- NativeProcessProtocol.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,9 +19,7 @@ using namespace lldb; using namespace lldb_private; -// ----------------------------------------------------------------------------- // NativeProcessProtocol Members -// ----------------------------------------------------------------------------- NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd, NativeDelegate &delegate)
diff --git a/src/llvm-project/lldb/source/Host/common/NativeRegisterContext.cpp b/src/llvm-project/lldb/source/Host/common/NativeRegisterContext.cpp index 6e6632a..2f30d52 100644 --- a/src/llvm-project/lldb/source/Host/common/NativeRegisterContext.cpp +++ b/src/llvm-project/lldb/source/Host/common/NativeRegisterContext.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContext.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,9 +21,7 @@ NativeRegisterContext::NativeRegisterContext(NativeThreadProtocol &thread) : m_thread(thread) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- NativeRegisterContext::~NativeRegisterContext() {} // FIXME revisit invalidation, process stop ids, etc. Right now we don't
diff --git a/src/llvm-project/lldb/source/Host/common/NativeThreadProtocol.cpp b/src/llvm-project/lldb/source/Host/common/NativeThreadProtocol.cpp index af43683..e62b142 100644 --- a/src/llvm-project/lldb/source/Host/common/NativeThreadProtocol.cpp +++ b/src/llvm-project/lldb/source/Host/common/NativeThreadProtocol.cpp
@@ -1,9 +1,8 @@ //===-- NativeThreadProtocol.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/NativeWatchpointList.cpp b/src/llvm-project/lldb/source/Host/common/NativeWatchpointList.cpp index e6ef730..c3db95f 100644 --- a/src/llvm-project/lldb/source/Host/common/NativeWatchpointList.cpp +++ b/src/llvm-project/lldb/source/Host/common/NativeWatchpointList.cpp
@@ -1,9 +1,8 @@ //===-- NativeWatchpointList.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/OptionParser.cpp b/src/llvm-project/lldb/source/Host/common/OptionParser.cpp index d78bf33..1e76f9b 100644 --- a/src/llvm-project/lldb/source/Host/common/OptionParser.cpp +++ b/src/llvm-project/lldb/source/Host/common/OptionParser.cpp
@@ -1,9 +1,8 @@ //===-- source/Host/common/OptionParser.cpp ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,8 +27,9 @@ void OptionParser::EnableError(bool error) { opterr = error ? 1 : 0; } -int OptionParser::Parse(int argc, char *const argv[], llvm::StringRef optstring, - const Option *longopts, int *longindex) { +int OptionParser::Parse(llvm::MutableArrayRef<char *> argv, + llvm::StringRef optstring, const Option *longopts, + int *longindex) { std::vector<option> opts; while (longopts->definition != nullptr) { option opt; @@ -42,7 +42,8 @@ } opts.push_back(option()); std::string opt_cstr = optstring; - return getopt_long_only(argc, argv, opt_cstr.c_str(), &opts[0], longindex); + return getopt_long_only(argv.size() - 1, argv.data(), opt_cstr.c_str(), + &opts[0], longindex); } char *OptionParser::GetOptionArgument() { return optarg; } @@ -56,11 +57,11 @@ int i = 0; bool done = false; while (!done) { - if (long_options[i].name == 0 && long_options[i].has_arg == 0 && - long_options[i].flag == 0 && long_options[i].val == 0) { + if (long_options[i].name == nullptr && long_options[i].has_arg == 0 && + long_options[i].flag == nullptr && long_options[i].val == 0) { done = true; } else { - if (long_options[i].flag == NULL && isalpha(long_options[i].val)) { + if (long_options[i].flag == nullptr && isalpha(long_options[i].val)) { s.append(1, (char)long_options[i].val); switch (long_options[i].has_arg) { default:
diff --git a/src/llvm-project/lldb/source/Host/common/PipeBase.cpp b/src/llvm-project/lldb/source/Host/common/PipeBase.cpp index 632bfcb..2cbadf0 100644 --- a/src/llvm-project/lldb/source/Host/common/PipeBase.cpp +++ b/src/llvm-project/lldb/source/Host/common/PipeBase.cpp
@@ -1,9 +1,8 @@ //===-- source/Host/common/PipeBase.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/ProcessLaunchInfo.cpp b/src/llvm-project/lldb/source/Host/common/ProcessLaunchInfo.cpp similarity index 95% rename from src/llvm-project/lldb/source/Target/ProcessLaunchInfo.cpp rename to src/llvm-project/lldb/source/Host/common/ProcessLaunchInfo.cpp index ac1eba0..266b467 100644 --- a/src/llvm-project/lldb/source/Target/ProcessLaunchInfo.cpp +++ b/src/llvm-project/lldb/source/Host/common/ProcessLaunchInfo.cpp
@@ -1,19 +1,18 @@ //===-- ProcessLaunchInfo.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <climits> #include "lldb/Host/Config.h" +#include "lldb/Host/FileAction.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/FileAction.h" -#include "lldb/Target/ProcessLaunchInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" @@ -27,9 +26,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------------- // ProcessLaunchInfo member functions -//---------------------------------------------------------------------------- ProcessLaunchInfo::ProcessLaunchInfo() : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(0), @@ -191,8 +188,13 @@ bool ProcessLaunchInfo::MonitorProcess() const { if (m_monitor_callback && ProcessIDIsValid()) { + llvm::Expected<HostThread> maybe_thread = Host::StartMonitoringChildProcess(m_monitor_callback, GetProcessID(), m_monitor_signals); + if (!maybe_thread) + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(maybe_thread.takeError())); return true; } return false;
diff --git a/src/llvm-project/lldb/source/Host/common/ProcessRunLock.cpp b/src/llvm-project/lldb/source/Host/common/ProcessRunLock.cpp index e0ba2ec..a931da7 100644 --- a/src/llvm-project/lldb/source/Host/common/ProcessRunLock.cpp +++ b/src/llvm-project/lldb/source/Host/common/ProcessRunLock.cpp
@@ -1,9 +1,8 @@ //===-- ProcessRunLock.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,19 +12,13 @@ namespace lldb_private { ProcessRunLock::ProcessRunLock() : m_running(false) { - int err = ::pthread_rwlock_init(&m_rwlock, NULL); + int err = ::pthread_rwlock_init(&m_rwlock, nullptr); (void)err; - //#if LLDB_CONFIGURATION_DEBUG - // assert(err == 0); - //#endif } ProcessRunLock::~ProcessRunLock() { int err = ::pthread_rwlock_destroy(&m_rwlock); (void)err; - //#if LLDB_CONFIGURATION_DEBUG - // assert(err == 0); - //#endif } bool ProcessRunLock::ReadTryLock() {
diff --git a/src/llvm-project/lldb/source/Host/common/PseudoTerminal.cpp b/src/llvm-project/lldb/source/Host/common/PseudoTerminal.cpp index 08d4fa2..85e54f4 100644 --- a/src/llvm-project/lldb/source/Host/common/PseudoTerminal.cpp +++ b/src/llvm-project/lldb/source/Host/common/PseudoTerminal.cpp
@@ -1,9 +1,8 @@ //===-- PseudoTerminal.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -27,36 +26,28 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // Write string describing error number -//---------------------------------------------------------------------- static void ErrnoToStr(char *error_str, size_t error_len) { std::string strerror = llvm::sys::StrError(); ::snprintf(error_str, error_len, "%s", strerror.c_str()); } -//---------------------------------------------------------------------- // PseudoTerminal constructor -//---------------------------------------------------------------------- PseudoTerminal::PseudoTerminal() : m_master_fd(invalid_fd), m_slave_fd(invalid_fd) {} -//---------------------------------------------------------------------- // Destructor // // The destructor will close the master and slave file descriptors if they are // valid and ownership has not been released using the // ReleaseMasterFileDescriptor() or the ReleaseSaveFileDescriptor() member // functions. -//---------------------------------------------------------------------- PseudoTerminal::~PseudoTerminal() { CloseMasterFileDescriptor(); CloseSlaveFileDescriptor(); } -//---------------------------------------------------------------------- // Close the master file descriptor if it is valid. -//---------------------------------------------------------------------- void PseudoTerminal::CloseMasterFileDescriptor() { if (m_master_fd >= 0) { ::close(m_master_fd); @@ -64,9 +55,7 @@ } } -//---------------------------------------------------------------------- // Close the slave file descriptor if it is valid. -//---------------------------------------------------------------------- void PseudoTerminal::CloseSlaveFileDescriptor() { if (m_slave_fd >= 0) { ::close(m_slave_fd); @@ -74,7 +63,6 @@ } } -//---------------------------------------------------------------------- // Open the first available pseudo terminal with OFLAG as the permissions. The // file descriptor is stored in this object and can be accessed with the // MasterFileDescriptor() accessor. The ownership of the master file descriptor @@ -86,7 +74,6 @@ // // RETURNS: // True when successful, false indicating an error occurred. -//---------------------------------------------------------------------- bool PseudoTerminal::OpenFirstAvailableMaster(int oflag, char *error_str, size_t error_len) { if (error_str) @@ -125,7 +112,6 @@ #endif } -//---------------------------------------------------------------------- // Open the slave pseudo terminal for the current master pseudo terminal. A // master pseudo terminal should already be valid prior to calling this // function (see OpenFirstAvailableMaster()). The file descriptor is stored @@ -135,7 +121,6 @@ // // RETURNS: // True when successful, false indicating an error occurred. -//---------------------------------------------------------------------- bool PseudoTerminal::OpenSlave(int oflag, char *error_str, size_t error_len) { if (error_str) error_str[0] = '\0'; @@ -148,7 +133,7 @@ if (slave_name == nullptr) return false; - m_slave_fd = ::open(slave_name, oflag); + m_slave_fd = llvm::sys::RetryAfterSignal(-1, ::open, slave_name, oflag); if (m_slave_fd < 0) { if (error_str) @@ -159,7 +144,6 @@ return true; } -//---------------------------------------------------------------------- // Get the name of the slave pseudo terminal. A master pseudo terminal should // already be valid prior to calling this function (see // OpenFirstAvailableMaster()). @@ -169,7 +153,6 @@ // The name of the slave pseudo terminal as a NULL terminated C string // that comes from static memory, so a copy of the string should be // made as subsequent calls can change this value. -//---------------------------------------------------------------------- const char *PseudoTerminal::GetSlaveName(char *error_str, size_t error_len) const { if (error_str) @@ -189,7 +172,6 @@ return slave_name; } -//---------------------------------------------------------------------- // Fork a child process and have its stdio routed to a pseudo terminal. // // In the parent process when a valid pid is returned, the master file @@ -207,7 +189,6 @@ // RETURNS: // in the parent process: the pid of the child, or -1 if fork fails // in the child process: zero -//---------------------------------------------------------------------- lldb::pid_t PseudoTerminal::Fork(char *error_str, size_t error_len) { if (error_str) error_str[0] = '\0'; @@ -266,7 +247,6 @@ return pid; } -//---------------------------------------------------------------------- // The master file descriptor accessor. This object retains ownership of the // master file descriptor when this accessor is used. Use // ReleaseMasterFileDescriptor() if you wish this object to release ownership @@ -274,23 +254,18 @@ // // Returns the master file descriptor, or -1 if the master file descriptor is // not currently valid. -//---------------------------------------------------------------------- int PseudoTerminal::GetMasterFileDescriptor() const { return m_master_fd; } -//---------------------------------------------------------------------- // The slave file descriptor accessor. // // Returns the slave file descriptor, or -1 if the slave file descriptor is not // currently valid. -//---------------------------------------------------------------------- int PseudoTerminal::GetSlaveFileDescriptor() const { return m_slave_fd; } -//---------------------------------------------------------------------- // Release ownership of the master pseudo terminal file descriptor without // closing it. The destructor for this class will close the master file // descriptor if the ownership isn't released using this call and the master // file descriptor has been opened. -//---------------------------------------------------------------------- int PseudoTerminal::ReleaseMasterFileDescriptor() { // Release ownership of the master pseudo terminal file descriptor without // closing it. (the destructor for this class will close it otherwise!) @@ -299,12 +274,10 @@ return fd; } -//---------------------------------------------------------------------- // Release ownership of the slave pseudo terminal file descriptor without // closing it. The destructor for this class will close the slave file // descriptor if the ownership isn't released using this call and the slave // file descriptor has been opened. -//---------------------------------------------------------------------- int PseudoTerminal::ReleaseSlaveFileDescriptor() { // Release ownership of the slave pseudo terminal file descriptor without // closing it (the destructor for this class will close it otherwise!)
diff --git a/src/llvm-project/lldb/source/Host/common/Socket.cpp b/src/llvm-project/lldb/source/Host/common/Socket.cpp index 875291b..a89f117 100644 --- a/src/llvm-project/lldb/source/Host/common/Socket.cpp +++ b/src/llvm-project/lldb/source/Host/common/Socket.cpp
@@ -1,9 +1,8 @@ //===-- Socket.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,6 +18,9 @@ #include "lldb/Utility/RegularExpression.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/Support/Errno.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/WindowsError.h" #ifndef LLDB_DISABLE_POSIX #include "lldb/Host/posix/DomainSocket.h" @@ -78,6 +80,31 @@ Socket::~Socket() { Close(); } +llvm::Error Socket::Initialize() { +#if defined(_WIN32) + auto wVersion = WINSOCK_VERSION; + WSADATA wsaData; + int err = ::WSAStartup(wVersion, &wsaData); + if (err == 0) { + if (wsaData.wVersion < wVersion) { + WSACleanup(); + return llvm::make_error<llvm::StringError>( + "WSASock version is not expected.", llvm::inconvertibleErrorCode()); + } + } else { + return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError())); + } +#endif + + return llvm::Error::success(); +} + +void Socket::Terminate() { +#if defined(_WIN32) + ::WSACleanup(); +#endif +} + std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, bool child_processes_inherit, Status &error) { @@ -124,7 +151,7 @@ Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); if (log) log->Printf("Socket::%s (host/port = %s)", __FUNCTION__, - host_and_port.data()); + host_and_port.str().c_str()); Status error; std::unique_ptr<Socket> connect_socket( @@ -144,7 +171,7 @@ Predicate<uint16_t> *predicate, int backlog) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) - log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data()); + log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.str().c_str()); Status error; std::string host_str; @@ -184,7 +211,7 @@ Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) log->Printf("Socket::%s (host/port = %s)", __FUNCTION__, - host_and_port.data()); + host_and_port.str().c_str()); return UDPSocket::Connect(host_and_port, child_processes_inherit, socket); } @@ -260,8 +287,8 @@ llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)")); RegularExpression::Match regex_match(2); if (g_regex.Execute(host_and_port, ®ex_match)) { - if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) && - regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) { + if (regex_match.GetMatchAtIndex(host_and_port, 1, host_str) && + regex_match.GetMatchAtIndex(host_and_port, 2, port_str)) { // IPv6 addresses are wrapped in [] when specified with ports if (host_str.front() == '[' && host_str.back() == ']') host_str = host_str.substr(1, host_str.size() - 2); @@ -275,7 +302,8 @@ // port is too large if (error_ptr) error_ptr->SetErrorStringWithFormat( - "invalid host:port specification: '%s'", host_and_port.data()); + "invalid host:port specification: '%s'", + host_and_port.str().c_str()); return false; } } @@ -284,9 +312,7 @@ // integer, representing a port with an empty host. host_str.clear(); port_str.clear(); - bool ok = false; - port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok); - if (ok && port < UINT16_MAX) { + if (to_integer(host_and_port, port, 10) && port < UINT16_MAX) { port_str = host_and_port; if (error_ptr) error_ptr->Clear(); @@ -295,7 +321,7 @@ if (error_ptr) error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", - host_and_port.data()); + host_and_port.str().c_str()); return false; } @@ -368,8 +394,8 @@ Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) - log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this), - m_socket); + log->Printf("%p Socket::Close (fd = %" PRIu64 ")", + static_cast<void *>(this), static_cast<uint64_t>(m_socket)); #if defined(_WIN32) bool success = !!closesocket(m_socket); @@ -453,9 +479,11 @@ if (!child_processes_inherit) { flags |= SOCK_CLOEXEC; } - NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags); + NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept4, + sockfd, addr, addrlen, flags); #else - NativeSocket fd = ::accept(sockfd, addr, addrlen); + NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept, + sockfd, addr, addrlen); #endif if (fd == kInvalidSocketValue) SetLastError(error);
diff --git a/src/llvm-project/lldb/source/Host/common/SocketAddress.cpp b/src/llvm-project/lldb/source/Host/common/SocketAddress.cpp index 172cb06..882fd24 100644 --- a/src/llvm-project/lldb/source/Host/common/SocketAddress.cpp +++ b/src/llvm-project/lldb/source/Host/common/SocketAddress.cpp
@@ -1,9 +1,8 @@ //===-- SocketAddress.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // @@ -72,9 +71,7 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // SocketAddress constructor -//---------------------------------------------------------------------- SocketAddress::SocketAddress() { Clear(); } SocketAddress::SocketAddress(const struct sockaddr &s) { m_socket_addr.sa = s; } @@ -95,15 +92,7 @@ *this = addr_info; } -//---------------------------------------------------------------------- -// SocketAddress copy constructor -//---------------------------------------------------------------------- -SocketAddress::SocketAddress(const SocketAddress &rhs) - : m_socket_addr(rhs.m_socket_addr) {} - -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SocketAddress::~SocketAddress() {} void SocketAddress::Clear() { @@ -184,9 +173,7 @@ return false; } -//---------------------------------------------------------------------- // SocketAddress assignment operator -//---------------------------------------------------------------------- const SocketAddress &SocketAddress::operator=(const SocketAddress &rhs) { if (this != &rhs) m_socket_addr = rhs.m_socket_addr; @@ -249,11 +236,11 @@ hints.ai_protocol = ai_protocol; hints.ai_flags = ai_flags; - struct addrinfo *service_info_list = NULL; + struct addrinfo *service_info_list = nullptr; int err = ::getaddrinfo(hostname, servname, &hints, &service_info_list); if (err == 0 && service_info_list) { - for (struct addrinfo *service_ptr = service_info_list; service_ptr != NULL; - service_ptr = service_ptr->ai_next) { + for (struct addrinfo *service_ptr = service_info_list; + service_ptr != nullptr; service_ptr = service_ptr->ai_next) { addr_list.emplace_back(SocketAddress(service_ptr)); } }
diff --git a/src/llvm-project/lldb/source/Host/common/StringConvert.cpp b/src/llvm-project/lldb/source/Host/common/StringConvert.cpp index 8f4e195..8bf04f0 100644 --- a/src/llvm-project/lldb/source/Host/common/StringConvert.cpp +++ b/src/llvm-project/lldb/source/Host/common/StringConvert.cpp
@@ -1,9 +1,8 @@ //===-- StringConvert.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/common/TCPSocket.cpp b/src/llvm-project/lldb/source/Host/common/TCPSocket.cpp index 1a10336..58f99f7 100644 --- a/src/llvm-project/lldb/source/Host/common/TCPSocket.cpp +++ b/src/llvm-project/lldb/source/Host/common/TCPSocket.cpp
@@ -1,9 +1,8 @@ //===-- TCPSocket.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,6 +17,7 @@ #include "lldb/Utility/Log.h" #include "llvm/Config/llvm-config.h" +#include "llvm/Support/Errno.h" #include "llvm/Support/raw_ostream.h" #ifndef LLDB_DISABLE_POSIX @@ -118,6 +118,14 @@ return ""; } +std::string TCPSocket::GetRemoteConnectionURI() const { + if (m_socket != kInvalidSocketValue) { + return llvm::formatv("connect://[{0}]:{1}", GetRemoteIPAddress(), + GetRemotePortNumber()); + } + return ""; +} + Status TCPSocket::CreateSocket(int domain) { Status error; if (IsValid()) @@ -143,7 +151,7 @@ return error; auto addresses = lldb_private::SocketAddress::GetAddressInfo( - host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP); + host_str.c_str(), nullptr, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP); for (auto address : addresses) { error = CreateSocket(address.GetFamily()); if (error.Fail()) @@ -151,8 +159,8 @@ address.SetPort(port); - if (-1 == ::connect(GetNativeSocket(), &address.sockaddr(), - address.GetLength())) { + if (-1 == llvm::sys::RetryAfterSignal(-1, ::connect, + GetNativeSocket(), &address.sockaddr(), address.GetLength())) { CLOSE_SOCKET(GetNativeSocket()); continue; } @@ -182,7 +190,7 @@ if (host_str == "*") host_str = "0.0.0.0"; auto addresses = lldb_private::SocketAddress::GetAddressInfo( - host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP); + host_str.c_str(), nullptr, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP); for (auto address : addresses) { int fd = Socket::CreateSocket(address.GetFamily(), kType, IPPROTO_TCP, m_child_processes_inherit, error);
diff --git a/src/llvm-project/lldb/source/Host/common/TaskPool.cpp b/src/llvm-project/lldb/source/Host/common/TaskPool.cpp index ba1362a..73f761b 100644 --- a/src/llvm-project/lldb/source/Host/common/TaskPool.cpp +++ b/src/llvm-project/lldb/source/Host/common/TaskPool.cpp
@@ -1,14 +1,14 @@ //===--------------------- TaskPool.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/TaskPool.h" #include "lldb/Host/ThreadLauncher.h" +#include "lldb/Utility/Log.h" #include <cstdint> #include <queue> @@ -66,15 +66,22 @@ // Note that this detach call needs to happen with the m_tasks_mutex held. // This prevents the thread from exiting prematurely and triggering a linux // libc bug (https://sourceware.org/bugzilla/show_bug.cgi?id=19951). - lldb_private::ThreadLauncher::LaunchThread("task-pool.worker", WorkerPtr, - this, nullptr, min_stack_size) - .Release(); + llvm::Expected<HostThread> host_thread = + lldb_private::ThreadLauncher::LaunchThread( + "task-pool.worker", WorkerPtr, this, min_stack_size); + if (host_thread) { + host_thread->Release(); + } else { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(host_thread.takeError())); + } } } lldb::thread_result_t TaskPoolImpl::WorkerPtr(void *pool) { Worker((TaskPoolImpl *)pool); - return 0; + return {}; } void TaskPoolImpl::Worker(TaskPoolImpl *pool) {
diff --git a/src/llvm-project/lldb/source/Host/common/Terminal.cpp b/src/llvm-project/lldb/source/Host/common/Terminal.cpp index be912fb..4b536b0 100644 --- a/src/llvm-project/lldb/source/Host/common/Terminal.cpp +++ b/src/llvm-project/lldb/source/Host/common/Terminal.cpp
@@ -1,9 +1,8 @@ //===-- Terminal.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -82,36 +81,30 @@ return false; } -//---------------------------------------------------------------------- // Default constructor -//---------------------------------------------------------------------- TerminalState::TerminalState() : m_tty(), m_tflags(-1), #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED - m_termios_ap(), + m_termios_up(), #endif m_process_group(-1) { } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- TerminalState::~TerminalState() {} void TerminalState::Clear() { m_tty.Clear(); m_tflags = -1; #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED - m_termios_ap.reset(); + m_termios_up.reset(); #endif m_process_group = -1; } -//---------------------------------------------------------------------- // Save the current state of the TTY for the file descriptor "fd" and if // "save_process_group" is true, attempt to save the process group info for the // TTY. -//---------------------------------------------------------------------- bool TerminalState::Save(int fd, bool save_process_group) { m_tty.SetFileDescriptor(fd); if (m_tty.IsATerminal()) { @@ -119,11 +112,11 @@ m_tflags = ::fcntl(fd, F_GETFL, 0); #endif #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED - if (m_termios_ap.get() == NULL) - m_termios_ap.reset(new struct termios); - int err = ::tcgetattr(fd, m_termios_ap.get()); + if (m_termios_up == nullptr) + m_termios_up.reset(new struct termios); + int err = ::tcgetattr(fd, m_termios_up.get()); if (err != 0) - m_termios_ap.reset(); + m_termios_up.reset(); #endif // #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED #ifndef LLDB_DISABLE_POSIX if (save_process_group) @@ -135,17 +128,15 @@ m_tty.Clear(); m_tflags = -1; #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED - m_termios_ap.reset(); + m_termios_up.reset(); #endif m_process_group = -1; } return IsValid(); } -//---------------------------------------------------------------------- // Restore the state of the TTY using the cached values from a previous call to // Save(). -//---------------------------------------------------------------------- bool TerminalState::Restore() const { #ifndef LLDB_DISABLE_POSIX if (IsValid()) { @@ -155,12 +146,12 @@ #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED if (TTYStateIsValid()) - tcsetattr(fd, TCSANOW, m_termios_ap.get()); + tcsetattr(fd, TCSANOW, m_termios_up.get()); #endif // #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED if (ProcessGroupIsValid()) { // Save the original signal handler. - void (*saved_sigttou_callback)(int) = NULL; + void (*saved_sigttou_callback)(int) = nullptr; saved_sigttou_callback = (void (*)(int))signal(SIGTTOU, SIG_IGN); // Set the process group tcsetpgrp(fd, m_process_group); @@ -173,60 +164,44 @@ return false; } -//---------------------------------------------------------------------- // Returns true if this object has valid saved TTY state settings that can be // used to restore a previous state. -//---------------------------------------------------------------------- bool TerminalState::IsValid() const { return m_tty.FileDescriptorIsValid() && (TFlagsIsValid() || TTYStateIsValid()); } -//---------------------------------------------------------------------- // Returns true if m_tflags is valid -//---------------------------------------------------------------------- bool TerminalState::TFlagsIsValid() const { return m_tflags != -1; } -//---------------------------------------------------------------------- // Returns true if m_ttystate is valid -//---------------------------------------------------------------------- bool TerminalState::TTYStateIsValid() const { #ifdef LLDB_CONFIG_TERMIOS_SUPPORTED - return m_termios_ap.get() != 0; + return m_termios_up != nullptr; #else return false; #endif } -//---------------------------------------------------------------------- // Returns true if m_process_group is valid -//---------------------------------------------------------------------- bool TerminalState::ProcessGroupIsValid() const { return static_cast<int32_t>(m_process_group) != -1; } -//------------------------------------------------------------------ // Constructor -//------------------------------------------------------------------ TerminalStateSwitcher::TerminalStateSwitcher() : m_currentState(UINT32_MAX) {} -//------------------------------------------------------------------ // Destructor -//------------------------------------------------------------------ TerminalStateSwitcher::~TerminalStateSwitcher() {} -//------------------------------------------------------------------ // Returns the number of states that this switcher contains -//------------------------------------------------------------------ uint32_t TerminalStateSwitcher::GetNumberOfStates() const { return llvm::array_lengthof(m_ttystates); } -//------------------------------------------------------------------ // Restore the state at index "idx". // // Returns true if the restore was successful, false otherwise. -//------------------------------------------------------------------ bool TerminalStateSwitcher::Restore(uint32_t idx) const { const uint32_t num_states = GetNumberOfStates(); if (idx >= num_states) @@ -248,12 +223,10 @@ return false; } -//------------------------------------------------------------------ // Save the state at index "idx" for file descriptor "fd" and save the process // group if requested. // // Returns true if the restore was successful, false otherwise. -//------------------------------------------------------------------ bool TerminalStateSwitcher::Save(uint32_t idx, int fd, bool save_process_group) { const uint32_t num_states = GetNumberOfStates();
diff --git a/src/llvm-project/lldb/source/Host/common/ThreadLauncher.cpp b/src/llvm-project/lldb/source/Host/common/ThreadLauncher.cpp index f340101..6e3c8b6 100644 --- a/src/llvm-project/lldb/source/Host/common/ThreadLauncher.cpp +++ b/src/llvm-project/lldb/source/Host/common/ThreadLauncher.cpp
@@ -1,10 +1,8 @@ -//===-- ThreadLauncher.cpp ---------------------------------------*- C++ -//-*-===// +//===-- ThreadLauncher.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,18 +16,14 @@ #include "lldb/Host/windows/windows.h" #endif +#include "llvm/Support/WindowsError.h" + using namespace lldb; using namespace lldb_private; -HostThread ThreadLauncher::LaunchThread(llvm::StringRef name, - lldb::thread_func_t thread_function, - lldb::thread_arg_t thread_arg, - Status *error_ptr, - size_t min_stack_byte_size) { - Status error; - if (error_ptr) - error_ptr->Clear(); - +llvm::Expected<HostThread> ThreadLauncher::LaunchThread( + llvm::StringRef name, lldb::thread_func_t thread_function, + lldb::thread_arg_t thread_arg, size_t min_stack_byte_size) { // Host::ThreadCreateTrampoline will delete this pointer for us. HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo(name.data(), thread_function, thread_arg); @@ -38,8 +32,8 @@ thread = (lldb::thread_t)::_beginthreadex( 0, (unsigned)min_stack_byte_size, HostNativeThread::ThreadCreateTrampoline, info_ptr, 0, NULL); - if (thread == (lldb::thread_t)(-1L)) - error.SetError(::GetLastError(), eErrorTypeWin32); + if (thread == LLDB_INVALID_HOST_THREAD) + return llvm::errorCodeToError(llvm::mapWindowsError(GetLastError())); #else // ASAN instrumentation adds a lot of bookkeeping overhead on stack frames. @@ -50,7 +44,7 @@ } #endif - pthread_attr_t *thread_attr_ptr = NULL; + pthread_attr_t *thread_attr_ptr = nullptr; pthread_attr_t thread_attr; bool destroy_attr = false; if (min_stack_byte_size > 0) { @@ -74,12 +68,10 @@ if (destroy_attr) ::pthread_attr_destroy(&thread_attr); - error.SetError(err, eErrorTypePOSIX); + if (err) + return llvm::errorCodeToError( + std::error_code(err, std::generic_category())); #endif - if (error_ptr) - *error_ptr = error; - if (!error.Success()) - thread = LLDB_INVALID_HOST_THREAD; return HostThread(thread); }
diff --git a/src/llvm-project/lldb/source/Host/common/UDPSocket.cpp b/src/llvm-project/lldb/source/Host/common/UDPSocket.cpp index 96bcc6a..8dbf57d 100644 --- a/src/llvm-project/lldb/source/Host/common/UDPSocket.cpp +++ b/src/llvm-project/lldb/source/Host/common/UDPSocket.cpp
@@ -1,9 +1,8 @@ //===-- UDPSocket.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -135,3 +134,11 @@ error.Clear(); return error; } + +std::string UDPSocket::GetRemoteConnectionURI() const { + if (m_socket != kInvalidSocketValue) { + return llvm::formatv("udp://[{0}]:{1}", m_sockaddr.GetIPAddress(), + m_sockaddr.GetPort()); + } + return ""; +}
diff --git a/src/llvm-project/lldb/source/Host/common/XML.cpp b/src/llvm-project/lldb/source/Host/common/XML.cpp index 967a294..cb23ac1 100644 --- a/src/llvm-project/lldb/source/Host/common/XML.cpp +++ b/src/llvm-project/lldb/source/Host/common/XML.cpp
@@ -1,9 +1,8 @@ //===-- XML.cpp -------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -135,7 +134,7 @@ llvm::StringRef XMLNode::GetAttributeValue(const char *name, const char *fail_value) const { - const char *attr_value = NULL; + const char *attr_value = nullptr; #if defined(LIBXML2_DEFINED) if (IsValid())
diff --git a/src/llvm-project/lldb/source/Host/freebsd/Host.cpp b/src/llvm-project/lldb/source/Host/freebsd/Host.cpp index 7bf959a..99d728d 100644 --- a/src/llvm-project/lldb/source/Host/freebsd/Host.cpp +++ b/src/llvm-project/lldb/source/Host/freebsd/Host.cpp
@@ -1,10 +1,9 @@ //===-- source/Host/freebsd/Host.cpp ------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,12 +23,12 @@ #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/Process.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/NameMatches.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" @@ -39,6 +38,10 @@ extern char **environ; } +namespace lldb_private { +class ProcessLaunchInfo; +} + using namespace lldb; using namespace lldb_private;
diff --git a/src/llvm-project/lldb/source/Host/freebsd/HostInfoFreeBSD.cpp b/src/llvm-project/lldb/source/Host/freebsd/HostInfoFreeBSD.cpp index d123936..e28cf4a 100644 --- a/src/llvm-project/lldb/source/Host/freebsd/HostInfoFreeBSD.cpp +++ b/src/llvm-project/lldb/source/Host/freebsd/HostInfoFreeBSD.cpp
@@ -1,9 +1,8 @@ //===-- HostInfoFreeBSD.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/linux/AbstractSocket.cpp b/src/llvm-project/lldb/source/Host/linux/AbstractSocket.cpp index 2d6f6ad..5a47787 100644 --- a/src/llvm-project/lldb/source/Host/linux/AbstractSocket.cpp +++ b/src/llvm-project/lldb/source/Host/linux/AbstractSocket.cpp
@@ -1,9 +1,8 @@ //===-- AbstractSocket.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/linux/Host.cpp b/src/llvm-project/lldb/source/Host/linux/Host.cpp index bd596f8..f6a8766 100644 --- a/src/llvm-project/lldb/source/Host/linux/Host.cpp +++ b/src/llvm-project/lldb/source/Host/linux/Host.cpp
@@ -1,9 +1,8 @@ //===-- source/Host/linux/Host.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,8 +19,8 @@ #include "llvm/Object/ELF.h" #include "llvm/Support/ScopedPrinter.h" -#include "lldb/Target/Process.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Host/FileSystem.h" @@ -45,6 +44,10 @@ }; } +namespace lldb_private { +class ProcessLaunchInfo; +} + static bool GetStatusInfo(::pid_t Pid, ProcessInstanceInfo &ProcessInfo, ProcessState &State, ::pid_t &TracerPid) { auto BufferOrError = getProcFile(Pid, "status"); @@ -213,12 +216,12 @@ DIR *dirproc = opendir(procdir); if (dirproc) { - struct dirent *direntry = NULL; + struct dirent *direntry = nullptr; const uid_t our_uid = getuid(); const lldb::pid_t our_pid = getpid(); bool all_users = match_info.GetMatchAllUsers(); - while ((direntry = readdir(dirproc)) != NULL) { + while ((direntry = readdir(dirproc)) != nullptr) { if (direntry->d_type != DT_DIR || !IsDirNumeric(direntry->d_name)) continue; @@ -266,8 +269,8 @@ DIR *dirproc = opendir(process_task_dir.c_str()); if (dirproc) { - struct dirent *direntry = NULL; - while ((direntry = readdir(dirproc)) != NULL) { + struct dirent *direntry = nullptr; + while ((direntry = readdir(dirproc)) != nullptr) { if (direntry->d_type != DT_DIR || !IsDirNumeric(direntry->d_name)) continue;
diff --git a/src/llvm-project/lldb/source/Host/linux/HostInfoLinux.cpp b/src/llvm-project/lldb/source/Host/linux/HostInfoLinux.cpp index f5a6b2c..78dd77b 100644 --- a/src/llvm-project/lldb/source/Host/linux/HostInfoLinux.cpp +++ b/src/llvm-project/lldb/source/Host/linux/HostInfoLinux.cpp
@@ -1,9 +1,8 @@ //===-- HostInfoLinux.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -122,7 +121,8 @@ // retrieve the distribution id string. char distribution_id[256] = {'\0'}; - if (fgets(distribution_id, sizeof(distribution_id) - 1, file) != NULL) { + if (fgets(distribution_id, sizeof(distribution_id) - 1, file) != + nullptr) { if (log) log->Printf("distribution id command returned \"%s\"", distribution_id);
diff --git a/src/llvm-project/lldb/source/Host/linux/LibcGlue.cpp b/src/llvm-project/lldb/source/Host/linux/LibcGlue.cpp index 93d2a41..0acc206 100644 --- a/src/llvm-project/lldb/source/Host/linux/LibcGlue.cpp +++ b/src/llvm-project/lldb/source/Host/linux/LibcGlue.cpp
@@ -1,9 +1,8 @@ //===-- LibcGlue.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/linux/Support.cpp b/src/llvm-project/lldb/source/Host/linux/Support.cpp index 3180840..b9deb21 100644 --- a/src/llvm-project/lldb/source/Host/linux/Support.cpp +++ b/src/llvm-project/lldb/source/Host/linux/Support.cpp
@@ -1,9 +1,8 @@ //===-- Support.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.cpp b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.cpp index 08f1670..0ca2c00 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.cpp +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.cpp
@@ -1,18 +1,15 @@ //===-- CFCBundle.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "CFCBundle.h" #include "CFCString.h" -//---------------------------------------------------------------------- // CFCBundle constructor -//---------------------------------------------------------------------- CFCBundle::CFCBundle(const char *path) : CFCReleaser<CFBundleRef>() { if (path && path[0]) SetPath(path); @@ -21,14 +18,10 @@ CFCBundle::CFCBundle(CFURLRef url) : CFCReleaser<CFBundleRef>(url ? CFBundleCreate(NULL, url) : NULL) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFCBundle::~CFCBundle() {} -//---------------------------------------------------------------------- // Set the path for a bundle by supplying a -//---------------------------------------------------------------------- bool CFCBundle::SetPath(const char *path) { CFAllocatorRef alloc = kCFAllocatorDefault; // Release our old bundle and URL
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.h index 9506b93..014552a 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCBundle.h
@@ -1,9 +1,8 @@ //===-- CFCBundle.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ class CFCBundle : public CFCReleaser<CFBundleRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFCBundle(const char *path = NULL); CFCBundle(CFURLRef url); @@ -34,9 +31,9 @@ private: // Disallow copy and assignment constructors - CFCBundle(const CFCBundle &); + CFCBundle(const CFCBundle &) = delete; - const CFCBundle &operator=(const CFCBundle &); + const CFCBundle &operator=(const CFCBundle &) = delete; }; #endif // #ifndef CoreFoundationCPP_CFBundle_h_
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.cpp b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.cpp index 95caded..191f473 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.cpp +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.cpp
@@ -1,27 +1,20 @@ //===-- CFCData.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "CFCData.h" -//---------------------------------------------------------------------- // CFCData constructor -//---------------------------------------------------------------------- CFCData::CFCData(CFDataRef data) : CFCReleaser<CFDataRef>(data) {} -//---------------------------------------------------------------------- // CFCData copy constructor -//---------------------------------------------------------------------- CFCData::CFCData(const CFCData &rhs) : CFCReleaser<CFDataRef>(rhs) {} -//---------------------------------------------------------------------- // CFCData copy constructor -//---------------------------------------------------------------------- CFCData &CFCData::operator=(const CFCData &rhs) { @@ -30,9 +23,7 @@ return *this; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFCData::~CFCData() {} CFIndex CFCData::GetLength() const {
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.h index e89d7be..33fcf53 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCData.h
@@ -1,9 +1,8 @@ //===-- CFCData.h -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ class CFCData : public CFCReleaser<CFDataRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFCData(CFDataRef data = NULL); CFCData(const CFCData &rhs); CFCData &operator=(const CFCData &rhs); @@ -27,9 +24,7 @@ CFIndex GetLength() const; protected: - //------------------------------------------------------------------ // Classes that inherit from CFCData can see and modify these - //------------------------------------------------------------------ }; #endif // #ifndef CoreFoundationCPP_CFData_h_
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.cpp b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.cpp index f426e9c..a2172c2 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.cpp +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.cpp
@@ -1,33 +1,26 @@ //===-- CFCMutableArray.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "CFCMutableArray.h" #include "CFCString.h" -//---------------------------------------------------------------------- // CFCString constructor -//---------------------------------------------------------------------- CFCMutableArray::CFCMutableArray(CFMutableArrayRef s) : CFCReleaser<CFMutableArrayRef>(s) {} -//---------------------------------------------------------------------- // CFCMutableArray copy constructor -//---------------------------------------------------------------------- CFCMutableArray::CFCMutableArray(const CFCMutableArray &rhs) : CFCReleaser<CFMutableArrayRef>(rhs) // NOTE: this won't make a copy of the // array, just add a new reference to // it {} -//---------------------------------------------------------------------- // CFCMutableArray copy constructor -//---------------------------------------------------------------------- CFCMutableArray &CFCMutableArray::operator=(const CFCMutableArray &rhs) { if (this != &rhs) *this = rhs; // NOTE: this operator won't make a copy of the array, just add @@ -35,9 +28,7 @@ return *this; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFCMutableArray::~CFCMutableArray() {} CFIndex CFCMutableArray::GetCount() const {
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.h index 23d1f93..46c5b91 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableArray.h
@@ -1,9 +1,8 @@ //===-- CFCMutableArray.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ class CFCMutableArray : public CFCReleaser<CFMutableArrayRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFCMutableArray(CFMutableArrayRef array = NULL); CFCMutableArray(const CFCMutableArray &rhs); // This will copy the array // contents into a new array
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.cpp b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.cpp index 0c52aa3..66d572d 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.cpp +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.cpp
@@ -1,29 +1,22 @@ //===-- CFCMutableDictionary.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "CFCMutableDictionary.h" #include "CFCString.h" -//---------------------------------------------------------------------- // CFCString constructor -//---------------------------------------------------------------------- CFCMutableDictionary::CFCMutableDictionary(CFMutableDictionaryRef s) : CFCReleaser<CFMutableDictionaryRef>(s) {} -//---------------------------------------------------------------------- // CFCMutableDictionary copy constructor -//---------------------------------------------------------------------- CFCMutableDictionary::CFCMutableDictionary(const CFCMutableDictionary &rhs) : CFCReleaser<CFMutableDictionaryRef>(rhs) {} -//---------------------------------------------------------------------- // CFCMutableDictionary copy constructor -//---------------------------------------------------------------------- const CFCMutableDictionary &CFCMutableDictionary:: operator=(const CFCMutableDictionary &rhs) { if (this != &rhs) @@ -31,9 +24,7 @@ return *this; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFCMutableDictionary::~CFCMutableDictionary() {} CFIndex CFCMutableDictionary::GetCount() const {
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.h index b30a2e6..e9b494a 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableDictionary.h
@@ -1,9 +1,8 @@ //===-- CFCMutableDictionary.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,16 +13,12 @@ class CFCMutableDictionary : public CFCReleaser<CFMutableDictionaryRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFCMutableDictionary(CFMutableDictionaryRef s = NULL); CFCMutableDictionary(const CFCMutableDictionary &rhs); virtual ~CFCMutableDictionary(); - //------------------------------------------------------------------ // Operators - //------------------------------------------------------------------ const CFCMutableDictionary &operator=(const CFCMutableDictionary &rhs); CFIndex GetCount() const; @@ -62,14 +57,10 @@ CFMutableDictionaryRef Dictionary(bool can_create); protected: - //------------------------------------------------------------------ // Classes that inherit from CFCMutableDictionary can see and modify these - //------------------------------------------------------------------ private: - //------------------------------------------------------------------ // For CFCMutableDictionary only - //------------------------------------------------------------------ }; #endif // CoreFoundationCPP_CFMutableDictionary_h_
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.cpp b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.cpp index b8bf81e..a6517fa 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.cpp +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.cpp
@@ -1,39 +1,30 @@ //===-- CFCMutableSet.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "CFCMutableSet.h" -//---------------------------------------------------------------------- // CFCString constructor -//---------------------------------------------------------------------- CFCMutableSet::CFCMutableSet(CFMutableSetRef s) : CFCReleaser<CFMutableSetRef>(s) {} -//---------------------------------------------------------------------- // CFCMutableSet copy constructor -//---------------------------------------------------------------------- CFCMutableSet::CFCMutableSet(const CFCMutableSet &rhs) : CFCReleaser<CFMutableSetRef>(rhs) {} -//---------------------------------------------------------------------- // CFCMutableSet copy constructor -//---------------------------------------------------------------------- const CFCMutableSet &CFCMutableSet::operator=(const CFCMutableSet &rhs) { if (this != &rhs) *this = rhs; return *this; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFCMutableSet::~CFCMutableSet() {} CFIndex CFCMutableSet::GetCount() const {
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.h index 1459b7e..a55d646 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCMutableSet.h
@@ -1,9 +1,8 @@ //===-- CFCMutableSet.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,16 +13,12 @@ class CFCMutableSet : public CFCReleaser<CFMutableSetRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFCMutableSet(CFMutableSetRef s = NULL); CFCMutableSet(const CFCMutableSet &rhs); virtual ~CFCMutableSet(); - //------------------------------------------------------------------ // Operators - //------------------------------------------------------------------ const CFCMutableSet &operator=(const CFCMutableSet &rhs); CFIndex GetCount() const; @@ -34,14 +29,10 @@ void RemoveAllValues(); protected: - //------------------------------------------------------------------ // Classes that inherit from CFCMutableSet can see and modify these - //------------------------------------------------------------------ private: - //------------------------------------------------------------------ // For CFCMutableSet only - //------------------------------------------------------------------ }; #endif // CoreFoundationCPP_CFMutableSet_h_
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCReleaser.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCReleaser.h index c596d1e..8a29f39 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCReleaser.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCReleaser.h
@@ -1,9 +1,8 @@ //===-- CFCReleaser.h -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,7 +15,6 @@ #include <assert.h> -//---------------------------------------------------------------------- // Templatized CF helper class that can own any CF pointer and will // call CFRelease() on any valid pointer it owns unless that pointer is // explicitly released using the release() member function. This class @@ -25,42 +23,33 @@ // CFCReleaser<T>::release() function won't actually CFRelease any owned // pointer, it is designed to relinquish ownership of the pointer just // like std:auto_ptr<T>::release() does. -//---------------------------------------------------------------------- template <class T> class CFCReleaser { public: - //---------------------------------------------------------- // Constructor that takes a pointer to a CF object that is // to be released when this object goes out of scope - //---------------------------------------------------------- CFCReleaser(T ptr = NULL) : _ptr(ptr) {} - //---------------------------------------------------------- // Copy constructor // // Note that copying a CFCReleaser will not transfer // ownership of the contained pointer, but it will bump its // reference count. This is where this class differs from // std::auto_ptr. - //---------------------------------------------------------- CFCReleaser(const CFCReleaser &rhs) : _ptr(rhs.get()) { if (get()) ::CFRetain(get()); } - //---------------------------------------------------------- // The destructor will release the pointer that it contains // if it has a valid pointer. - //---------------------------------------------------------- virtual ~CFCReleaser() { reset(); } - //---------------------------------------------------------- // Assignment operator. // // Note that assigning one CFCReleaser to another will // not transfer ownership of the contained pointer, but it // will bump its reference count. This is where this class // differs from std::auto_ptr. - //---------------------------------------------------------- CFCReleaser &operator=(const CFCReleaser<T> &rhs) { if (this != &rhs) { // Replace our owned pointer with the new one @@ -72,7 +61,6 @@ return *this; } - //---------------------------------------------------------- // Get the address of the contained type in case it needs // to be passed to a function that will fill in a pointer // value. The function currently will assert if _ptr is not @@ -84,36 +72,29 @@ // sure any owned objects has CFRelease called on it. // I had to add the "enforce_null" bool here because some // API's require the pointer address even though they don't change it. - //---------------------------------------------------------- T *ptr_address(bool enforce_null = true) { if (enforce_null) assert(_ptr == NULL); return &_ptr; } - //---------------------------------------------------------- // Access the pointer itself - //---------------------------------------------------------- T get() { return _ptr; } const T get() const { return _ptr; } - //---------------------------------------------------------- // Set a new value for the pointer and CFRelease our old // value if we had a valid one. - //---------------------------------------------------------- void reset(T ptr = NULL) { if ((_ptr != NULL) && (ptr != _ptr)) ::CFRelease(_ptr); _ptr = ptr; } - //---------------------------------------------------------- // Release ownership without calling CFRelease. This class // is designed to mimic std::auto_ptr<T>, so the release // method releases ownership of the contained pointer // and does NOT call CFRelease. - //---------------------------------------------------------- T release() { T tmp = _ptr; _ptr = NULL;
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.cpp b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.cpp index 6191f87..fbd33fc 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.cpp +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.cpp
@@ -1,9 +1,8 @@ //===-- CFCString.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,19 +10,13 @@ #include <glob.h> #include <string> -//---------------------------------------------------------------------- // CFCString constructor -//---------------------------------------------------------------------- CFCString::CFCString(CFStringRef s) : CFCReleaser<CFStringRef>(s) {} -//---------------------------------------------------------------------- // CFCString copy constructor -//---------------------------------------------------------------------- CFCString::CFCString(const CFCString &rhs) : CFCReleaser<CFStringRef>(rhs) {} -//---------------------------------------------------------------------- // CFCString copy constructor -//---------------------------------------------------------------------- CFCString &CFCString::operator=(const CFCString &rhs) { if (this != &rhs) *this = rhs; @@ -38,9 +31,7 @@ } } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFCString::~CFCString() {} const char *CFCString::GetFileSystemRepresentation(std::string &s) {
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.h index a7bb029..300b1c4 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CFCString.h
@@ -1,9 +1,8 @@ //===-- CFCString.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ class CFCString : public CFCReleaser<CFStringRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFCString(CFStringRef cf_str = NULL); CFCString(const char *s, CFStringEncoding encoding = kCFStringEncodingUTF8); CFCString(const CFCString &rhs);
diff --git a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CoreFoundationCPP.h b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CoreFoundationCPP.h index 88d0f5a..0c2b82a 100644 --- a/src/llvm-project/lldb/source/Host/macosx/cfcpp/CoreFoundationCPP.h +++ b/src/llvm-project/lldb/source/Host/macosx/cfcpp/CoreFoundationCPP.h
@@ -1,12 +1,10 @@ //===-- CoreFoundationCPP.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// -//---------------------------------------------------------------------- // // CoreFoundationCPP.h // CoreFoundationCPP @@ -14,7 +12,6 @@ // Created by Greg Clayton on 4/23/09. // // -//---------------------------------------------------------------------- #ifndef CoreFoundationCPP_CoreFoundationCPP_H_ #define CoreFoundationCPP_CoreFoundationCPP_H_
diff --git a/src/llvm-project/lldb/source/Host/macosx/objcxx/CMakeLists.txt b/src/llvm-project/lldb/source/Host/macosx/objcxx/CMakeLists.txt index 77e3091..e55b094 100644 --- a/src/llvm-project/lldb/source/Host/macosx/objcxx/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Host/macosx/objcxx/CMakeLists.txt
@@ -8,13 +8,9 @@ HostThreadMacOSX.mm LINK_LIBS - lldbCore - lldbSymbol - lldbTarget lldbUtility ${EXTRA_LIBS} LINK_COMPONENTS - Object Support )
diff --git a/src/llvm-project/lldb/source/Host/macosx/objcxx/Host.mm b/src/llvm-project/lldb/source/Host/macosx/objcxx/Host.mm index 3cf44c4..12d7ba0 100644 --- a/src/llvm-project/lldb/source/Host/macosx/objcxx/Host.mm +++ b/src/llvm-project/lldb/source/Host/macosx/objcxx/Host.mm
@@ -1,9 +1,8 @@ //===-- Host.mm -------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -57,9 +56,8 @@ #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/HostInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Host/ThreadLauncher.h" -#include "lldb/Target/Process.h" -#include "lldb/Target/ProcessLaunchInfo.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/CleanUp.h" #include "lldb/Utility/DataBufferHeap.h" @@ -68,6 +66,7 @@ #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/NameMatches.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StructuredData.h" #include "lldb/lldb-defines.h" @@ -314,13 +313,16 @@ // in a shell and the shell will fork/exec a couple of times before we get // to the process that we wanted to launch. So when our process actually // gets launched, we will handshake with it and get the process ID for it. - HostThread accept_thread = ThreadLauncher::LaunchThread( - unix_socket_name, AcceptPIDFromInferior, connect_url, &lldb_error); + llvm::Expected<HostThread> accept_thread = ThreadLauncher::LaunchThread( + unix_socket_name, AcceptPIDFromInferior, connect_url); + + if (!accept_thread) + return Status(accept_thread.takeError()); [applescript executeAndReturnError:nil]; thread_result_t accept_thread_result = NULL; - lldb_error = accept_thread.Join(&accept_thread_result); + lldb_error = accept_thread->Join(&accept_thread_result); if (lldb_error.Success() && accept_thread_result) { pid = (intptr_t)accept_thread_result; @@ -548,7 +550,7 @@ match_info_ptr->GetNameMatchType(), match_info_ptr->GetProcessInfo().GetName())) { // Skip NULLs - while (1) { + while (true) { const uint8_t *p = data.PeekData(offset, 1); if ((p == NULL) || (*p != '\0')) break; @@ -1300,12 +1302,15 @@ lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; - if (ShouldLaunchUsingXPC(launch_info)) { - error = LaunchProcessXPC(exe_spec.GetPath().c_str(), launch_info, pid); - } else { - error = - LaunchProcessPosixSpawn(exe_spec.GetPath().c_str(), launch_info, pid); - } + // From now on we'll deal with the external (devirtualized) path. + auto exe_path = fs.GetExternalPath(exe_spec); + if (!exe_path) + return Status(exe_path.getError()); + + if (ShouldLaunchUsingXPC(launch_info)) + error = LaunchProcessXPC(exe_path->c_str(), launch_info, pid); + else + error = LaunchProcessPosixSpawn(exe_path->c_str(), launch_info, pid); if (pid != LLDB_INVALID_PROCESS_ID) { // If all went well, then set the process ID into the launch info @@ -1362,8 +1367,11 @@ launch_info.SetWorkingDirectory(working_dir); } } + bool run_in_default_shell = true; + bool hide_stderr = true; RunShellCommand(expand_command, cwd, &status, nullptr, &output, - std::chrono::seconds(10)); + std::chrono::seconds(10), run_in_default_shell, + hide_stderr); if (status != 0) { error.SetErrorStringWithFormat("lldb-argdumper exited with error %d", @@ -1412,7 +1420,7 @@ return error; } -HostThread Host::StartMonitoringChildProcess( +llvm::Expected<HostThread> Host::StartMonitoringChildProcess( const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid, bool monitor_signals) { unsigned long mask = DISPATCH_PROC_EXIT;
diff --git a/src/llvm-project/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm b/src/llvm-project/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm index 165e87e..f13cd9d 100644 --- a/src/llvm-project/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm +++ b/src/llvm-project/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
@@ -1,9 +1,8 @@ //===-- HostInfoMacOSX.mm ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/macosx/objcxx/HostThreadMacOSX.mm b/src/llvm-project/lldb/source/Host/macosx/objcxx/HostThreadMacOSX.mm index c5051cd..d9f32ca 100644 --- a/src/llvm-project/lldb/source/Host/macosx/objcxx/HostThreadMacOSX.mm +++ b/src/llvm-project/lldb/source/Host/macosx/objcxx/HostThreadMacOSX.mm
@@ -1,9 +1,8 @@ //===-- HostThreadMacOSX.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/netbsd/Host.cpp b/src/llvm-project/lldb/source/Host/netbsd/Host.cpp index 4d50363..08fec09 100644 --- a/src/llvm-project/lldb/source/Host/netbsd/Host.cpp +++ b/src/llvm-project/lldb/source/Host/netbsd/Host.cpp
@@ -1,9 +1,8 @@ //===-- source/Host/netbsd/Host.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,12 +22,12 @@ #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/Process.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/NameMatches.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" @@ -41,6 +40,10 @@ using namespace lldb; using namespace lldb_private; +namespace lldb_private { +class ProcessLaunchInfo; +} + Environment Host::GetEnvironment() { return Environment(environ); } static bool GetNetBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr,
diff --git a/src/llvm-project/lldb/source/Host/netbsd/HostInfoNetBSD.cpp b/src/llvm-project/lldb/source/Host/netbsd/HostInfoNetBSD.cpp index a54483f..99d4139 100644 --- a/src/llvm-project/lldb/source/Host/netbsd/HostInfoNetBSD.cpp +++ b/src/llvm-project/lldb/source/Host/netbsd/HostInfoNetBSD.cpp
@@ -1,9 +1,8 @@ //===-- HostInfoNetBSD.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/openbsd/Host.cpp b/src/llvm-project/lldb/source/Host/openbsd/Host.cpp index 8db0498..ba6cf05 100644 --- a/src/llvm-project/lldb/source/Host/openbsd/Host.cpp +++ b/src/llvm-project/lldb/source/Host/openbsd/Host.cpp
@@ -1,9 +1,8 @@ //===-- source/Host/openbsd/Host.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,12 +19,12 @@ #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/Process.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/NameMatches.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" @@ -38,6 +37,10 @@ using namespace lldb; using namespace lldb_private; +namespace lldb_private { +class ProcessLaunchInfo; +} + Environment Host::GetEnvironment() { Environment env; char *v;
diff --git a/src/llvm-project/lldb/source/Host/openbsd/HostInfoOpenBSD.cpp b/src/llvm-project/lldb/source/Host/openbsd/HostInfoOpenBSD.cpp index cf7acb7..950f2eb 100644 --- a/src/llvm-project/lldb/source/Host/openbsd/HostInfoOpenBSD.cpp +++ b/src/llvm-project/lldb/source/Host/openbsd/HostInfoOpenBSD.cpp
@@ -1,9 +1,8 @@ //===-- HostInfoOpenBSD.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp b/src/llvm-project/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp index deac384..067e859 100644 --- a/src/llvm-project/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp +++ b/src/llvm-project/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp
@@ -1,9 +1,8 @@ //===-- ConnectionFileDescriptorPosix.cpp -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,6 +31,7 @@ #include <unistd.h> #endif +#include <memory> #include <sstream> #include "llvm/Support/Errno.h" @@ -87,8 +87,8 @@ ConnectionFileDescriptor::ConnectionFileDescriptor(int fd, bool owns_fd) : Connection(), m_pipe(), m_mutex(), m_shutting_down(false), m_waiting_for_accept(false), m_child_processes_inherit(false) { - m_write_sp.reset(new File(fd, owns_fd)); - m_read_sp.reset(new File(fd, false)); + m_write_sp = std::make_shared<File>(fd, owns_fd); + m_read_sp = std::make_shared<File>(fd, false); Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT)); @@ -111,7 +111,7 @@ if (log) log->Printf("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", static_cast<void *>(this)); - Disconnect(NULL); + Disconnect(nullptr); CloseCommandPipe(); } @@ -222,8 +222,8 @@ m_read_sp = std::move(tcp_socket); m_write_sp = m_read_sp; } else { - m_read_sp.reset(new File(fd, false)); - m_write_sp.reset(new File(fd, false)); + m_read_sp = std::make_shared<File>(fd, false); + m_write_sp = std::make_shared<File>(fd, false); } m_uri = *addr; return eConnectionStatusSuccess; @@ -262,7 +262,7 @@ options.c_cc[VMIN] = 1; options.c_cc[VTIME] = 0; - ::tcsetattr(fd, TCSANOW, &options); + llvm::sys::RetryAfterSignal(-1, ::tcsetattr, fd, TCSANOW, &options); } int flags = ::fcntl(fd, F_GETFL, 0); @@ -272,8 +272,8 @@ ::fcntl(fd, F_SETFL, flags); } } - m_read_sp.reset(new File(fd, true)); - m_write_sp.reset(new File(fd, false)); + m_read_sp = std::make_shared<File>(fd, true); + m_write_sp = std::make_shared<File>(fd, false); return eConnectionStatusSuccess; } #endif @@ -758,13 +758,7 @@ } void ConnectionFileDescriptor::InitializeSocket(Socket *socket) { - assert(socket->GetSocketProtocol() == Socket::ProtocolTcp); - TCPSocket *tcp_socket = static_cast<TCPSocket *>(socket); - m_write_sp.reset(socket); m_read_sp = m_write_sp; - StreamString strm; - strm.Printf("connect://%s:%u", tcp_socket->GetRemoteIPAddress().c_str(), - tcp_socket->GetRemotePortNumber()); - m_uri = strm.GetString(); + m_uri = socket->GetRemoteConnectionURI(); }
diff --git a/src/llvm-project/lldb/source/Host/posix/DomainSocket.cpp b/src/llvm-project/lldb/source/Host/posix/DomainSocket.cpp index 3e3abad..27872f4 100644 --- a/src/llvm-project/lldb/source/Host/posix/DomainSocket.cpp +++ b/src/llvm-project/lldb/source/Host/posix/DomainSocket.cpp
@@ -1,14 +1,14 @@ //===-- DomainSocket.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/posix/DomainSocket.h" +#include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #include <stddef.h> @@ -82,8 +82,8 @@ m_socket = CreateSocket(kDomain, kType, 0, m_child_processes_inherit, error); if (error.Fail()) return error; - if (::connect(GetNativeSocket(), (struct sockaddr *)&saddr_un, saddr_un_len) < - 0) + if (llvm::sys::RetryAfterSignal(-1, ::connect, GetNativeSocket(), + (struct sockaddr *)&saddr_un, saddr_un_len) < 0) SetLastError(error); return error; @@ -125,3 +125,31 @@ void DomainSocket::DeleteSocketFile(llvm::StringRef name) { llvm::sys::fs::remove(name); } + +std::string DomainSocket::GetSocketName() const { + if (m_socket != kInvalidSocketValue) { + struct sockaddr_un saddr_un; + saddr_un.sun_family = AF_UNIX; + socklen_t sock_addr_len = sizeof(struct sockaddr_un); + if (::getpeername(m_socket, (struct sockaddr *)&saddr_un, &sock_addr_len) == + 0) { + std::string name(saddr_un.sun_path + GetNameOffset(), + sock_addr_len - + offsetof(struct sockaddr_un, sun_path) - + GetNameOffset()); + if (name.back() == '\0') name.pop_back(); + return name; + } + } + return ""; +} + +std::string DomainSocket::GetRemoteConnectionURI() const { + if (m_socket != kInvalidSocketValue) { + return llvm::formatv("{0}://{1}", + GetNameOffset() == 0 ? "unix-connect" + : "unix-abstract-connect", + GetSocketName()); + } + return ""; +}
diff --git a/src/llvm-project/lldb/source/Host/posix/FileSystem.cpp b/src/llvm-project/lldb/source/Host/posix/FileSystem.cpp index d7045ff..32fae68 100644 --- a/src/llvm-project/lldb/source/Host/posix/FileSystem.cpp +++ b/src/llvm-project/lldb/source/Host/posix/FileSystem.cpp
@@ -1,9 +1,8 @@ //===-- FileSystem.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,6 +25,7 @@ #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" +#include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" using namespace lldb; @@ -72,9 +72,9 @@ } FILE *FileSystem::Fopen(const char *path, const char *mode) { - return ::fopen(path, mode); + return llvm::sys::RetryAfterSignal(nullptr, ::fopen, path, mode); } int FileSystem::Open(const char *path, int flags, int mode) { - return ::open(path, flags, mode); + return llvm::sys::RetryAfterSignal(-1, ::open, path, flags, mode); }
diff --git a/src/llvm-project/lldb/source/Host/posix/HostInfoPosix.cpp b/src/llvm-project/lldb/source/Host/posix/HostInfoPosix.cpp index 4763ebc..f300e22 100644 --- a/src/llvm-project/lldb/source/Host/posix/HostInfoPosix.cpp +++ b/src/llvm-project/lldb/source/Host/posix/HostInfoPosix.cpp
@@ -1,13 +1,13 @@ //===-- HostInfoPosix.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/posix/HostInfoPosix.h" +#include "lldb/Utility/UserIDResolver.h" #include "lldb/Utility/Log.h" #include "llvm/ADT/SmallString.h" @@ -49,40 +49,38 @@ #define USE_GETPWUID #endif -#ifdef USE_GETPWUID -static std::mutex s_getpwuid_lock; -#endif +namespace { +class PosixUserIDResolver : public UserIDResolver { +protected: + llvm::Optional<std::string> DoGetUserName(id_t uid) override; + llvm::Optional<std::string> DoGetGroupName(id_t gid) override; +}; +} // namespace -const char *HostInfoPosix::LookupUserName(uint32_t uid, - std::string &user_name) { +llvm::Optional<std::string> PosixUserIDResolver::DoGetUserName(id_t uid) { #ifdef USE_GETPWUID // getpwuid_r is missing from android-9 - // make getpwuid thread safe with a mutex - std::lock_guard<std::mutex> lock(s_getpwuid_lock); + // UserIDResolver provides some thread safety by making sure noone calls this + // function concurrently, but using getpwuid is ultimately not thread-safe as + // we don't know who else might be calling it. struct passwd *user_info_ptr = ::getpwuid(uid); - if (user_info_ptr) { - user_name.assign(user_info_ptr->pw_name); - return user_name.c_str(); - } + if (user_info_ptr) + return std::string(user_info_ptr->pw_name); #else struct passwd user_info; struct passwd *user_info_ptr = &user_info; char user_buffer[PATH_MAX]; size_t user_buffer_size = sizeof(user_buffer); if (::getpwuid_r(uid, &user_info, user_buffer, user_buffer_size, - &user_info_ptr) == 0) { - if (user_info_ptr) { - user_name.assign(user_info_ptr->pw_name); - return user_name.c_str(); - } + &user_info_ptr) == 0 && + user_info_ptr) { + return std::string(user_info_ptr->pw_name); } #endif - user_name.clear(); - return nullptr; + return llvm::None; } -const char *HostInfoPosix::LookupGroupName(uint32_t gid, - std::string &group_name) { +llvm::Optional<std::string> PosixUserIDResolver::DoGetGroupName(id_t gid) { #ifndef __ANDROID__ char group_buffer[PATH_MAX]; size_t group_buffer_size = sizeof(group_buffer); @@ -91,24 +89,25 @@ // Try the threadsafe version first if (::getgrgid_r(gid, &group_info, group_buffer, group_buffer_size, &group_info_ptr) == 0) { - if (group_info_ptr) { - group_name.assign(group_info_ptr->gr_name); - return group_name.c_str(); - } + if (group_info_ptr) + return std::string(group_info_ptr->gr_name); } else { // The threadsafe version isn't currently working for me on darwin, but the // non-threadsafe version is, so I am calling it below. group_info_ptr = ::getgrgid(gid); - if (group_info_ptr) { - group_name.assign(group_info_ptr->gr_name); - return group_name.c_str(); - } + if (group_info_ptr) + return std::string(group_info_ptr->gr_name); } - group_name.clear(); #else assert(false && "getgrgid_r() not supported on Android"); #endif - return NULL; + return llvm::None; +} + +static llvm::ManagedStatic<PosixUserIDResolver> g_user_id_resolver; + +UserIDResolver &HostInfoPosix::GetUserIDResolver() { + return *g_user_id_resolver; } uint32_t HostInfoPosix::GetUserID() { return getuid(); } @@ -121,43 +120,6 @@ FileSpec HostInfoPosix::GetDefaultShell() { return FileSpec("/bin/sh"); } -bool HostInfoPosix::ComputePathRelativeToLibrary(FileSpec &file_spec, - llvm::StringRef dir) { - Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); - - FileSpec lldb_file_spec = GetShlibDir(); - if (!lldb_file_spec) - return false; - - std::string raw_path = lldb_file_spec.GetPath(); - // drop library directory - llvm::StringRef parent_path = llvm::sys::path::parent_path(raw_path); - - // Most Posix systems (e.g. Linux/*BSD) will attempt to replace a */lib with - // */bin as the base directory for helper exe programs. This will fail if - // the /lib and /bin directories are rooted in entirely different trees. - if (log) - log->Printf("HostInfoPosix::ComputePathRelativeToLibrary() attempting to " - "derive the %s path from this path: %s", - dir.data(), raw_path.c_str()); - - if (!parent_path.empty()) { - // Now write in bin in place of lib. - raw_path = (parent_path + dir).str(); - - if (log) - log->Printf("Host::%s() derived the bin path as: %s", __FUNCTION__, - raw_path.c_str()); - } else { - if (log) - log->Printf("Host::%s() failed to find /lib/liblldb within the shared " - "lib path, bailing on bin path construction", - __FUNCTION__); - } - file_spec.GetDirectory().SetString(raw_path); - return (bool)file_spec.GetDirectory(); -} - bool HostInfoPosix::ComputeSupportExeDirectory(FileSpec &file_spec) { return ComputePathRelativeToLibrary(file_spec, "/bin"); }
diff --git a/src/llvm-project/lldb/source/Host/posix/HostProcessPosix.cpp b/src/llvm-project/lldb/source/Host/posix/HostProcessPosix.cpp index f431e0c..cc187d4 100644 --- a/src/llvm-project/lldb/source/Host/posix/HostProcessPosix.cpp +++ b/src/llvm-project/lldb/source/Host/posix/HostProcessPosix.cpp
@@ -1,9 +1,8 @@ //===-- HostProcessPosix.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -88,7 +87,7 @@ return error.Success(); } -HostThread HostProcessPosix::StartMonitoring( +llvm::Expected<HostThread> HostProcessPosix::StartMonitoring( const Host::MonitorChildProcessCallback &callback, bool monitor_signals) { return Host::StartMonitoringChildProcess(callback, m_process, monitor_signals);
diff --git a/src/llvm-project/lldb/source/Host/posix/HostThreadPosix.cpp b/src/llvm-project/lldb/source/Host/posix/HostThreadPosix.cpp index 13de42f..d78bba5 100644 --- a/src/llvm-project/lldb/source/Host/posix/HostThreadPosix.cpp +++ b/src/llvm-project/lldb/source/Host/posix/HostThreadPosix.cpp
@@ -1,9 +1,8 @@ //===-- HostThreadPosix.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,7 +29,7 @@ error.SetError(err, lldb::eErrorTypePOSIX); } else { if (result) - *result = NULL; + *result = nullptr; error.SetError(EINVAL, eErrorTypePOSIX); }
diff --git a/src/llvm-project/lldb/source/Host/posix/LockFilePosix.cpp b/src/llvm-project/lldb/source/Host/posix/LockFilePosix.cpp index 0542306..a6eae95 100644 --- a/src/llvm-project/lldb/source/Host/posix/LockFilePosix.cpp +++ b/src/llvm-project/lldb/source/Host/posix/LockFilePosix.cpp
@@ -1,14 +1,15 @@ //===-- LockFilePosix.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/posix/LockFilePosix.h" +#include "llvm/Support/Errno.h" + #include <fcntl.h> #include <unistd.h> @@ -28,7 +29,7 @@ fl.l_pid = ::getpid(); Status error; - if (::fcntl(fd, cmd, &fl) == -1) + if (llvm::sys::RetryAfterSignal(-1, ::fcntl, fd, cmd, &fl) == -1) error.SetErrorToErrno(); return error;
diff --git a/src/llvm-project/lldb/source/Host/posix/PipePosix.cpp b/src/llvm-project/lldb/source/Host/posix/PipePosix.cpp index 866a989..efdc151 100644 --- a/src/llvm-project/lldb/source/Host/posix/PipePosix.cpp +++ b/src/llvm-project/lldb/source/Host/posix/PipePosix.cpp
@@ -1,9 +1,8 @@ //===-- PipePosix.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,6 +10,7 @@ #include "lldb/Host/HostInfo.h" #include "lldb/Utility/SelectHelper.h" #include "llvm/ADT/SmallString.h" +#include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) @@ -158,7 +158,7 @@ flags |= O_CLOEXEC; Status error; - int fd = ::open(name.data(), flags); + int fd = llvm::sys::RetryAfterSignal(-1, ::open, name.data(), flags); if (fd != -1) m_fds[READ] = fd; else @@ -193,7 +193,7 @@ if (fd == -1) { const auto errno_copy = errno; // We may get ENXIO if a reader side of the pipe hasn't opened yet. - if (errno_copy != ENXIO) + if (errno_copy != ENXIO && errno_copy != EINTR) return Status(errno_copy, eErrorTypePOSIX); std::this_thread::sleep_for( @@ -276,6 +276,8 @@ bytes_read += result; if (bytes_read == size || result == 0) break; + } else if (errno == EINTR) { + continue; } else { error.SetErrorToErrno(); break; @@ -306,6 +308,8 @@ bytes_written += result; if (bytes_written == size) break; + } else if (errno == EINTR) { + continue; } else { error.SetErrorToErrno(); }
diff --git a/src/llvm-project/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp b/src/llvm-project/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp index 6bf7846..185c7f0 100644 --- a/src/llvm-project/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp +++ b/src/llvm-project/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp
@@ -1,9 +1,8 @@ -//===-- ProcessLauncherLinux.cpp --------------------------------*- C++ -*-===// +//===-- ProcessLauncherPosixFork.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,7 +10,7 @@ #include "lldb/Host/Host.h" #include "lldb/Host/HostProcess.h" #include "lldb/Host/Pipe.h" -#include "lldb/Target/ProcessLaunchInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "llvm/Support/Errno.h" @@ -73,7 +72,8 @@ static void DupDescriptor(int error_fd, const FileSpec &file_spec, int fd, int flags) { - int target_fd = ::open(file_spec.GetCString(), flags, 0666); + int target_fd = llvm::sys::RetryAfterSignal(-1, ::open, + file_spec.GetCString(), flags, 0666); if (target_fd == -1) ExitWithError(error_fd, "DupDescriptor-open"); @@ -212,7 +212,7 @@ error.SetErrorString(buf); - waitpid(pid, nullptr, 0); + llvm::sys::RetryAfterSignal(-1, waitpid, pid, nullptr, 0); return HostProcess(); }
diff --git a/src/llvm-project/lldb/source/Host/windows/ConnectionGenericFileWindows.cpp b/src/llvm-project/lldb/source/Host/windows/ConnectionGenericFileWindows.cpp index e59e190..66cb59d 100644 --- a/src/llvm-project/lldb/source/Host/windows/ConnectionGenericFileWindows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/ConnectionGenericFileWindows.cpp
@@ -1,9 +1,8 @@ //===-- ConnectionGenericFileWindows.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/windows/EditLineWin.cpp b/src/llvm-project/lldb/source/Host/windows/EditLineWin.cpp index 3bccc4e..67a7d54 100644 --- a/src/llvm-project/lldb/source/Host/windows/EditLineWin.cpp +++ b/src/llvm-project/lldb/source/Host/windows/EditLineWin.cpp
@@ -1,9 +1,8 @@ //===-- EditLineWin.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/windows/FileSystem.cpp b/src/llvm-project/lldb/source/Host/windows/FileSystem.cpp index 3217cdc..04dba44 100644 --- a/src/llvm-project/lldb/source/Host/windows/FileSystem.cpp +++ b/src/llvm-project/lldb/source/Host/windows/FileSystem.cpp
@@ -1,9 +1,8 @@ //===-- FileSystem.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/windows/Host.cpp b/src/llvm-project/lldb/source/Host/windows/Host.cpp index 3ac16a4..413b172 100644 --- a/src/llvm-project/lldb/source/Host/windows/Host.cpp +++ b/src/llvm-project/lldb/source/Host/windows/Host.cpp
@@ -1,9 +1,8 @@ //===-- source/Host/windows/Host.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,11 +13,13 @@ #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/Process.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" +#include "lldb/Utility/StreamString.h" #include "lldb/Utility/StructuredData.h" #include "llvm/Support/ConvertUTF.h" @@ -171,7 +172,7 @@ return true; } -HostThread Host::StartMonitoringChildProcess( +llvm::Expected<HostThread> Host::StartMonitoringChildProcess( const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid, bool monitor_signals) { return HostThread();
diff --git a/src/llvm-project/lldb/source/Host/windows/HostInfoWindows.cpp b/src/llvm-project/lldb/source/Host/windows/HostInfoWindows.cpp index 81392d9..459703f 100644 --- a/src/llvm-project/lldb/source/Host/windows/HostInfoWindows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/HostInfoWindows.cpp
@@ -1,9 +1,8 @@ //===-- HostInfoWindows.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,15 +14,29 @@ #include "lldb/Host/windows/HostInfoWindows.h" #include "lldb/Host/windows/PosixApi.h" +#include "lldb/Utility/UserIDResolver.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/FileSystem.h" +#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/Threading.h" #include "llvm/Support/raw_ostream.h" using namespace lldb_private; +namespace { +class WindowsUserIDResolver : public UserIDResolver { +protected: + llvm::Optional<std::string> DoGetUserName(id_t uid) override { + return llvm::None; + } + llvm::Optional<std::string> DoGetGroupName(id_t gid) override { + return llvm::None; + } +}; +} // namespace + FileSpec HostInfoWindows::m_program_filespec; void HostInfoWindows::Initialize() { @@ -82,6 +95,8 @@ if (!::GetComputerNameW(buffer, &dwSize)) return false; + // The conversion requires an empty string. + s.clear(); return llvm::convertWideToUTF8(buffer, s); } @@ -118,3 +133,9 @@ return llvm::convertWideToUTF8(wvar, var); return false; } + +static llvm::ManagedStatic<WindowsUserIDResolver> g_user_id_resolver; + +UserIDResolver &HostInfoWindows::GetUserIDResolver() { + return *g_user_id_resolver; +}
diff --git a/src/llvm-project/lldb/source/Host/windows/HostProcessWindows.cpp b/src/llvm-project/lldb/source/Host/windows/HostProcessWindows.cpp index 701167f..9051724 100644 --- a/src/llvm-project/lldb/source/Host/windows/HostProcessWindows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/HostProcessWindows.cpp
@@ -1,9 +1,8 @@ //===-- HostProcessWindows.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,6 +14,7 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/Support/ConvertUTF.h" +#include "llvm/Support/WindowsError.h" #include <psapi.h> @@ -81,22 +81,22 @@ return (code == STILL_ACTIVE); } -HostThread HostProcessWindows::StartMonitoring( +llvm::Expected<HostThread> HostProcessWindows::StartMonitoring( const Host::MonitorChildProcessCallback &callback, bool monitor_signals) { - HostThread monitor_thread; MonitorInfo *info = new MonitorInfo; info->callback = callback; // Since the life of this HostProcessWindows instance and the life of the // process may be different, duplicate the handle so that the monitor thread // can have ownership over its own copy of the handle. - HostThread result; if (::DuplicateHandle(GetCurrentProcess(), m_process, GetCurrentProcess(), - &info->process_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) - result = ThreadLauncher::LaunchThread("ChildProcessMonitor", - HostProcessWindows::MonitorThread, - info, nullptr); - return result; + &info->process_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) { + return ThreadLauncher::LaunchThread("ChildProcessMonitor", + HostProcessWindows::MonitorThread, + info); + } else { + return llvm::errorCodeToError(llvm::mapWindowsError(GetLastError())); + } } lldb::thread_result_t HostProcessWindows::MonitorThread(void *thread_arg) { @@ -110,7 +110,7 @@ ::CloseHandle(info->process_handle); delete (info); } - return 0; + return {}; } void HostProcessWindows::Close() {
diff --git a/src/llvm-project/lldb/source/Host/windows/HostThreadWindows.cpp b/src/llvm-project/lldb/source/Host/windows/HostThreadWindows.cpp index b516230..3eaaee2 100644 --- a/src/llvm-project/lldb/source/Host/windows/HostThreadWindows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/HostThreadWindows.cpp
@@ -1,9 +1,8 @@ //===-- HostThreadWindows.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/windows/LockFileWindows.cpp b/src/llvm-project/lldb/source/Host/windows/LockFileWindows.cpp index 2178fd1..6b82796 100644 --- a/src/llvm-project/lldb/source/Host/windows/LockFileWindows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/LockFileWindows.cpp
@@ -1,9 +1,8 @@ //===-- LockFileWindows.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/windows/PipeWindows.cpp b/src/llvm-project/lldb/source/Host/windows/PipeWindows.cpp index 57221a7..920e5a1 100644 --- a/src/llvm-project/lldb/source/Host/windows/PipeWindows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/PipeWindows.cpp
@@ -1,9 +1,8 @@ //===-- PipeWindows.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/windows/ProcessLauncherWindows.cpp b/src/llvm-project/lldb/source/Host/windows/ProcessLauncherWindows.cpp index a186c71..3f5c637 100644 --- a/src/llvm-project/lldb/source/Host/windows/ProcessLauncherWindows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/ProcessLauncherWindows.cpp
@@ -1,18 +1,18 @@ //===-- ProcessLauncherWindows.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/windows/ProcessLauncherWindows.h" #include "lldb/Host/HostProcess.h" -#include "lldb/Target/ProcessLaunchInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/ConvertUTF.h" +#include "llvm/Support/Program.h" #include <string> #include <vector> @@ -30,15 +30,28 @@ for (const auto &KV : env) { std::wstring warg; if (llvm::ConvertUTF8toWide(Environment::compose(KV), warg)) { - buffer.insert(buffer.end(), (char *)warg.c_str(), - (char *)(warg.c_str() + warg.size() + 1)); + buffer.insert( + buffer.end(), reinterpret_cast<const char *>(warg.c_str()), + reinterpret_cast<const char *>(warg.c_str() + warg.size() + 1)); } } // One null wchar_t (to end the block) is two null bytes buffer.push_back(0); buffer.push_back(0); } + +bool GetFlattenedWindowsCommandString(Args args, std::string &command) { + if (args.empty()) + return false; + + std::vector<llvm::StringRef> args_ref; + for (auto &entry : args.entries()) + args_ref.push_back(entry.ref); + + command = llvm::sys::flattenWindowsCommandLine(args_ref); + return true; } +} // namespace HostProcess ProcessLauncherWindows::LaunchProcess(const ProcessLaunchInfo &launch_info, @@ -85,24 +98,28 @@ env_block = environment.data(); executable = launch_info.GetExecutableFile().GetPath(); - launch_info.GetArguments().GetQuotedCommandString(commandLine); + GetFlattenedWindowsCommandString(launch_info.GetArguments(), commandLine); std::wstring wexecutable, wcommandLine, wworkingDirectory; llvm::ConvertUTF8toWide(executable, wexecutable); llvm::ConvertUTF8toWide(commandLine, wcommandLine); llvm::ConvertUTF8toWide(launch_info.GetWorkingDirectory().GetCString(), wworkingDirectory); + // If the command line is empty, it's best to pass a null pointer to tell + // CreateProcessW to use the executable name as the command line. If the + // command line is not empty, its contents may be modified by CreateProcessW. + WCHAR *pwcommandLine = wcommandLine.empty() ? nullptr : &wcommandLine[0]; - wcommandLine.resize(PATH_MAX); // Needs to be over-allocated because - // CreateProcessW can modify it BOOL result = ::CreateProcessW( - wexecutable.c_str(), &wcommandLine[0], NULL, NULL, TRUE, flags, env_block, + wexecutable.c_str(), pwcommandLine, NULL, NULL, TRUE, flags, env_block, wworkingDirectory.size() == 0 ? NULL : wworkingDirectory.c_str(), &startupinfo, &pi); if (!result) { // Call GetLastError before we make any other system calls. error.SetError(::GetLastError(), eErrorTypeWin32); + // Note that error 50 ("The request is not supported") will occur if you + // try debug a 64-bit inferior from a 32-bit LLDB. } if (result) {
diff --git a/src/llvm-project/lldb/source/Host/windows/ProcessRunLock.cpp b/src/llvm-project/lldb/source/Host/windows/ProcessRunLock.cpp index 6427691..85df782 100644 --- a/src/llvm-project/lldb/source/Host/windows/ProcessRunLock.cpp +++ b/src/llvm-project/lldb/source/Host/windows/ProcessRunLock.cpp
@@ -1,9 +1,8 @@ //===-- ProcessRunLock.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Host/windows/Windows.cpp b/src/llvm-project/lldb/source/Host/windows/Windows.cpp index 9d0e70e..c52f5c1 100644 --- a/src/llvm-project/lldb/source/Host/windows/Windows.cpp +++ b/src/llvm-project/lldb/source/Host/windows/Windows.cpp
@@ -1,9 +1,8 @@ //===-- Windows.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -85,7 +84,7 @@ } while (strncasecmp(s, find, len) != 0); s--; } - return ((char *)s); + return const_cast<char *>(s); } char *realpath(const char *name, char *resolved) {
diff --git a/src/llvm-project/lldb/source/Initialization/CMakeLists.txt b/src/llvm-project/lldb/source/Initialization/CMakeLists.txt index f8ee7c6..c1a1678 100644 --- a/src/llvm-project/lldb/source/Initialization/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Initialization/CMakeLists.txt
@@ -14,11 +14,6 @@ LINK_LIBS lldbCore lldbHost - lldbPluginInstructionARM - lldbPluginInstructionMIPS - lldbPluginInstructionMIPS64 - lldbPluginObjectContainerBSDArchive - lldbPluginObjectContainerMachOArchive lldbPluginProcessGDBRemote ${EXTRA_PLUGINS} ${LLDB_SYSTEM_LIBS}
diff --git a/src/llvm-project/lldb/source/Initialization/SystemInitializer.cpp b/src/llvm-project/lldb/source/Initialization/SystemInitializer.cpp index 4a8e10c..1e40c269 100644 --- a/src/llvm-project/lldb/source/Initialization/SystemInitializer.cpp +++ b/src/llvm-project/lldb/source/Initialization/SystemInitializer.cpp
@@ -1,9 +1,8 @@ //===-- SystemInitializer.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Initialization/SystemInitializerCommon.cpp b/src/llvm-project/lldb/source/Initialization/SystemInitializerCommon.cpp index d1d55fc..8558911 100644 --- a/src/llvm-project/lldb/source/Initialization/SystemInitializerCommon.cpp +++ b/src/llvm-project/lldb/source/Initialization/SystemInitializerCommon.cpp
@@ -1,32 +1,28 @@ //===-- SystemInitializerCommon.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Initialization/SystemInitializerCommon.h" -#include "Plugins/Instruction/ARM/EmulateInstructionARM.h" -#include "Plugins/Instruction/MIPS/EmulateInstructionMIPS.h" -#include "Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h" -#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h" -#include "Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h" #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" +#include "lldb/Host/Socket.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Reproducer.h" #include "lldb/Utility/Timer.h" +#include "lldb/lldb-private.h" #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" #endif -#if defined(_MSC_VER) +#if defined(_WIN32) #include "Plugins/Process/Windows/Common/ProcessWindowsLog.h" #include "lldb/Host/windows/windows.h" #endif @@ -42,9 +38,8 @@ SystemInitializerCommon::~SystemInitializerCommon() {} -llvm::Error -SystemInitializerCommon::Initialize(const InitializerOptions &options) { -#if defined(_MSC_VER) +llvm::Error SystemInitializerCommon::Initialize() { +#if defined(_WIN32) const char *disable_crash_dialog_var = getenv("LLDB_DISABLE_CRASH_DIALOG"); if (disable_crash_dialog_var && llvm::StringRef(disable_crash_dialog_var).equals_lower("true")) { @@ -66,39 +61,47 @@ } #endif - ReproducerMode mode = ReproducerMode::Off; - if (options.reproducer_capture) - mode = ReproducerMode::Capture; - if (options.reproducer_replay) - mode = ReproducerMode::Replay; + // If the reproducer wasn't initialized before, we can safely assume it's + // off. + if (!Reproducer::Initialized()) { + if (auto e = Reproducer::Initialize(ReproducerMode::Off, llvm::None)) + return e; + } - if (auto e = Reproducer::Initialize(mode, FileSpec(options.reproducer_path))) - return e; + auto &r = repro::Reproducer::Instance(); + if (repro::Loader *loader = r.GetLoader()) { + FileSpec vfs_mapping = loader->GetFile<FileProvider::Info>(); + if (vfs_mapping) { + if (llvm::Error e = FileSystem::Initialize(vfs_mapping)) + return e; + } else { + FileSystem::Initialize(); + } + } else if (repro::Generator *g = r.GetGenerator()) { + repro::VersionProvider &vp = g->GetOrCreate<repro::VersionProvider>(); + vp.SetVersion(lldb_private::GetVersion()); + repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>(); + FileSystem::Initialize(fp.GetFileCollector()); + } else { + FileSystem::Initialize(); + } - FileSystem::Initialize(); Log::Initialize(); HostInfo::Initialize(); + + llvm::Error error = Socket::Initialize(); + if (error) + return error; + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); process_gdb_remote::ProcessGDBRemoteLog::Initialize(); - // Initialize plug-ins - ObjectContainerBSDArchive::Initialize(); - - EmulateInstructionARM::Initialize(); - EmulateInstructionMIPS::Initialize(); - EmulateInstructionMIPS64::Initialize(); - - //---------------------------------------------------------------------- - // Apple/Darwin hosted plugins - //---------------------------------------------------------------------- - ObjectContainerUniversalMachO::Initialize(); - #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) ProcessPOSIXLog::Initialize(); #endif -#if defined(_MSC_VER) +#if defined(_WIN32) ProcessWindowsLog::Initialize(); #endif @@ -108,18 +111,12 @@ void SystemInitializerCommon::Terminate() { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); - ObjectContainerBSDArchive::Terminate(); - EmulateInstructionARM::Terminate(); - EmulateInstructionMIPS::Terminate(); - EmulateInstructionMIPS64::Terminate(); - - ObjectContainerUniversalMachO::Terminate(); - -#if defined(_MSC_VER) +#if defined(_WIN32) ProcessWindowsLog::Terminate(); #endif + Socket::Terminate(); HostInfo::Terminate(); Log::DisableAllLogChannels(); FileSystem::Terminate();
diff --git a/src/llvm-project/lldb/source/Initialization/SystemLifetimeManager.cpp b/src/llvm-project/lldb/source/Initialization/SystemLifetimeManager.cpp index 65431bf..97f6048 100644 --- a/src/llvm-project/lldb/source/Initialization/SystemLifetimeManager.cpp +++ b/src/llvm-project/lldb/source/Initialization/SystemLifetimeManager.cpp
@@ -1,9 +1,8 @@ //===-- SystemLifetimeManager.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,7 +25,7 @@ llvm::Error SystemLifetimeManager::Initialize( std::unique_ptr<SystemInitializer> initializer, - const InitializerOptions &options, LoadPluginCallbackType plugin_callback) { + LoadPluginCallbackType plugin_callback) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (!m_initialized) { assert(!m_initializer && "Attempting to call " @@ -35,7 +34,7 @@ m_initialized = true; m_initializer = std::move(initializer); - if (auto e = m_initializer->Initialize(options)) + if (auto e = m_initializer->Initialize()) return e; Debugger::Initialize(plugin_callback);
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandAlias.cpp b/src/llvm-project/lldb/source/Interpreter/CommandAlias.cpp index 078eb73..8c40574 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandAlias.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandAlias.cpp
@@ -1,9 +1,8 @@ //===-- CommandAlias.cpp -----------------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,6 +30,8 @@ Args args(options_args); std::string options_string(options_args); + // TODO: Find a way to propagate errors in this CommandReturnObject up the + // stack. CommandReturnObject result; // Check to see if the command being aliased can take any command options. Options *options = cmd_obj_sp->GetOptions();
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandHistory.cpp b/src/llvm-project/lldb/source/Interpreter/CommandHistory.cpp index ca5c906..0be61f8 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandHistory.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandHistory.cpp
@@ -1,9 +1,8 @@ //===-- CommandHistory.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandInterpreter.cpp b/src/llvm-project/lldb/source/Interpreter/CommandInterpreter.cpp index 6d75ec5..8948037 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandInterpreter.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandInterpreter.cpp
@@ -1,12 +1,12 @@ //===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <memory> #include <stdlib.h> #include <string> #include <vector> @@ -81,6 +81,17 @@ static constexpr uintptr_t DefaultValueTrue = true; static constexpr uintptr_t DefaultValueFalse = false; static constexpr const char *NoCStrDefault = nullptr; +static constexpr const char *InitFileWarning = + "There is a .lldbinit file in the current directory which is not being " + "read.\n" + "To silence this warning without sourcing in the local .lldbinit,\n" + "add the following to the lldbinit file in your home directory:\n" + " settings set target.load-cwd-lldbinit false\n" + "To allow lldb to source .lldbinit files in the current working " + "directory,\n" + "set the value of this variable to true. Only do so if you understand " + "and\n" + "accept the security risk."; static constexpr PropertyDefinition g_properties[] = { {"expand-regex-aliases", OptionValue::eTypeBoolean, NoGlobalSetting, @@ -122,7 +133,6 @@ } CommandInterpreter::CommandInterpreter(Debugger &debugger, - ScriptLanguage script_language, bool synchronous_execution) : Broadcaster(debugger.GetBroadcasterManager(), CommandInterpreter::GetStaticBroadcasterClass().AsCString()), @@ -131,11 +141,10 @@ IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand), m_debugger(debugger), m_synchronous_execution(synchronous_execution), m_skip_lldbinit_files(false), m_skip_app_init_files(false), - m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'), + m_command_io_handler_sp(), m_comment_char('#'), m_batch_command_mode(false), m_truncation_warning(eNoTruncation), m_command_source_depth(0), m_num_errors(0), m_quit_requested(false), m_stopped_for_crash(false) { - debugger.SetScriptLanguage(script_language); SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit"); SetEventName(eBroadcastBitResetPrompt, "reset-prompt"); SetEventName(eBroadcastBitQuitCommandReceived, "quit"); @@ -367,7 +376,7 @@ if (cmd_obj_sp) AddAlias("image", cmd_obj_sp); - alias_arguments_vector_sp.reset(new OptionArgVector); + alias_arguments_vector_sp = std::make_shared<OptionArgVector>(); cmd_obj_sp = GetCommandSPExact("expression", false); if (cmd_obj_sp) { @@ -393,7 +402,7 @@ cmd_obj_sp = GetCommandSPExact("process launch", false); if (cmd_obj_sp) { - alias_arguments_vector_sp.reset(new OptionArgVector); + alias_arguments_vector_sp = std::make_shared<OptionArgVector>(); #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) AddAlias("r", cmd_obj_sp, "--"); AddAlias("run", cmd_obj_sp, "--"); @@ -431,13 +440,15 @@ AddAlias("var", cmd_obj_sp); AddAlias("vo", cmd_obj_sp, "--object-description"); } + + cmd_obj_sp = GetCommandSPExact("register", false); + if (cmd_obj_sp) { + AddAlias("re", cmd_obj_sp); + } } void CommandInterpreter::Clear() { m_command_io_handler_sp.reset(); - - if (m_script_interpreter_sp) - m_script_interpreter_sp->Clear(); } const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) { @@ -522,7 +533,7 @@ size_t num_regexes = llvm::array_lengthof(break_regexes); - std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-break", "Set a breakpoint using one of several shorthand formats.", @@ -550,28 +561,29 @@ "current file\n" " // containing text 'break " "here'.\n", - 2, CommandCompletions::eSymbolCompletion | - CommandCompletions::eSourceFileCompletion, + 2, + CommandCompletions::eSymbolCompletion | + CommandCompletions::eSourceFileCompletion, false)); - if (break_regex_cmd_ap.get()) { + if (break_regex_cmd_up) { bool success = true; for (size_t i = 0; i < num_regexes; i++) { - success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], + success = break_regex_cmd_up->AddRegexCommand(break_regexes[i][0], break_regexes[i][1]); if (!success) break; } success = - break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); + break_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full"); if (success) { - CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); + CommandObjectSP break_regex_cmd_sp(break_regex_cmd_up.release()); m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-tbreak", "Set a one-shot breakpoint using one of several shorthand formats.", @@ -599,11 +611,12 @@ "current file\n" " // containing text 'break " "here'.\n", - 2, CommandCompletions::eSymbolCompletion | - CommandCompletions::eSourceFileCompletion, + 2, + CommandCompletions::eSymbolCompletion | + CommandCompletions::eSourceFileCompletion, false)); - if (tbreak_regex_cmd_ap.get()) { + if (tbreak_regex_cmd_up) { bool success = true; for (size_t i = 0; i < num_regexes; i++) { // If you add a resultant command string longer than 1024 characters be @@ -614,155 +627,160 @@ lldbassert(num_printed < 1024); UNUSED_IF_ASSERT_DISABLED(num_printed); success = - tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer); + tbreak_regex_cmd_up->AddRegexCommand(break_regexes[i][0], buffer); if (!success) break; } success = - tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); + tbreak_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full"); if (success) { - CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release()); + CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_up.release()); m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] = tbreak_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-attach", "Attach to process by ID or name.", "_regexp-attach <pid> | <process-name>", 2, 0, false)); - if (attach_regex_cmd_ap.get()) { - if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", + if (attach_regex_cmd_up) { + if (attach_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") && - attach_regex_cmd_ap->AddRegexCommand( + attach_regex_cmd_up->AddRegexCommand( "^(-.*|.* -.*)$", "process attach %1") && // Any options that are // specified get passed to // 'process attach' - attach_regex_cmd_ap->AddRegexCommand("^(.+)$", + attach_regex_cmd_up->AddRegexCommand("^(.+)$", "process attach --name '%1'") && - attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) { - CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release()); + attach_regex_cmd_up->AddRegexCommand("^$", "process attach")) { + CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_up.release()); m_command_dict[attach_regex_cmd_sp->GetCommandName()] = attach_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_up( new CommandObjectRegexCommand(*this, "_regexp-down", "Select a newer stack frame. Defaults to " "moving one frame, a numeric argument can " "specify an arbitrary number.", "_regexp-down [<count>]", 2, 0, false)); - if (down_regex_cmd_ap.get()) { - if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") && - down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", + if (down_regex_cmd_up) { + if (down_regex_cmd_up->AddRegexCommand("^$", "frame select -r -1") && + down_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "frame select -r -%1")) { - CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release()); + CommandObjectSP down_regex_cmd_sp(down_regex_cmd_up.release()); m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-up", "Select an older stack frame. Defaults to moving one " "frame, a numeric argument can specify an arbitrary number.", "_regexp-up [<count>]", 2, 0, false)); - if (up_regex_cmd_ap.get()) { - if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") && - up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) { - CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release()); + if (up_regex_cmd_up) { + if (up_regex_cmd_up->AddRegexCommand("^$", "frame select -r 1") && + up_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) { + CommandObjectSP up_regex_cmd_sp(up_regex_cmd_up.release()); m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-display", "Evaluate an expression at every stop (see 'help target stop-hook'.)", "_regexp-display expression", 2, 0, false)); - if (display_regex_cmd_ap.get()) { - if (display_regex_cmd_ap->AddRegexCommand( + if (display_regex_cmd_up) { + if (display_regex_cmd_up->AddRegexCommand( "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) { - CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release()); + CommandObjectSP display_regex_cmd_sp(display_regex_cmd_up.release()); m_command_dict[display_regex_cmd_sp->GetCommandName()] = display_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap( - new CommandObjectRegexCommand( - *this, "_regexp-undisplay", "Stop displaying expression at every " - "stop (specified by stop-hook index.)", - "_regexp-undisplay stop-hook-number", 2, 0, false)); - if (undisplay_regex_cmd_ap.get()) { - if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", + std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_up( + new CommandObjectRegexCommand(*this, "_regexp-undisplay", + "Stop displaying expression at every " + "stop (specified by stop-hook index.)", + "_regexp-undisplay stop-hook-number", 2, 0, + false)); + if (undisplay_regex_cmd_up) { + if (undisplay_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1")) { - CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release()); + CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_up.release()); m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] = undisplay_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_up( new CommandObjectRegexCommand( - *this, "gdb-remote", "Connect to a process via remote GDB server. " - "If no host is specifed, localhost is assumed.", + *this, "gdb-remote", + "Connect to a process via remote GDB server. " + "If no host is specifed, localhost is assumed.", "gdb-remote [<hostname>:]<portnum>", 2, 0, false)); - if (connect_gdb_remote_cmd_ap.get()) { - if (connect_gdb_remote_cmd_ap->AddRegexCommand( + if (connect_gdb_remote_cmd_up) { + if (connect_gdb_remote_cmd_up->AddRegexCommand( "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$", "process connect --plugin gdb-remote connect://%1:%2") && - connect_gdb_remote_cmd_ap->AddRegexCommand( + connect_gdb_remote_cmd_up->AddRegexCommand( "^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1")) { - CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release()); + CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release()); m_command_dict[command_sp->GetCommandName()] = command_sp; } } - std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up( new CommandObjectRegexCommand( - *this, "kdp-remote", "Connect to a process via remote KDP server. " - "If no UDP port is specified, port 41139 is " - "assumed.", + *this, "kdp-remote", + "Connect to a process via remote KDP server. " + "If no UDP port is specified, port 41139 is " + "assumed.", "kdp-remote <hostname>[:<portnum>]", 2, 0, false)); - if (connect_kdp_remote_cmd_ap.get()) { - if (connect_kdp_remote_cmd_ap->AddRegexCommand( + if (connect_kdp_remote_cmd_up) { + if (connect_kdp_remote_cmd_up->AddRegexCommand( "^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") && - connect_kdp_remote_cmd_ap->AddRegexCommand( + connect_kdp_remote_cmd_up->AddRegexCommand( "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) { - CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release()); + CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release()); m_command_dict[command_sp->GetCommandName()] = command_sp; } } - std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-bt", "Show the current thread's call stack. Any numeric argument " "displays at most that many " - "frames. The argument 'all' displays all threads.", + "frames. The argument 'all' displays all threads. Use 'settings" + " set frame-format' to customize the printing of individual frames " + "and 'settings set thread-format' to customize the thread header.", "bt [<digit> | all]", 2, 0, false)); - if (bt_regex_cmd_ap.get()) { + if (bt_regex_cmd_up) { // accept but don't document "bt -c <number>" -- before bt was a regex // command if you wanted to backtrace three frames you would do "bt -c 3" // but the intention is to have this emulate the gdb "bt" command and so // now "bt 3" is the preferred form, in line with gdb. - if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", + if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$", "thread backtrace -c %1") && - bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", + bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)[[:space:]]*$", "thread backtrace -c %1") && - bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") && - bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) { - CommandObjectSP command_sp(bt_regex_cmd_ap.release()); + bt_regex_cmd_up->AddRegexCommand("^all[[:space:]]*$", "thread backtrace all") && + bt_regex_cmd_up->AddRegexCommand("^[[:space:]]*$", "thread backtrace")) { + CommandObjectSP command_sp(bt_regex_cmd_up.release()); m_command_dict[command_sp->GetCommandName()] = command_sp; } } - std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-list", "List relevant source code using one of several shorthand formats.", @@ -775,48 +793,48 @@ "_regexp-list -[<count>] // List previous <count> lines\n" "_regexp-list // List subsequent lines", 2, CommandCompletions::eSourceFileCompletion, false)); - if (list_regex_cmd_ap.get()) { - if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", + if (list_regex_cmd_up) { + if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") && - list_regex_cmd_ap->AddRegexCommand( + list_regex_cmd_up->AddRegexCommand( "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]" "]*$", "source list --file '%1' --line %2") && - list_regex_cmd_ap->AddRegexCommand( + list_regex_cmd_up->AddRegexCommand( "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") && - list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", + list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") && - list_regex_cmd_ap->AddRegexCommand( + list_regex_cmd_up->AddRegexCommand( "^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") && - list_regex_cmd_ap->AddRegexCommand("^(.+)$", + list_regex_cmd_up->AddRegexCommand("^(.+)$", "source list --name \"%1\"") && - list_regex_cmd_ap->AddRegexCommand("^$", "source list")) { - CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release()); + list_regex_cmd_up->AddRegexCommand("^$", "source list")) { + CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release()); m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-env", "Shorthand for viewing and setting environment variables.", "\n" - "_regexp-env // Show enrivonment\n" + "_regexp-env // Show environment\n" "_regexp-env <name>=<value> // Set an environment variable", 2, 0, false)); - if (env_regex_cmd_ap.get()) { - if (env_regex_cmd_ap->AddRegexCommand("^$", + if (env_regex_cmd_up) { + if (env_regex_cmd_up->AddRegexCommand("^$", "settings show target.env-vars") && - env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", + env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1")) { - CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release()); + CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release()); m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp; } } - std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap( + std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up( new CommandObjectRegexCommand( *this, "_regexp-jump", "Set the program counter to a new address.", "\n" @@ -825,16 +843,16 @@ "_regexp-jump <file>:<line>\n" "_regexp-jump *<addr>\n", 2, 0, false)); - if (jump_regex_cmd_ap.get()) { - if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", + if (jump_regex_cmd_up) { + if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") && - jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", + jump_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") && - jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", + jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") && - jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", + jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1")) { - CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release()); + CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release()); m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp; } } @@ -1721,7 +1739,7 @@ log->Printf("HandleCommand, (revised) command_string: '%s'", command_string.c_str()); const bool wants_raw_input = - (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false; + (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false; log->Printf("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False"); } @@ -2084,106 +2102,119 @@ return position; } -void CommandInterpreter::SourceInitFile(bool in_cwd, +static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file, + llvm::StringRef suffix = {}) { + std::string init_file_name = ".lldbinit"; + if (!suffix.empty()) { + init_file_name.append("-"); + init_file_name.append(suffix.str()); + } + + llvm::sys::path::home_directory(init_file); + llvm::sys::path::append(init_file, init_file_name); + + FileSystem::Instance().Resolve(init_file); +} + +static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) { + llvm::StringRef s = ".lldbinit"; + init_file.assign(s.begin(), s.end()); + FileSystem::Instance().Resolve(init_file); +} + +static LoadCWDlldbinitFile ShouldLoadCwdInitFile() { + lldb::TargetPropertiesSP properties = Target::GetGlobalProperties(); + if (!properties) + return eLoadCWDlldbinitFalse; + return properties->GetLoadCWDlldbinitFile(); +} + +void CommandInterpreter::SourceInitFile(FileSpec file, CommandReturnObject &result) { - FileSpec init_file; - if (in_cwd) { - ExecutionContext exe_ctx(GetExecutionContext()); - Target *target = exe_ctx.GetTargetPtr(); - if (target) { - // In the current working directory we don't load any program specific - // .lldbinit files, we only look for a ".lldbinit" file. - if (m_skip_lldbinit_files) - return; + assert(!m_skip_lldbinit_files); - LoadCWDlldbinitFile should_load = - target->TargetProperties::GetLoadCWDlldbinitFile(); - if (should_load == eLoadCWDlldbinitWarn) { - FileSpec dot_lldb(".lldbinit"); - FileSystem::Instance().Resolve(dot_lldb); - llvm::SmallString<64> home_dir_path; - llvm::sys::path::home_directory(home_dir_path); - FileSpec homedir_dot_lldb(home_dir_path.c_str()); - homedir_dot_lldb.AppendPathComponent(".lldbinit"); - FileSystem::Instance().Resolve(homedir_dot_lldb); - if (FileSystem::Instance().Exists(dot_lldb) && - dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) { - result.AppendErrorWithFormat( - "There is a .lldbinit file in the current directory which is not " - "being read.\n" - "To silence this warning without sourcing in the local " - ".lldbinit,\n" - "add the following to the lldbinit file in your home directory:\n" - " settings set target.load-cwd-lldbinit false\n" - "To allow lldb to source .lldbinit files in the current working " - "directory,\n" - "set the value of this variable to true. Only do so if you " - "understand and\n" - "accept the security risk."); - result.SetStatus(eReturnStatusFailed); - return; - } - } else if (should_load == eLoadCWDlldbinitTrue) { - init_file.SetFile("./.lldbinit", FileSpec::Style::native); - FileSystem::Instance().Resolve(init_file); - } - } - } else { - // If we aren't looking in the current working directory we are looking in - // the home directory. We will first see if there is an application - // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-" - // and the name of the program. If this file doesn't exist, we fall back to - // just the "~/.lldbinit" file. We also obey any requests to not load the - // init files. - llvm::SmallString<64> home_dir_path; - llvm::sys::path::home_directory(home_dir_path); - FileSpec profilePath(home_dir_path.c_str()); - profilePath.AppendPathComponent(".lldbinit"); - std::string init_file_path = profilePath.GetPath(); - - if (!m_skip_app_init_files) { - FileSpec program_file_spec(HostInfo::GetProgramFileSpec()); - const char *program_name = program_file_spec.GetFilename().AsCString(); - - if (program_name) { - char program_init_file_name[PATH_MAX]; - ::snprintf(program_init_file_name, sizeof(program_init_file_name), - "%s-%s", init_file_path.c_str(), program_name); - init_file.SetFile(program_init_file_name, FileSpec::Style::native); - FileSystem::Instance().Resolve(init_file); - if (!FileSystem::Instance().Exists(init_file)) - init_file.Clear(); - } - } - - if (!init_file && !m_skip_lldbinit_files) - init_file.SetFile(init_file_path, FileSpec::Style::native); - } - - // If the file exists, tell HandleCommand to 'source' it; this will do the - // actual broadcasting of the commands back to any appropriate listener (see - // CommandObjectSource::Execute for more details). - - if (FileSystem::Instance().Exists(init_file)) { - const bool saved_batch = SetBatchCommandMode(true); - CommandInterpreterRunOptions options; - options.SetSilent(true); - options.SetStopOnError(false); - options.SetStopOnContinue(true); - - HandleCommandsFromFile(init_file, - nullptr, // Execution context - options, result); - SetBatchCommandMode(saved_batch); - } else { - // nothing to be done if the file doesn't exist + if (!FileSystem::Instance().Exists(file)) { result.SetStatus(eReturnStatusSuccessFinishNoResult); + return; } + + // Use HandleCommand to 'source' the given file; this will do the actual + // broadcasting of the commands back to any appropriate listener (see + // CommandObjectSource::Execute for more details). + const bool saved_batch = SetBatchCommandMode(true); + ExecutionContext *ctx = nullptr; + CommandInterpreterRunOptions options; + options.SetSilent(true); + options.SetPrintErrors(true); + options.SetStopOnError(false); + options.SetStopOnContinue(true); + HandleCommandsFromFile(file, ctx, options, result); + SetBatchCommandMode(saved_batch); +} + +void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) { + if (m_skip_lldbinit_files) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return; + } + + llvm::SmallString<128> init_file; + GetCwdInitFile(init_file); + if (!FileSystem::Instance().Exists(init_file)) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return; + } + + LoadCWDlldbinitFile should_load = ShouldLoadCwdInitFile(); + + switch (should_load) { + case eLoadCWDlldbinitFalse: + result.SetStatus(eReturnStatusSuccessFinishNoResult); + break; + case eLoadCWDlldbinitTrue: + SourceInitFile(FileSpec(init_file.str()), result); + break; + case eLoadCWDlldbinitWarn: { + llvm::SmallString<128> home_init_file; + GetHomeInitFile(home_init_file); + if (llvm::sys::path::parent_path(init_file) == + llvm::sys::path::parent_path(home_init_file)) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendErrorWithFormat(InitFileWarning); + result.SetStatus(eReturnStatusFailed); + } + } + } +} + +/// We will first see if there is an application specific ".lldbinit" file +/// whose name is "~/.lldbinit" followed by a "-" and the name of the program. +/// If this file doesn't exist, we fall back to just the "~/.lldbinit" file. +void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result) { + if (m_skip_lldbinit_files) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return; + } + + llvm::SmallString<128> init_file; + GetHomeInitFile(init_file); + + if (!m_skip_app_init_files) { + llvm::StringRef program_name = + HostInfo::GetProgramFileSpec().GetFilename().GetStringRef(); + llvm::SmallString<128> program_init_file; + GetHomeInitFile(program_init_file, program_name); + if (FileSystem::Instance().Exists(program_init_file)) + init_file = program_init_file; + } + + SourceInitFile(FileSpec(init_file.str()), result); } const char *CommandInterpreter::GetCommandPrefix() { const char *prefix = GetDebugger().GetIOHandlerCommandPrefix(); - return prefix == NULL ? "" : prefix; + return prefix == nullptr ? "" : prefix; } PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) { @@ -2359,156 +2390,152 @@ eHandleCommandFlagEchoCommand = (1u << 2), eHandleCommandFlagEchoCommentCommand = (1u << 3), eHandleCommandFlagPrintResult = (1u << 4), - eHandleCommandFlagStopOnCrash = (1u << 5) + eHandleCommandFlagPrintErrors = (1u << 5), + eHandleCommandFlagStopOnCrash = (1u << 6) }; void CommandInterpreter::HandleCommandsFromFile( FileSpec &cmd_file, ExecutionContext *context, CommandInterpreterRunOptions &options, CommandReturnObject &result) { - if (FileSystem::Instance().Exists(cmd_file)) { - StreamFileSP input_file_sp(new StreamFile()); - - std::string cmd_file_path = cmd_file.GetPath(); - Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), - cmd_file, File::eOpenOptionRead); - if (error.Success()) { - Debugger &debugger = GetDebugger(); - - uint32_t flags = 0; - - if (options.m_stop_on_continue == eLazyBoolCalculate) { - if (m_command_source_flags.empty()) { - // Stop on continue by default - flags |= eHandleCommandFlagStopOnContinue; - } else if (m_command_source_flags.back() & - eHandleCommandFlagStopOnContinue) { - flags |= eHandleCommandFlagStopOnContinue; - } - } else if (options.m_stop_on_continue == eLazyBoolYes) { - flags |= eHandleCommandFlagStopOnContinue; - } - - if (options.m_stop_on_error == eLazyBoolCalculate) { - if (m_command_source_flags.empty()) { - if (GetStopCmdSourceOnError()) - flags |= eHandleCommandFlagStopOnError; - } else if (m_command_source_flags.back() & - eHandleCommandFlagStopOnError) { - flags |= eHandleCommandFlagStopOnError; - } - } else if (options.m_stop_on_error == eLazyBoolYes) { - flags |= eHandleCommandFlagStopOnError; - } - - // stop-on-crash can only be set, if it is present in all levels of - // pushed flag sets. - if (options.GetStopOnCrash()) { - if (m_command_source_flags.empty()) { - flags |= eHandleCommandFlagStopOnCrash; - } else if (m_command_source_flags.back() & - eHandleCommandFlagStopOnCrash) { - flags |= eHandleCommandFlagStopOnCrash; - } - } - - if (options.m_echo_commands == eLazyBoolCalculate) { - if (m_command_source_flags.empty()) { - // Echo command by default - flags |= eHandleCommandFlagEchoCommand; - } else if (m_command_source_flags.back() & - eHandleCommandFlagEchoCommand) { - flags |= eHandleCommandFlagEchoCommand; - } - } else if (options.m_echo_commands == eLazyBoolYes) { - flags |= eHandleCommandFlagEchoCommand; - } - - // We will only ever ask for this flag, if we echo commands in general. - if (options.m_echo_comment_commands == eLazyBoolCalculate) { - if (m_command_source_flags.empty()) { - // Echo comments by default - flags |= eHandleCommandFlagEchoCommentCommand; - } else if (m_command_source_flags.back() & - eHandleCommandFlagEchoCommentCommand) { - flags |= eHandleCommandFlagEchoCommentCommand; - } - } else if (options.m_echo_comment_commands == eLazyBoolYes) { - flags |= eHandleCommandFlagEchoCommentCommand; - } - - if (options.m_print_results == eLazyBoolCalculate) { - if (m_command_source_flags.empty()) { - // Print output by default - flags |= eHandleCommandFlagPrintResult; - } else if (m_command_source_flags.back() & - eHandleCommandFlagPrintResult) { - flags |= eHandleCommandFlagPrintResult; - } - } else if (options.m_print_results == eLazyBoolYes) { - flags |= eHandleCommandFlagPrintResult; - } - - if (flags & eHandleCommandFlagPrintResult) { - debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", - cmd_file_path.c_str()); - } - - // Used for inheriting the right settings when "command source" might - // have nested "command source" commands - lldb::StreamFileSP empty_stream_sp; - m_command_source_flags.push_back(flags); - IOHandlerSP io_handler_sp(new IOHandlerEditline( - debugger, IOHandler::Type::CommandInterpreter, input_file_sp, - empty_stream_sp, // Pass in an empty stream so we inherit the top - // input reader output stream - empty_stream_sp, // Pass in an empty stream so we inherit the top - // input reader error stream - flags, - nullptr, // Pass in NULL for "editline_name" so no history is saved, - // or written - debugger.GetPrompt(), llvm::StringRef(), - false, // Not multi-line - debugger.GetUseColor(), 0, *this)); - const bool old_async_execution = debugger.GetAsyncExecution(); - - // Set synchronous execution if we are not stopping on continue - if ((flags & eHandleCommandFlagStopOnContinue) == 0) - debugger.SetAsyncExecution(false); - - m_command_source_depth++; - - debugger.RunIOHandler(io_handler_sp); - if (!m_command_source_flags.empty()) - m_command_source_flags.pop_back(); - m_command_source_depth--; - result.SetStatus(eReturnStatusSuccessFinishNoResult); - debugger.SetAsyncExecution(old_async_execution); - } else { - result.AppendErrorWithFormat( - "error: an error occurred read file '%s': %s\n", - cmd_file_path.c_str(), error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } - - } else { + if (!FileSystem::Instance().Exists(cmd_file)) { result.AppendErrorWithFormat( "Error reading commands from file %s - file not found.\n", cmd_file.GetFilename().AsCString("<Unknown>")); result.SetStatus(eReturnStatusFailed); return; } -} -ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) { - std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); - if (!m_script_interpreter_sp) { - if (!can_create) - return nullptr; - lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage(); - m_script_interpreter_sp = - PluginManager::GetScriptInterpreterForLanguage(script_lang, *this); + StreamFileSP input_file_sp(new StreamFile()); + std::string cmd_file_path = cmd_file.GetPath(); + Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file, + File::eOpenOptionRead); + + if (error.Fail()) { + result.AppendErrorWithFormat( + "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return; } - return m_script_interpreter_sp.get(); + + Debugger &debugger = GetDebugger(); + + uint32_t flags = 0; + + if (options.m_stop_on_continue == eLazyBoolCalculate) { + if (m_command_source_flags.empty()) { + // Stop on continue by default + flags |= eHandleCommandFlagStopOnContinue; + } else if (m_command_source_flags.back() & + eHandleCommandFlagStopOnContinue) { + flags |= eHandleCommandFlagStopOnContinue; + } + } else if (options.m_stop_on_continue == eLazyBoolYes) { + flags |= eHandleCommandFlagStopOnContinue; + } + + if (options.m_stop_on_error == eLazyBoolCalculate) { + if (m_command_source_flags.empty()) { + if (GetStopCmdSourceOnError()) + flags |= eHandleCommandFlagStopOnError; + } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) { + flags |= eHandleCommandFlagStopOnError; + } + } else if (options.m_stop_on_error == eLazyBoolYes) { + flags |= eHandleCommandFlagStopOnError; + } + + // stop-on-crash can only be set, if it is present in all levels of + // pushed flag sets. + if (options.GetStopOnCrash()) { + if (m_command_source_flags.empty()) { + flags |= eHandleCommandFlagStopOnCrash; + } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) { + flags |= eHandleCommandFlagStopOnCrash; + } + } + + if (options.m_echo_commands == eLazyBoolCalculate) { + if (m_command_source_flags.empty()) { + // Echo command by default + flags |= eHandleCommandFlagEchoCommand; + } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) { + flags |= eHandleCommandFlagEchoCommand; + } + } else if (options.m_echo_commands == eLazyBoolYes) { + flags |= eHandleCommandFlagEchoCommand; + } + + // We will only ever ask for this flag, if we echo commands in general. + if (options.m_echo_comment_commands == eLazyBoolCalculate) { + if (m_command_source_flags.empty()) { + // Echo comments by default + flags |= eHandleCommandFlagEchoCommentCommand; + } else if (m_command_source_flags.back() & + eHandleCommandFlagEchoCommentCommand) { + flags |= eHandleCommandFlagEchoCommentCommand; + } + } else if (options.m_echo_comment_commands == eLazyBoolYes) { + flags |= eHandleCommandFlagEchoCommentCommand; + } + + if (options.m_print_results == eLazyBoolCalculate) { + if (m_command_source_flags.empty()) { + // Print output by default + flags |= eHandleCommandFlagPrintResult; + } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) { + flags |= eHandleCommandFlagPrintResult; + } + } else if (options.m_print_results == eLazyBoolYes) { + flags |= eHandleCommandFlagPrintResult; + } + + if (options.m_print_errors == eLazyBoolCalculate) { + if (m_command_source_flags.empty()) { + // Print output by default + flags |= eHandleCommandFlagPrintErrors; + } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) { + flags |= eHandleCommandFlagPrintErrors; + } + } else if (options.m_print_errors == eLazyBoolYes) { + flags |= eHandleCommandFlagPrintErrors; + } + + if (flags & eHandleCommandFlagPrintResult) { + debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", + cmd_file_path.c_str()); + } + + // Used for inheriting the right settings when "command source" might + // have nested "command source" commands + lldb::StreamFileSP empty_stream_sp; + m_command_source_flags.push_back(flags); + IOHandlerSP io_handler_sp(new IOHandlerEditline( + debugger, IOHandler::Type::CommandInterpreter, input_file_sp, + empty_stream_sp, // Pass in an empty stream so we inherit the top + // input reader output stream + empty_stream_sp, // Pass in an empty stream so we inherit the top + // input reader error stream + flags, + nullptr, // Pass in NULL for "editline_name" so no history is saved, + // or written + debugger.GetPrompt(), llvm::StringRef(), + false, // Not multi-line + debugger.GetUseColor(), 0, *this, nullptr)); + const bool old_async_execution = debugger.GetAsyncExecution(); + + // Set synchronous execution if we are not stopping on continue + if ((flags & eHandleCommandFlagStopOnContinue) == 0) + debugger.SetAsyncExecution(false); + + m_command_source_depth++; + + debugger.RunIOHandler(io_handler_sp); + if (!m_command_source_flags.empty()) + m_command_source_flags.pop_back(); + m_command_source_depth--; + result.SetStatus(eReturnStatusSuccessFinishNoResult); + debugger.SetAsyncExecution(old_async_execution); } bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; } @@ -2588,7 +2615,7 @@ uint32_t chars_left = max_columns; auto nextWordLength = [](llvm::StringRef S) { - size_t pos = S.find_first_of(' '); + size_t pos = S.find(' '); return pos == llvm::StringRef::npos ? S.size() : pos; }; @@ -2801,7 +2828,9 @@ HandleCommand(line.c_str(), eLazyBoolCalculate, result); // Now emit the command output text from the command we just executed - if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) { + if ((result.Succeeded() && + io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) || + io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) { // Display any STDOUT/STDERR _prior_ to emitting the command result text GetProcessOutput(); @@ -2885,7 +2914,8 @@ } } - ScriptInterpreter *script_interpreter = GetScriptInterpreter(false); + ScriptInterpreter *script_interpreter = + m_debugger.GetScriptInterpreter(false); if (script_interpreter) { if (script_interpreter->Interrupt()) return true; @@ -2904,8 +2934,9 @@ llvm::StringRef(), // Continuation prompt true, // Get multiple lines debugger.GetUseColor(), - 0, // Don't show line numbers - delegate)); // IOHandlerDelegate + 0, // Don't show line numbers + delegate, // IOHandlerDelegate + nullptr)); // FileShadowCollector if (io_handler_sp) { io_handler_sp->SetUserData(baton); @@ -2927,8 +2958,9 @@ llvm::StringRef(), // Continuation prompt true, // Get multiple lines debugger.GetUseColor(), - 0, // Don't show line numbers - delegate)); // IOHandlerDelegate + 0, // Don't show line numbers + delegate, // IOHandlerDelegate + nullptr)); // FileShadowCollector if (io_handler_sp) { io_handler_sp->SetUserData(baton); @@ -2968,19 +3000,23 @@ flags |= eHandleCommandFlagEchoCommentCommand; if (options->m_print_results != eLazyBoolNo) flags |= eHandleCommandFlagPrintResult; + if (options->m_print_errors != eLazyBoolNo) + flags |= eHandleCommandFlagPrintErrors; } else { - flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult; + flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult | + eHandleCommandFlagPrintErrors; } - m_command_io_handler_sp.reset(new IOHandlerEditline( + m_command_io_handler_sp = std::make_shared<IOHandlerEditline>( m_debugger, IOHandler::Type::CommandInterpreter, m_debugger.GetInputFile(), m_debugger.GetOutputFile(), m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(), llvm::StringRef(), // Continuation prompt false, // Don't enable multiple line input, just single line commands m_debugger.GetUseColor(), - 0, // Don't show line numbers - *this)); + 0, // Don't show line numbers + *this, // IOHandlerDelegate + GetDebugger().GetInputRecorder()); } return m_command_io_handler_sp; } @@ -3170,7 +3206,7 @@ if (!scratch_command.empty()) revised_command_line.Printf(" %s", scratch_command.c_str()); - if (cmd_obj != NULL) + if (cmd_obj != nullptr) command_line = revised_command_line.GetString(); return cmd_obj;
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandObject.cpp b/src/llvm-project/lldb/source/Interpreter/CommandObject.cpp index 05c540b..8e493c7 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandObject.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandObject.cpp
@@ -1,9 +1,8 @@ //===-- CommandObject.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,9 +35,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObject -//------------------------------------------------------------------------- CommandObject::CommandObject(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help, llvm::StringRef syntax, uint32_t flags) @@ -52,6 +49,8 @@ CommandObject::~CommandObject() {} +Debugger &CommandObject::GetDebugger() { return m_interpreter.GetDebugger(); } + llvm::StringRef CommandObject::GetHelp() { return m_cmd_help_short; } llvm::StringRef CommandObject::GetHelpLong() { return m_cmd_help_long; } @@ -137,17 +136,15 @@ } bool CommandObject::CheckRequirements(CommandReturnObject &result) { -#ifdef LLDB_CONFIGURATION_DEBUG // Nothing should be stored in m_exe_ctx between running commands as // m_exe_ctx has shared pointers to the target, process, thread and frame and // we don't want any CommandObject instances to keep any of these objects // around longer than for a single command. Every command should call - // CommandObject::Cleanup() after it has completed - assert(m_exe_ctx.GetTargetPtr() == NULL); - assert(m_exe_ctx.GetProcessPtr() == NULL); - assert(m_exe_ctx.GetThreadPtr() == NULL); - assert(m_exe_ctx.GetFramePtr() == NULL); -#endif + // CommandObject::Cleanup() after it has completed. + assert(!m_exe_ctx.GetTargetPtr()); + assert(!m_exe_ctx.GetProcessPtr()); + assert(!m_exe_ctx.GetThreadPtr()); + assert(!m_exe_ctx.GetFramePtr()); // Lock down the interpreter's execution context prior to running the command // so we guarantee the selected target, process, thread and frame can't go @@ -1106,7 +1103,8 @@ const CommandObject::ArgumentTableEntry *CommandObject::GetArgumentTable() { // If this assertion fires, then the table above is out of date with the // CommandArgumentType enumeration - assert((sizeof(CommandObject::g_arguments_data) / - sizeof(CommandObject::ArgumentTableEntry)) == eArgTypeLastArg); + static_assert((sizeof(CommandObject::g_arguments_data) / + sizeof(CommandObject::ArgumentTableEntry)) == eArgTypeLastArg, + ""); return CommandObject::g_arguments_data; }
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandObjectRegexCommand.cpp b/src/llvm-project/lldb/source/Interpreter/CommandObjectRegexCommand.cpp index 2944177..19335b9 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandObjectRegexCommand.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandObjectRegexCommand.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectRegexCommand.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // CommandObjectRegexCommand constructor -//---------------------------------------------------------------------- CommandObjectRegexCommand::CommandObjectRegexCommand( CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help, llvm::StringRef syntax, uint32_t max_matches, uint32_t completion_type_mask, @@ -26,9 +23,7 @@ m_max_matches(max_matches), m_completion_type_mask(completion_type_mask), m_entries(), m_is_removable(is_removable) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CommandObjectRegexCommand::~CommandObjectRegexCommand() {} bool CommandObjectRegexCommand::DoExecute(llvm::StringRef command,
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.cpp b/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.cpp index ed434031..edb1f67 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.cpp
@@ -1,9 +1,8 @@ //===-- CommandObjectScript.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,9 +21,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // CommandObjectScript -//------------------------------------------------------------------------- CommandObjectScript::CommandObjectScript(CommandInterpreter &interpreter, ScriptLanguage script_lang) @@ -53,7 +50,7 @@ return false; } - ScriptInterpreter *script_interpreter = m_interpreter.GetScriptInterpreter(); + ScriptInterpreter *script_interpreter = GetDebugger().GetScriptInterpreter(); if (script_interpreter == nullptr) { result.AppendError("no script interpreter");
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.h b/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.h index ca453a8..4f7a912 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.h +++ b/src/llvm-project/lldb/source/Interpreter/CommandObjectScript.h
@@ -1,9 +1,8 @@ //===-- CommandObjectScript.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ namespace lldb_private { -//------------------------------------------------------------------------- // CommandObjectScript -//------------------------------------------------------------------------- class CommandObjectScript : public CommandObjectRaw { public:
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandOptionValidators.cpp b/src/llvm-project/lldb/source/Interpreter/CommandOptionValidators.cpp index 1e614a9..c41c156 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandOptionValidators.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandOptionValidators.cpp
@@ -1,9 +1,8 @@ //===-- CommandOptionValidators.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/CommandReturnObject.cpp b/src/llvm-project/lldb/source/Interpreter/CommandReturnObject.cpp index cf397a4..3a7a875 100644 --- a/src/llvm-project/lldb/source/Interpreter/CommandReturnObject.cpp +++ b/src/llvm-project/lldb/source/Interpreter/CommandReturnObject.cpp
@@ -1,9 +1,8 @@ //===-- CommandReturnObject.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionArgParser.cpp b/src/llvm-project/lldb/source/Interpreter/OptionArgParser.cpp index b0565b7..efaac07 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionArgParser.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionArgParser.cpp
@@ -1,9 +1,8 @@ //===-- OptionArgParser.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupArchitecture.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupArchitecture.cpp index 42eafc9..2ee1a9c 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupArchitecture.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupArchitecture.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupArchitecture.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupBoolean.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupBoolean.cpp index ca694ef..8a6482c 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupBoolean.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupBoolean.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupBoolean.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupFile.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupFile.cpp index 241bad0..cda75ec 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupFile.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupFile.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupFile.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupFormat.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupFormat.cpp index 6345a63..d9acfd6 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupFormat.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupFormat.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupFormat.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupOutputFile.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupOutputFile.cpp index aebbf05..ccb99a8 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupOutputFile.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupOutputFile.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupOutputFile.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupPlatform.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupPlatform.cpp index 5858fcc..6dc2996 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupPlatform.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupPlatform.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupPlatform.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupString.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupString.cpp index 1b1fbdf..c01b706 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupString.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupString.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupString.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupUInt64.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupUInt64.cpp index bb2dcbb..53e5674 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupUInt64.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupUInt64.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupUInt64.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupUUID.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupUUID.cpp index 0859877..e32673b 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupUUID.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupUUID.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupUUID.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp index 40f219c..4e5463a 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupValueObjectDisplay.cpp -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupVariable.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupVariable.cpp index f90212cf..d703c3d 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupVariable.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupVariable.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupVariable.cpp -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionGroupWatchpoint.cpp b/src/llvm-project/lldb/source/Interpreter/OptionGroupWatchpoint.cpp index 36b4cc5..28e6b81 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionGroupWatchpoint.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionGroupWatchpoint.cpp
@@ -1,9 +1,8 @@ //===-- OptionGroupWatchpoint.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValue.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValue.cpp index 4e480dd..00c8642 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValue.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValue.cpp
@@ -1,9 +1,8 @@ //===-- OptionValue.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,10 +14,8 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // Get this value as a uint64_t value if it is encoded as a boolean, uint64_t // or int64_t. Other types will cause "fail_value" to be returned -//------------------------------------------------------------------------- uint64_t OptionValue::GetUInt64Value(uint64_t fail_value, bool *success_ptr) { if (success_ptr) *success_ptr = true; @@ -168,13 +165,13 @@ OptionValueLanguage *OptionValue::GetAsLanguage() { if (GetType() == OptionValue::eTypeLanguage) return static_cast<OptionValueLanguage *>(this); - return NULL; + return nullptr; } const OptionValueLanguage *OptionValue::GetAsLanguage() const { if (GetType() == OptionValue::eTypeLanguage) return static_cast<const OptionValueLanguage *>(this); - return NULL; + return nullptr; } OptionValueFormatEntity *OptionValue::GetAsFormatEntity() { @@ -523,7 +520,7 @@ value_sp.reset(new OptionValueFormat(eFormatInvalid)); break; case 1u << eTypeFormatEntity: - value_sp.reset(new OptionValueFormatEntity(NULL)); + value_sp.reset(new OptionValueFormatEntity(nullptr)); break; case 1u << eTypeLanguage: value_sp.reset(new OptionValueLanguage(eLanguageTypeUnknown));
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueArch.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueArch.cpp index e4f0b9d..92dc45d 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueArch.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueArch.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueArch.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueArgs.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueArgs.cpp index 4fa9e18..d619dba 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueArgs.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueArgs.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueArgs.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueArray.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueArray.cpp index d755fa2..30902c0 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueArray.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueArray.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueArray.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueBoolean.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueBoolean.cpp index a7fe10e..8be8220 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueBoolean.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueBoolean.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueBoolean.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueChar.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueChar.cpp index 1307b47..23012e6 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueChar.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueChar.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueChar.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueDictionary.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueDictionary.cpp index 5058064..eb66c48 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueDictionary.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueDictionary.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueDictionary.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -277,7 +276,7 @@ } lldb::OptionValueSP -OptionValueDictionary::GetValueForKey(const ConstString &key) const { +OptionValueDictionary::GetValueForKey(ConstString key) const { lldb::OptionValueSP value_sp; collection::const_iterator pos = m_values.find(key); if (pos != m_values.end()) @@ -285,7 +284,7 @@ return value_sp; } -bool OptionValueDictionary::SetValueForKey(const ConstString &key, +bool OptionValueDictionary::SetValueForKey(ConstString key, const lldb::OptionValueSP &value_sp, bool can_replace) { // Make sure the value_sp object is allowed to contain values of the type @@ -302,7 +301,7 @@ return false; } -bool OptionValueDictionary::DeleteValueForKey(const ConstString &key) { +bool OptionValueDictionary::DeleteValueForKey(ConstString key) { collection::iterator pos = m_values.find(key); if (pos != m_values.end()) { m_values.erase(pos);
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueEnumeration.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueEnumeration.cpp index e65dd2b..0b76bd0 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueEnumeration.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueEnumeration.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueEnumeration.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpec.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpec.cpp index 735a7d8..062d7cc 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpec.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpec.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueFileSpec.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp index fd78bba..a951888 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueFileSpecLIst.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,6 +17,7 @@ void OptionValueFileSpecList::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) { + std::lock_guard<std::recursive_mutex> lock(m_mutex); if (dump_mask & eDumpOptionType) strm.Printf("(%s)", GetTypeAsCString()); if (dump_mask & eDumpOptionValue) { @@ -44,6 +44,7 @@ Status OptionValueFileSpecList::SetValueFromString(llvm::StringRef value, VarSetOperationType op) { + std::lock_guard<std::recursive_mutex> lock(m_mutex); Status error; Args args(value.str()); const size_t argc = args.GetArgumentCount(); @@ -164,5 +165,6 @@ } lldb::OptionValueSP OptionValueFileSpecList::DeepCopy() const { - return OptionValueSP(new OptionValueFileSpecList(*this)); + std::lock_guard<std::recursive_mutex> lock(m_mutex); + return OptionValueSP(new OptionValueFileSpecList(m_current_value)); }
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueFormat.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueFormat.cpp index 945d8bd..ba5a44c 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueFormat.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueFormat.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueFormat.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueFormatEntity.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueFormatEntity.cpp index 1878362..1bb8c9f 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueFormatEntity.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueFormatEntity.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueFormatEntity.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueLanguage.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueLanguage.cpp index c6e168d..d935d5e 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueLanguage.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueLanguage.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueLanguage.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValuePathMappings.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValuePathMappings.cpp index 11ec739..75fcf02 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValuePathMappings.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValuePathMappings.cpp
@@ -1,9 +1,8 @@ //===-- OptionValuePathMappings.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueProperties.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueProperties.cpp index 327d26b..4dae930 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueProperties.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueProperties.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueProperties.cpp --------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,7 @@ using namespace lldb; using namespace lldb_private; -OptionValueProperties::OptionValueProperties(const ConstString &name) +OptionValueProperties::OptionValueProperties(ConstString name) : OptionValue(), m_name(name), m_properties(), m_name_to_index() {} OptionValueProperties::OptionValueProperties( @@ -67,8 +66,8 @@ property->SetValueChangedCallback(callback, baton); } -void OptionValueProperties::AppendProperty(const ConstString &name, - const ConstString &desc, +void OptionValueProperties::AppendProperty(ConstString name, + ConstString desc, bool is_global, const OptionValueSP &value_sp) { Property property(name, desc, is_global, value_sp); @@ -99,7 +98,7 @@ // lldb::OptionValueSP OptionValueProperties::GetValueForKey(const ExecutionContext *exe_ctx, - const ConstString &key, + ConstString key, bool will_modify) const { lldb::OptionValueSP value_sp; size_t idx = m_name_to_index.Find(key, SIZE_MAX); @@ -160,7 +159,7 @@ // args if executable basename is "test" and arch is "x86_64" if (sub_name[1]) { llvm::StringRef predicate_start = sub_name.drop_front(); - size_t pos = predicate_start.find_first_of('}'); + size_t pos = predicate_start.find('}'); if (pos != llvm::StringRef::npos) { auto predicate = predicate_start.take_front(pos); auto rest = predicate_start.drop_front(pos); @@ -205,7 +204,6 @@ if (Properties::IsSettingExperimental(part)) name_contains_experimental = true; - lldb::OptionValueSP value_sp(GetSubValue(exe_ctx, name, will_modify, error)); if (value_sp) error = value_sp->SetValueFromString(value, op); @@ -220,14 +218,14 @@ } uint32_t -OptionValueProperties::GetPropertyIndex(const ConstString &name) const { +OptionValueProperties::GetPropertyIndex(ConstString name) const { return m_name_to_index.Find(name, SIZE_MAX); } const Property * OptionValueProperties::GetProperty(const ExecutionContext *exe_ctx, bool will_modify, - const ConstString &name) const { + ConstString name) const { return GetPropertyAtIndex( exe_ctx, will_modify, m_name_to_index.Find(name, SIZE_MAX)); @@ -668,7 +666,7 @@ lldb::OptionValuePropertiesSP OptionValueProperties::GetSubProperty(const ExecutionContext *exe_ctx, - const ConstString &name) { + ConstString name) { lldb::OptionValueSP option_value_sp(GetValueForKey(exe_ctx, name, false)); if (option_value_sp) { OptionValueProperties *ov_properties = option_value_sp->GetAsProperties();
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueRegex.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueRegex.cpp index 3c06ff3..bbe3fa7 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueRegex.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueRegex.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueRegex.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueSInt64.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueSInt64.cpp index c087c3e..d26fc08 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueSInt64.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueSInt64.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueSInt64.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueString.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueString.cpp index c89a0c6..a519249 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueString.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueString.cpp
@@ -1,10 +1,9 @@ //===-- OptionValueString.cpp ------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueUInt64.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueUInt64.cpp index 053b579..3be0772 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueUInt64.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueUInt64.cpp
@@ -1,10 +1,9 @@ //===-- OptionValueUInt64.cpp ------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/OptionValueUUID.cpp b/src/llvm-project/lldb/source/Interpreter/OptionValueUUID.cpp index 5518a05..f39b66b 100644 --- a/src/llvm-project/lldb/source/Interpreter/OptionValueUUID.cpp +++ b/src/llvm-project/lldb/source/Interpreter/OptionValueUUID.cpp
@@ -1,9 +1,8 @@ //===-- OptionValueUUID.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Interpreter/Options.cpp b/src/llvm-project/lldb/source/Interpreter/Options.cpp index c635739..ba15c02 100644 --- a/src/llvm-project/lldb/source/Interpreter/Options.cpp +++ b/src/llvm-project/lldb/source/Interpreter/Options.cpp
@@ -1,9 +1,8 @@ //===-- Options.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------------- // Options -//------------------------------------------------------------------------- Options::Options() : m_getopt_table() { BuildValidOptionSets(); } Options::~Options() {} @@ -761,7 +758,7 @@ CompletionRequest &request, OptionElementVector &opt_element_vector, int opt_element_index, CommandInterpreter &interpreter) { auto opt_defs = GetDefinitions(); - std::unique_ptr<SearchFilter> filter_ap; + std::unique_ptr<SearchFilter> filter_up; int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos; int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; @@ -832,7 +829,7 @@ interpreter.GetDebugger().GetSelectedTarget(); // Search filters require a target... if (target_sp) - filter_ap.reset(new SearchFilterByModule(target_sp, module_spec)); + filter_up.reset(new SearchFilterByModule(target_sp, module_spec)); } break; } @@ -840,7 +837,7 @@ } return CommandCompletions::InvokeCommonCompletionCallbacks( - interpreter, completion_mask, request, filter_ap.get()); + interpreter, completion_mask, request, filter_up.get()); } void OptionGroupOptions::Append(OptionGroup *group) { @@ -933,6 +930,7 @@ result.push_back(const_cast<char *>("<FAKE-ARG0>")); for (const Args::ArgEntry &entry : args) result.push_back(const_cast<char *>(entry.c_str())); + result.push_back(nullptr); return result; } @@ -975,19 +973,15 @@ return size_t(-1); } -llvm::Expected<Args> Options::ParseAlias(const Args &args, - OptionArgVector *option_arg_vector, - std::string &input_line) { - StreamString sstr; - int i; - Option *long_options = GetLongOptions(); +static std::string BuildShortOptions(const Option *long_options) { + std::string storage; + llvm::raw_string_ostream sstr(storage); - if (long_options == nullptr) { - return llvm::make_error<llvm::StringError>("Invalid long options", - llvm::inconvertibleErrorCode()); - } + // Leading : tells getopt to return a : for a missing option argument AND to + // suppress error messages. + sstr << ":"; - for (i = 0; long_options[i].definition != nullptr; ++i) { + for (size_t i = 0; long_options[i].definition != nullptr; ++i) { if (long_options[i].flag == nullptr) { sstr << (char)long_options[i].val; switch (long_options[i].definition->option_has_arg) { @@ -1003,6 +997,20 @@ } } } + return std::move(sstr.str()); +} + +llvm::Expected<Args> Options::ParseAlias(const Args &args, + OptionArgVector *option_arg_vector, + std::string &input_line) { + Option *long_options = GetLongOptions(); + + if (long_options == nullptr) { + return llvm::make_error<llvm::StringError>("Invalid long options", + llvm::inconvertibleErrorCode()); + } + + std::string short_options = BuildShortOptions(long_options); Args args_copy = args; std::vector<char *> argv = GetArgvForParsing(args); @@ -1010,10 +1018,15 @@ std::unique_lock<std::mutex> lock; OptionParser::Prepare(lock); int val; - while (1) { + while (true) { int long_options_index = -1; - val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(), - long_options, &long_options_index); + val = OptionParser::Parse(argv, short_options, long_options, + &long_options_index); + + if (val == ':') { + return llvm::createStringError(llvm::inconvertibleErrorCode(), + "last option requires an argument"); + } if (val == -1) break; @@ -1119,33 +1132,13 @@ OptionElementVector Options::ParseForCompletion(const Args &args, uint32_t cursor_index) { OptionElementVector option_element_vector; - StreamString sstr; Option *long_options = GetLongOptions(); option_element_vector.clear(); if (long_options == nullptr) return option_element_vector; - // Leading : tells getopt to return a : for a missing option argument AND to - // suppress error messages. - - sstr << ":"; - for (int i = 0; long_options[i].definition != nullptr; ++i) { - if (long_options[i].flag == nullptr) { - sstr << (char)long_options[i].val; - switch (long_options[i].definition->option_has_arg) { - default: - case OptionParser::eNoArgument: - break; - case OptionParser::eRequiredArgument: - sstr << ":"; - break; - case OptionParser::eOptionalArgument: - sstr << "::"; - break; - } - } - } + std::string short_options = BuildShortOptions(long_options); std::unique_lock<std::mutex> lock; OptionParser::Prepare(lock); @@ -1156,19 +1149,15 @@ std::vector<char *> dummy_vec = GetArgvForParsing(args); - // I stick an element on the end of the input, because if the last element - // is option that requires an argument, getopt_long_only will freak out. - dummy_vec.push_back(const_cast<char *>("<FAKE-VALUE>")); - bool failed_once = false; uint32_t dash_dash_pos = -1; - while (1) { + while (true) { bool missing_argument = false; int long_options_index = -1; - val = OptionParser::Parse(dummy_vec.size(), &dummy_vec[0], sstr.GetString(), - long_options, &long_options_index); + val = OptionParser::Parse(dummy_vec, short_options, long_options, + &long_options_index); if (val == -1) { // When we're completing a "--" which is the last option on line, @@ -1331,7 +1320,6 @@ ExecutionContext *execution_context, lldb::PlatformSP platform_sp, bool require_validation) { - StreamString sstr; Status error; Option *long_options = GetLongOptions(); if (long_options == nullptr) { @@ -1339,32 +1327,21 @@ llvm::inconvertibleErrorCode()); } - for (int i = 0; long_options[i].definition != nullptr; ++i) { - if (long_options[i].flag == nullptr) { - if (isprint8(long_options[i].val)) { - sstr << (char)long_options[i].val; - switch (long_options[i].definition->option_has_arg) { - default: - case OptionParser::eNoArgument: - break; - case OptionParser::eRequiredArgument: - sstr << ':'; - break; - case OptionParser::eOptionalArgument: - sstr << "::"; - break; - } - } - } - } + std::string short_options = BuildShortOptions(long_options); std::vector<char *> argv = GetArgvForParsing(args); std::unique_lock<std::mutex> lock; OptionParser::Prepare(lock); int val; - while (1) { + while (true) { int long_options_index = -1; - val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(), - long_options, &long_options_index); + val = OptionParser::Parse(argv, short_options, long_options, + &long_options_index); + + if (val == ':') { + error.SetErrorStringWithFormat("last option requires an argument"); + break; + } + if (val == -1) break; @@ -1437,10 +1414,12 @@ } else { error.SetErrorStringWithFormat("invalid option with value '%i'", val); } - if (error.Fail()) - return error.ToError(); } + if (error.Fail()) + return error.ToError(); + + argv.pop_back(); argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex()); return ReconstituteArgsAfterParsing(argv, args); }
diff --git a/src/llvm-project/lldb/source/Interpreter/Property.cpp b/src/llvm-project/lldb/source/Interpreter/Property.cpp index 5f10223..7820931 100644 --- a/src/llvm-project/lldb/source/Interpreter/Property.cpp +++ b/src/llvm-project/lldb/source/Interpreter/Property.cpp
@@ -1,9 +1,8 @@ //===-- Property.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,6 +15,8 @@ #include "lldb/Interpreter/OptionValues.h" #include "lldb/Target/Language.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -30,18 +31,20 @@ // "definition.default_uint_value" is not used // "definition.default_cstr_value" as a string value that represents the // default string value for the architecture/triple - m_value_sp.reset(new OptionValueArch(definition.default_cstr_value)); + m_value_sp = + std::make_shared<OptionValueArch>(definition.default_cstr_value); break; case OptionValue::eTypeArgs: // "definition.default_uint_value" is always a OptionValue::Type - m_value_sp.reset(new OptionValueArgs()); + m_value_sp = std::make_shared<OptionValueArgs>(); break; case OptionValue::eTypeArray: // "definition.default_uint_value" is always a OptionValue::Type - m_value_sp.reset(new OptionValueArray(OptionValue::ConvertTypeToMask( - (OptionValue::Type)definition.default_uint_value))); + m_value_sp = + std::make_shared<OptionValueArray>(OptionValue::ConvertTypeToMask( + (OptionValue::Type)definition.default_uint_value)); break; case OptionValue::eTypeBoolean: @@ -50,11 +53,12 @@ // "definition.default_cstr_value" as a string value that represents the // default value. if (definition.default_cstr_value) - m_value_sp.reset(new OptionValueBoolean(OptionArgParser::ToBoolean( - llvm::StringRef(definition.default_cstr_value), false, nullptr))); + m_value_sp = + std::make_shared<OptionValueBoolean>(OptionArgParser::ToBoolean( + llvm::StringRef(definition.default_cstr_value), false, nullptr)); else - m_value_sp.reset( - new OptionValueBoolean(definition.default_uint_value != 0)); + m_value_sp = std::make_shared<OptionValueBoolean>( + definition.default_uint_value != 0); break; case OptionValue::eTypeChar: { @@ -65,8 +69,9 @@ } case OptionValue::eTypeDictionary: // "definition.default_uint_value" is always a OptionValue::Type - m_value_sp.reset(new OptionValueDictionary(OptionValue::ConvertTypeToMask( - (OptionValue::Type)definition.default_uint_value))); + m_value_sp = + std::make_shared<OptionValueDictionary>(OptionValue::ConvertTypeToMask( + (OptionValue::Type)definition.default_uint_value)); break; case OptionValue::eTypeEnum: @@ -101,14 +106,14 @@ FileSpec file_spec = FileSpec(definition.default_cstr_value); if (resolve) FileSystem::Instance().Resolve(file_spec); - m_value_sp.reset(new OptionValueFileSpec(file_spec, resolve)); + m_value_sp = std::make_shared<OptionValueFileSpec>(file_spec, resolve); break; } case OptionValue::eTypeFileSpecList: // "definition.default_uint_value" is not used for a // OptionValue::eTypeFileSpecList - m_value_sp.reset(new OptionValueFileSpecList()); + m_value_sp = std::make_shared<OptionValueFileSpecList>(); break; case OptionValue::eTypeFormat: @@ -123,7 +128,7 @@ nullptr); else new_format = (Format)definition.default_uint_value; - m_value_sp.reset(new OptionValueFormat(new_format)); + m_value_sp = std::make_shared<OptionValueFormat>(new_format); } break; @@ -139,29 +144,30 @@ llvm::StringRef(definition.default_cstr_value)); else new_lang = (LanguageType)definition.default_uint_value; - m_value_sp.reset(new OptionValueLanguage(new_lang)); + m_value_sp = std::make_shared<OptionValueLanguage>(new_lang); } break; case OptionValue::eTypeFormatEntity: // "definition.default_cstr_value" as a string value that represents the // default - m_value_sp.reset( - new OptionValueFormatEntity(definition.default_cstr_value)); + m_value_sp = std::make_shared<OptionValueFormatEntity>( + definition.default_cstr_value); break; case OptionValue::eTypePathMap: // "definition.default_uint_value" tells us if notifications should occur // for path mappings - m_value_sp.reset( - new OptionValuePathMappings(definition.default_uint_value != 0)); + m_value_sp = std::make_shared<OptionValuePathMappings>( + definition.default_uint_value != 0); break; case OptionValue::eTypeRegex: // "definition.default_uint_value" is used to the regular expression flags // "definition.default_cstr_value" the default regular expression value // value. - m_value_sp.reset(new OptionValueRegex(definition.default_cstr_value)); + m_value_sp = + std::make_shared<OptionValueRegex>(definition.default_cstr_value); break; case OptionValue::eTypeSInt64: @@ -169,10 +175,10 @@ // "definition.default_cstr_value" is NULL, otherwise interpret // "definition.default_cstr_value" as a string value that represents the // default value. - m_value_sp.reset(new OptionValueSInt64( + m_value_sp = std::make_shared<OptionValueSInt64>( definition.default_cstr_value ? StringConvert::ToSInt64(definition.default_cstr_value) - : definition.default_uint_value)); + : definition.default_uint_value); break; case OptionValue::eTypeUInt64: @@ -180,10 +186,10 @@ // "definition.default_cstr_value" is NULL, otherwise interpret // "definition.default_cstr_value" as a string value that represents the // default value. - m_value_sp.reset(new OptionValueUInt64( + m_value_sp = std::make_shared<OptionValueUInt64>( definition.default_cstr_value ? StringConvert::ToUInt64(definition.default_cstr_value) - : definition.default_uint_value)); + : definition.default_uint_value); break; case OptionValue::eTypeUUID: @@ -193,7 +199,7 @@ UUID uuid; if (definition.default_cstr_value) uuid.SetFromStringRef(definition.default_cstr_value); - m_value_sp.reset(new OptionValueUUID(uuid)); + m_value_sp = std::make_shared<OptionValueUUID>(uuid); } break; @@ -212,7 +218,7 @@ } } -Property::Property(const ConstString &name, const ConstString &desc, +Property::Property(ConstString name, ConstString desc, bool is_global, const lldb::OptionValueSP &value_sp) : m_name(name), m_description(desc), m_value_sp(value_sp), m_is_global(is_global) {}
diff --git a/src/llvm-project/lldb/source/Interpreter/ScriptInterpreter.cpp b/src/llvm-project/lldb/source/Interpreter/ScriptInterpreter.cpp index 497ad28..d04baec 100644 --- a/src/llvm-project/lldb/source/Interpreter/ScriptInterpreter.cpp +++ b/src/llvm-project/lldb/source/Interpreter/ScriptInterpreter.cpp
@@ -1,9 +1,8 @@ //===-- ScriptInterpreter.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,16 +21,12 @@ using namespace lldb; using namespace lldb_private; -ScriptInterpreter::ScriptInterpreter(CommandInterpreter &interpreter, +ScriptInterpreter::ScriptInterpreter(Debugger &debugger, lldb::ScriptLanguage script_lang) - : m_interpreter(interpreter), m_script_lang(script_lang) {} + : m_debugger(debugger), m_script_lang(script_lang) {} ScriptInterpreter::~ScriptInterpreter() {} -CommandInterpreter &ScriptInterpreter::GetCommandInterpreter() { - return m_interpreter; -} - void ScriptInterpreter::CollectDataForBreakpointCommandCallback( std::vector<BreakpointOptions *> &bp_options_vec, CommandReturnObject &result) {
diff --git a/src/llvm-project/lldb/source/Interpreter/embedded_interpreter.py b/src/llvm-project/lldb/source/Interpreter/embedded_interpreter.py index c103b7e..8a1195d 100644 --- a/src/llvm-project/lldb/source/Interpreter/embedded_interpreter.py +++ b/src/llvm-project/lldb/source/Interpreter/embedded_interpreter.py
@@ -72,6 +72,7 @@ def readfunc_stdio(prompt): sys.stdout.write(prompt) + sys.stdout.flush() return sys.stdin.readline().rstrip()
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/ABI/CMakeLists.txt index 9d7a793..c88affd 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/ABI/CMakeLists.txt
@@ -11,3 +11,4 @@ add_subdirectory(MacOSX-i386) add_subdirectory(MacOSX-arm) add_subdirectory(MacOSX-arm64) +add_subdirectory(Windows-x86_64)
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp index 9055660..362a80b 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp
@@ -1,9 +1,8 @@ //===-- ABIMacOSX_arm.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -1317,9 +1316,7 @@ size_t ABIMacOSX_arm::GetRedZoneSize() const { return 0; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABIMacOSX_arm::CreateInstance(ProcessSP process_sp, const ArchSpec &arch) { @@ -1605,7 +1602,7 @@ r2_reg_info->byte_size + r3_reg_info->byte_size && process_sp) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue r0_reg_value; @@ -1618,18 +1615,18 @@ reg_ctx->ReadRegister(r3_reg_info, r3_reg_value)) { Status error; if (r0_reg_value.GetAsMemoryData(r0_reg_info, - heap_data_ap->GetBytes() + 0, + heap_data_up->GetBytes() + 0, 4, byte_order, error) && r1_reg_value.GetAsMemoryData(r1_reg_info, - heap_data_ap->GetBytes() + 4, + heap_data_up->GetBytes() + 4, 4, byte_order, error) && r2_reg_value.GetAsMemoryData(r2_reg_info, - heap_data_ap->GetBytes() + 8, + heap_data_up->GetBytes() + 8, 4, byte_order, error) && r3_reg_value.GetAsMemoryData(r3_reg_info, - heap_data_ap->GetBytes() + 12, + heap_data_up->GetBytes() + 12, 4, byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), + DataExtractor data(DataBufferSP(heap_data_up.release()), byte_order, process_sp->GetAddressByteSize()); @@ -2046,9 +2043,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABIMacOSX_arm::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h index 94f1e31..ac9ba00 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h
@@ -1,9 +1,8 @@ //===-- ABIMacOSX_arm.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -64,9 +63,7 @@ bool IsArmv7kProcess() const; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -76,9 +73,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp index d8706c4..368e372 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp
@@ -1,9 +1,8 @@ //===-- ABIMacOSX_arm64.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -1658,9 +1657,7 @@ size_t ABIMacOSX_arm64::GetRedZoneSize() const { return 128; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABIMacOSX_arm64::CreateInstance(ProcessSP process_sp, const ArchSpec &arch) { @@ -2115,7 +2112,7 @@ if (!byte_size || *byte_size == 0) return false; - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); Status error; @@ -2149,10 +2146,10 @@ if (!reg_ctx->ReadRegister(reg_info, reg_value)) return false; - // Make sure we have enough room in "heap_data_ap" - if ((data_offset + *base_byte_size) <= heap_data_ap->GetByteSize()) { + // Make sure we have enough room in "heap_data_up" + if ((data_offset + *base_byte_size) <= heap_data_up->GetByteSize()) { const size_t bytes_copied = reg_value.GetAsMemoryData( - reg_info, heap_data_ap->GetBytes() + data_offset, *base_byte_size, + reg_info, heap_data_up->GetBytes() + data_offset, *base_byte_size, byte_order, error); if (bytes_copied != *base_byte_size) return false; @@ -2163,7 +2160,7 @@ } data.SetByteOrder(byte_order); data.SetAddressByteSize(exe_ctx.GetProcessRef().GetAddressByteSize()); - data.SetData(DataBufferSP(heap_data_ap.release())); + data.SetData(DataBufferSP(heap_data_up.release())); return true; } } @@ -2192,7 +2189,7 @@ const size_t curr_byte_size = std::min<size_t>(8, bytes_left); const size_t bytes_copied = reg_value.GetAsMemoryData( - reg_info, heap_data_ap->GetBytes() + data_offset, curr_byte_size, + reg_info, heap_data_up->GetBytes() + data_offset, curr_byte_size, byte_order, error); if (bytes_copied == 0) return false; @@ -2236,15 +2233,15 @@ return false; if (exe_ctx.GetProcessRef().ReadMemory( - value_addr, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), - error) != heap_data_ap->GetByteSize()) { + value_addr, heap_data_up->GetBytes(), heap_data_up->GetByteSize(), + error) != heap_data_up->GetByteSize()) { return false; } } data.SetByteOrder(byte_order); data.SetAddressByteSize(exe_ctx.GetProcessRef().GetAddressByteSize()); - data.SetData(DataBufferSP(heap_data_ap.release())); + data.SetData(DataBufferSP(heap_data_up.release())); return true; } @@ -2296,7 +2293,7 @@ if (x1_reg_info) { if (*byte_size <= x0_reg_info->byte_size + x1_reg_info->byte_size) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); @@ -2306,13 +2303,13 @@ reg_ctx->ReadRegister(x1_reg_info, x1_reg_value)) { Status error; if (x0_reg_value.GetAsMemoryData( - x0_reg_info, heap_data_ap->GetBytes() + 0, 8, + x0_reg_info, heap_data_up->GetBytes() + 0, 8, byte_order, error) && x1_reg_value.GetAsMemoryData( - x1_reg_info, heap_data_ap->GetBytes() + 8, 8, + x1_reg_info, heap_data_up->GetBytes() + 8, 8, byte_order, error)) { DataExtractor data( - DataBufferSP(heap_data_ap.release()), byte_order, + DataBufferSP(heap_data_up.release()), byte_order, exe_ctx.GetProcessRef().GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( @@ -2396,16 +2393,16 @@ if (v0_info) { if (*byte_size <= v0_info->byte_size) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(v0_info, reg_value)) { Status error; - if (reg_value.GetAsMemoryData(v0_info, heap_data_ap->GetBytes(), - heap_data_ap->GetByteSize(), + if (reg_value.GetAsMemoryData(v0_info, heap_data_up->GetBytes(), + heap_data_up->GetByteSize(), byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), + DataExtractor data(DataBufferSP(heap_data_up.release()), byte_order, exe_ctx.GetProcessRef().GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( @@ -2440,9 +2437,7 @@ PluginManager::UnregisterPlugin(CreateInstance); } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString ABIMacOSX_arm64::GetPluginNameStatic() { static ConstString g_plugin_name("ABIMacOSX_arm64");
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h index 7a9444c..bfacbcd 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h
@@ -1,9 +1,8 @@ //===-- ABIMacOSX_arm64.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -66,9 +65,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -76,9 +73,7 @@ static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ static lldb_private::ConstString GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp index a297bd1..67371b4 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp
@@ -1,9 +1,8 @@ //===-- ABIMacOSX_i386.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -704,9 +703,7 @@ size_t ABIMacOSX_i386::GetRedZoneSize() const { return 0; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABIMacOSX_i386::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -1124,9 +1121,7 @@ return g_short_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABIMacOSX_i386::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h index 536132d..57def68 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h
@@ -1,9 +1,8 @@ //===-- ABIMacOSX_i386.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -69,9 +68,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -79,9 +76,7 @@ static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ static lldb_private::ConstString GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp index b93a852..dd47ac7 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_arm.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -1318,9 +1317,7 @@ size_t ABISysV_arm::GetRedZoneSize() const { return 0; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_arm::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -1742,8 +1739,8 @@ uint32_t index = 0; for (index = 0; index < num_children; index++) { std::string name; - base_type = - compiler_type.GetFieldAtIndex(index, name, NULL, NULL, NULL); + base_type = compiler_type.GetFieldAtIndex(index, name, nullptr, + nullptr, nullptr); if (base_type.IsFloatingPointType(float_count, is_complex)) { llvm::Optional<uint64_t> base_byte_size = @@ -1802,7 +1799,7 @@ const RegisterInfo *reg_info = reg_ctx->GetRegisterInfo(eRegisterKindDWARF, regnum); - if (reg_info == NULL) + if (reg_info == nullptr) break; RegisterValue reg_value; @@ -2150,9 +2147,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_arm::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h index 7f2d658..a0f00c8 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h
@@ -1,9 +1,8 @@ //===-- ABISysV_arm.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -64,9 +63,7 @@ bool IsArmHardFloat(lldb_private::Thread &thread) const; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -76,9 +73,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp index dd3f473..1d54712 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_arm64.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -1661,9 +1660,7 @@ size_t ABISysV_arm64::GetRedZoneSize() const { return 128; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_arm64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -2091,7 +2088,7 @@ if (byte_size || *byte_size == 0) return false; - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); Status error; @@ -2125,10 +2122,10 @@ if (!reg_ctx->ReadRegister(reg_info, reg_value)) return false; - // Make sure we have enough room in "heap_data_ap" - if ((data_offset + *base_byte_size) <= heap_data_ap->GetByteSize()) { + // Make sure we have enough room in "heap_data_up" + if ((data_offset + *base_byte_size) <= heap_data_up->GetByteSize()) { const size_t bytes_copied = reg_value.GetAsMemoryData( - reg_info, heap_data_ap->GetBytes() + data_offset, *base_byte_size, + reg_info, heap_data_up->GetBytes() + data_offset, *base_byte_size, byte_order, error); if (bytes_copied != *base_byte_size) return false; @@ -2139,7 +2136,7 @@ } data.SetByteOrder(byte_order); data.SetAddressByteSize(exe_ctx.GetProcessRef().GetAddressByteSize()); - data.SetData(DataBufferSP(heap_data_ap.release())); + data.SetData(DataBufferSP(heap_data_up.release())); return true; } } @@ -2164,7 +2161,7 @@ const size_t curr_byte_size = std::min<size_t>(8, bytes_left); const size_t bytes_copied = reg_value.GetAsMemoryData( - reg_info, heap_data_ap->GetBytes() + data_offset, curr_byte_size, + reg_info, heap_data_up->GetBytes() + data_offset, curr_byte_size, byte_order, error); if (bytes_copied == 0) return false; @@ -2205,15 +2202,15 @@ return false; if (exe_ctx.GetProcessRef().ReadMemory( - value_addr, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), - error) != heap_data_ap->GetByteSize()) { + value_addr, heap_data_up->GetBytes(), heap_data_up->GetByteSize(), + error) != heap_data_up->GetByteSize()) { return false; } } data.SetByteOrder(byte_order); data.SetAddressByteSize(exe_ctx.GetProcessRef().GetAddressByteSize()); - data.SetData(DataBufferSP(heap_data_ap.release())); + data.SetData(DataBufferSP(heap_data_up.release())); return true; } @@ -2267,7 +2264,7 @@ if (x1_reg_info) { if (*byte_size <= x0_reg_info->byte_size + x1_reg_info->byte_size) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); @@ -2277,13 +2274,13 @@ reg_ctx->ReadRegister(x1_reg_info, x1_reg_value)) { Status error; if (x0_reg_value.GetAsMemoryData( - x0_reg_info, heap_data_ap->GetBytes() + 0, 8, + x0_reg_info, heap_data_up->GetBytes() + 0, 8, byte_order, error) && x1_reg_value.GetAsMemoryData( - x1_reg_info, heap_data_ap->GetBytes() + 8, 8, + x1_reg_info, heap_data_up->GetBytes() + 8, 8, byte_order, error)) { DataExtractor data( - DataBufferSP(heap_data_ap.release()), byte_order, + DataBufferSP(heap_data_up.release()), byte_order, exe_ctx.GetProcessRef().GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( @@ -2365,16 +2362,16 @@ const RegisterInfo *v0_info = reg_ctx->GetRegisterInfoByName("v0", 0); if (v0_info) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(v0_info, reg_value)) { Status error; - if (reg_value.GetAsMemoryData(v0_info, heap_data_ap->GetBytes(), - heap_data_ap->GetByteSize(), byte_order, + if (reg_value.GetAsMemoryData(v0_info, heap_data_up->GetBytes(), + heap_data_up->GetByteSize(), byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), byte_order, + DataExtractor data(DataBufferSP(heap_data_up.release()), byte_order, exe_ctx.GetProcessRef().GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( &thread, return_compiler_type, ConstString(""), data); @@ -2413,9 +2410,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString ABISysV_arm64::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h index b36b454..1fbdc79 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h
@@ -1,9 +1,8 @@ //===-- ABISysV_arm64.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -71,9 +70,7 @@ bool GetPointerReturnRegister(const char *&name) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -83,9 +80,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp index ca40e9a..9364756 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_hexagon.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -1010,9 +1009,7 @@ */ size_t ABISysV_hexagon::GetRedZoneSize() const { return 0; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_hexagon::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -1104,7 +1101,7 @@ sp -= argSize; // write this argument onto the stack of the host process - proc->WriteMemory(sp, arg.data_ap.get(), arg.size, error); + proc->WriteMemory(sp, arg.data_up.get(), arg.size, error); if (error.Fail()) return false; @@ -1295,9 +1292,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_hexagon::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h index 6e39c07..459b631 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h
@@ -1,10 +1,9 @@ //===-- ABISysV_hexagon.h ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -72,9 +71,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -84,9 +81,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp index 3358eb8..05f5dba 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp
@@ -1,9 +1,8 @@ //===----------------------- ABISysV_i386.cpp -------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "ABISysV_i386.h" @@ -193,9 +192,7 @@ return g_register_infos; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_i386::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -649,19 +646,20 @@ if (*byte_size <= vec_reg->byte_size) { ProcessSP process_sp(thread.GetProcess()); if (process_sp) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(vec_reg, reg_value)) { Status error; - if (reg_value.GetAsMemoryData(vec_reg, heap_data_ap->GetBytes(), - heap_data_ap->GetByteSize(), + if (reg_value.GetAsMemoryData(vec_reg, heap_data_up->GetBytes(), + heap_data_up->GetByteSize(), byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), - byte_order, process_sp->GetTarget() - .GetArchitecture() - .GetAddressByteSize()); + DataExtractor data(DataBufferSP(heap_data_up.release()), + byte_order, + process_sp->GetTarget() + .GetArchitecture() + .GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( &thread, return_compiler_type, ConstString(""), data); } @@ -673,7 +671,7 @@ if (vec_reg2) { ProcessSP process_sp(thread.GetProcess()); if (process_sp) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; @@ -682,17 +680,18 @@ reg_ctx->ReadRegister(vec_reg2, reg_value2)) { Status error; - if (reg_value.GetAsMemoryData(vec_reg, heap_data_ap->GetBytes(), + if (reg_value.GetAsMemoryData(vec_reg, heap_data_up->GetBytes(), vec_reg->byte_size, byte_order, error) && reg_value2.GetAsMemoryData( - vec_reg2, heap_data_ap->GetBytes() + vec_reg->byte_size, - heap_data_ap->GetByteSize() - vec_reg->byte_size, + vec_reg2, heap_data_up->GetBytes() + vec_reg->byte_size, + heap_data_up->GetByteSize() - vec_reg->byte_size, byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), - byte_order, process_sp->GetTarget() - .GetArchitecture() - .GetAddressByteSize()); + DataExtractor data(DataBufferSP(heap_data_up.release()), + byte_order, + process_sp->GetTarget() + .GetArchitecture() + .GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( &thread, return_compiler_type, ConstString(""), data); } @@ -838,9 +837,7 @@ PluginManager::UnregisterPlugin(CreateInstance); } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_i386::GetPluginNameStatic() { static ConstString g_name("sysv-i386");
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h index 336a275..982bdd6 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h
@@ -1,9 +1,8 @@ //===------------------- ABISysV_i386.h -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -77,9 +76,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -87,9 +84,7 @@ static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ static lldb_private::ConstString GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp index 6f3d2e3..121c730 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_mips.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -550,9 +549,7 @@ size_t ABISysV_mips::GetRedZoneSize() const { return 0; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_mips::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -1063,9 +1060,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_mips::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h index d23dbe9..6cd9c19 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h
@@ -1,9 +1,8 @@ //===-- ABISysV_mips.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -62,9 +61,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -74,9 +71,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp index 1d6738d..18011cf 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_mips64.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -550,17 +549,12 @@ size_t ABISysV_mips64::GetRedZoneSize() const { return 0; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_mips64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { - const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); - if ((arch_type == llvm::Triple::mips64) || - (arch_type == llvm::Triple::mips64el)) { + if (arch.GetTriple().isMIPS64()) return ABISP(new ABISysV_mips64(process_sp)); - } return ABISP(); } @@ -923,15 +917,15 @@ uint32_t integer_bytes = 0; // True if return values are in FP return registers. - bool use_fp_regs = 0; + bool use_fp_regs = false; // True if we found any non floating point field in structure. - bool found_non_fp_field = 0; + bool found_non_fp_field = false; // True if return values are in r2 register. - bool use_r2 = 0; + bool use_r2 = false; // True if return values are in r3 register. - bool use_r3 = 0; + bool use_r3 = false; // True if the result is copied into our data buffer - bool sucess = 0; + bool sucess = false; std::string name; bool is_complex; uint32_t count; @@ -949,9 +943,9 @@ nullptr, nullptr); if (field_compiler_type.IsFloatingPointType(count, is_complex)) - use_fp_regs = 1; + use_fp_regs = true; else - found_non_fp_field = 1; + found_non_fp_field = true; } if (use_fp_regs && !found_non_fp_field) { @@ -1065,20 +1059,20 @@ // structure integer_bytes = integer_bytes + *field_byte_width + padding; // Increase the consumed bytes. - use_r2 = 1; + use_r2 = true; } else { // There isn't enough space left in r2 for this field, so this // will be in r3. integer_bytes = integer_bytes + *field_byte_width + padding; // Increase the consumed bytes. - use_r3 = 1; + use_r3 = true; } } // We already have consumed at-least 8 bytes that means r2 is done, // and this field will be in r3. Check if this field can fit in r3. else if (integer_bytes + *field_byte_width + padding <= 16) { integer_bytes = integer_bytes + *field_byte_width + padding; - use_r3 = 1; + use_r3 = true; } else { // There isn't any space left for this field, this should not // happen as we have already checked the overall size is not @@ -1091,10 +1085,10 @@ // Vector types up to 16 bytes are returned in GP return registers if (type_flags & eTypeIsVector) { if (*byte_size <= 8) - use_r2 = 1; + use_r2 = true; else { - use_r2 = 1; - use_r3 = 1; + use_r2 = true; + use_r3 = true; } } @@ -1106,7 +1100,7 @@ error); if (bytes_copied != r2_info->byte_size) return return_valobj_sp; - sucess = 1; + sucess = true; } if (use_r3) { reg_ctx->ReadRegister(r3_info, r3_value); @@ -1116,7 +1110,7 @@ if (bytes_copied != r3_info->byte_size) return return_valobj_sp; - sucess = 1; + sucess = true; } if (sucess) { // The result is in our data buffer. Create a variable object out of @@ -1214,9 +1208,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_mips64::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h index c7670f4..7da71b3 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h
@@ -1,9 +1,8 @@ //===-- ABISysV_mips64.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -75,9 +74,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -87,9 +84,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp index 1fe7a67..faa9950 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_ppc.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -214,9 +213,7 @@ size_t ABISysV_ppc::GetRedZoneSize() const { return 224; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_ppc::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -619,16 +616,16 @@ if (*byte_size <= altivec_reg->byte_size) { ProcessSP process_sp(thread.GetProcess()); if (process_sp) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(altivec_reg, reg_value)) { Status error; if (reg_value.GetAsMemoryData( - altivec_reg, heap_data_ap->GetBytes(), - heap_data_ap->GetByteSize(), byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), + altivec_reg, heap_data_up->GetBytes(), + heap_data_up->GetByteSize(), byte_order, error)) { + DataExtractor data(DataBufferSP(heap_data_up.release()), byte_order, process_sp->GetTarget() .GetArchitecture() @@ -976,9 +973,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_ppc::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h index 3559cbb..3b19985 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h
@@ -1,9 +1,8 @@ //===-- ABISysV_ppc.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -71,9 +70,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -83,9 +80,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp index fb46b7d..aa79075 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_ppc64.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -65,17 +64,13 @@ return GetProcessSP()->GetByteOrder(); } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_ppc64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { - if (arch.GetTriple().getArch() == llvm::Triple::ppc64 || - arch.GetTriple().getArch() == llvm::Triple::ppc64le) { + if (arch.GetTriple().isPPC64()) return ABISP(new ABISysV_ppc64(process_sp)); - } return ABISP(); } @@ -561,7 +556,7 @@ Thread &m_thread; CompilerType &m_type; uint64_t m_byte_size; - std::unique_ptr<DataBufferHeap> m_data_ap; + std::unique_ptr<DataBufferHeap> m_data_up; int32_t m_src_offs = 0; int32_t m_dst_offs = 0; bool m_packed = false; @@ -578,7 +573,7 @@ RegisterContext *reg_ctx, ProcessSP process_sp) : m_thread(thread), m_type(type), m_byte_size(m_type.GetByteSize(nullptr).getValueOr(0)), - m_data_ap(new DataBufferHeap(m_byte_size, 0)), m_reg_ctx(reg_ctx), + m_data_up(new DataBufferHeap(m_byte_size, 0)), m_reg_ctx(reg_ctx), m_process_sp(process_sp), m_byte_order(process_sp->GetByteOrder()), m_addr_size( process_sp->GetTarget().GetArchitecture().GetAddressByteSize()) {} @@ -687,7 +682,7 @@ // build the ValueObject from our data buffer ValueObjectSP BuildValueObject() { - DataExtractor de(DataBufferSP(m_data_ap.release()), m_byte_order, + DataExtractor de(DataBufferSP(m_data_up.release()), m_byte_order, m_addr_size); return ValueObjectConstResult::Create(&m_thread, m_type, ConstString(""), de); @@ -752,7 +747,7 @@ offs = vr_size - m_byte_size; // copy extracted data to our buffer - memcpy(m_data_ap->GetBytes(), vr_data->GetBytes() + offs, m_byte_size); + memcpy(m_data_up->GetBytes(), vr_data->GetBytes() + offs, m_byte_size); return BuildValueObject(); } @@ -766,7 +761,7 @@ return {}; Status error; - size_t rc = m_process_sp->ReadMemory(addr, m_data_ap->GetBytes(), + size_t rc = m_process_sp->ReadMemory(addr, m_data_up->GetBytes(), m_byte_size, error); if (rc != m_byte_size) { LLDB_LOG(m_log, LOG_PREFIX "Failed to read memory pointed by r3"); @@ -804,7 +799,8 @@ // copy to buffer Status error; size_t rc = val_sp->GetScalar().GetAsMemoryData( - m_data_ap->GetBytes() + m_dst_offs, *elem_size, m_byte_order, error); + m_data_up->GetBytes() + m_dst_offs, *elem_size, m_byte_order, + error); if (rc != *elem_size) { LLDB_LOG(m_log, LOG_PREFIX "Failed to get float data"); return {}; @@ -888,7 +884,7 @@ LOG_PREFIX "Extracting {0} alignment bytes at offset {1}", n, m_src_offs); // get alignment bytes - if (!ExtractFromRegs(m_src_offs, n, m_data_ap->GetBytes() + m_dst_offs)) + if (!ExtractFromRegs(m_src_offs, n, m_data_up->GetBytes() + m_dst_offs)) return false; m_src_offs += n; m_dst_offs += n; @@ -898,7 +894,7 @@ // get field LLDB_LOG(m_log, LOG_PREFIX "Extracting {0} field bytes at offset {1}", size, m_src_offs); - if (!ExtractFromRegs(m_src_offs, size, m_data_ap->GetBytes() + m_dst_offs)) + if (!ExtractFromRegs(m_src_offs, size, m_data_up->GetBytes() + m_dst_offs)) return false; m_src_offs += size; m_dst_offs += size; @@ -1086,9 +1082,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_ppc64::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h index 54f461e..d5fb09e 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h
@@ -1,9 +1,8 @@ //===-- ABISysV_ppc64.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -71,9 +70,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -83,9 +80,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp index d8056ea..abe847b 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_s390x.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -196,9 +195,7 @@ size_t ABISysV_s390x::GetRedZoneSize() const { return 0; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_s390x::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { @@ -743,9 +740,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_s390x::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h index 5433ebb..13df477 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h
@@ -1,9 +1,8 @@ //===-- ABISysV_s390x.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -63,9 +62,7 @@ const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -75,9 +72,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp index dc3e475..6c7b45f 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- ABISysV_x86_64.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,6 +30,8 @@ #include "lldb/Utility/RegisterValue.h" #include "lldb/Utility/Status.h" +#include <vector> + using namespace lldb; using namespace lldb_private; @@ -99,960 +100,90 @@ }; static RegisterInfo g_register_infos[] = { - // NAME ALT SZ OFF ENCODING FORMAT EH_FRAME - // DWARF GENERIC PROCESS PLUGIN - // LLDB NATIVE - // ======== ======= == === ============= =================== - // ======================= ===================== - // =========================== ===================== ====================== - {"rax", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rax, dwarf_rax, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rbx", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rbx, dwarf_rbx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rcx", - "arg4", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rcx, dwarf_rcx, LLDB_REGNUM_GENERIC_ARG4, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rdx", - "arg3", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rdx, dwarf_rdx, LLDB_REGNUM_GENERIC_ARG3, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rsi", - "arg2", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rsi, dwarf_rsi, LLDB_REGNUM_GENERIC_ARG2, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rdi", - "arg1", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rdi, dwarf_rdi, LLDB_REGNUM_GENERIC_ARG1, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rbp", - "fp", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rbp, dwarf_rbp, LLDB_REGNUM_GENERIC_FP, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rsp", - "sp", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rsp, dwarf_rsp, LLDB_REGNUM_GENERIC_SP, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r8", - "arg5", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r8, dwarf_r8, LLDB_REGNUM_GENERIC_ARG5, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r9", - "arg6", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r9, dwarf_r9, LLDB_REGNUM_GENERIC_ARG6, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r10", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r10, dwarf_r10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r11", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r11, dwarf_r11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r12", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r12, dwarf_r12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r13", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r13, dwarf_r13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r14", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r14, dwarf_r14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"r15", - nullptr, - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_r15, dwarf_r15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rip", - "pc", - 8, - 0, - eEncodingUint, - eFormatHex, - {dwarf_rip, dwarf_rip, LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"rflags", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_REGNUM_GENERIC_FLAGS, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"cs", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ss", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ds", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"es", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"fs", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"gs", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm0", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm0, dwarf_stmm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm1", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm1, dwarf_stmm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm2", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm2, dwarf_stmm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm3", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm3, dwarf_stmm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm4", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm4, dwarf_stmm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm5", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm5, dwarf_stmm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm6", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm6, dwarf_stmm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"stmm7", - nullptr, - 10, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_stmm7, dwarf_stmm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"fctrl", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"fstat", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ftag", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"fiseg", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"fioff", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"foseg", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"fooff", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"fop", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm0", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm0, dwarf_xmm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm1", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm1, dwarf_xmm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm2", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm2, dwarf_xmm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm3", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm3, dwarf_xmm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm4", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm4, dwarf_xmm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm5", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm5, dwarf_xmm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm6", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm6, dwarf_xmm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm7", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm7, dwarf_xmm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm8", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm8, dwarf_xmm8, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm9", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm9, dwarf_xmm9, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm10", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm10, dwarf_xmm10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm11", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm11, dwarf_xmm11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm12", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm12, dwarf_xmm12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm13", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm13, dwarf_xmm13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm14", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm14, dwarf_xmm14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"xmm15", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_xmm15, dwarf_xmm15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"mxcsr", - nullptr, - 4, - 0, - eEncodingUint, - eFormatHex, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm0", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm0, dwarf_ymm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm1", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm1, dwarf_ymm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm2", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm2, dwarf_ymm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm3", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm3, dwarf_ymm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm4", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm4, dwarf_ymm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm5", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm5, dwarf_ymm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm6", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm6, dwarf_ymm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm7", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm7, dwarf_ymm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm8", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm8, dwarf_ymm8, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm9", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm9, dwarf_ymm9, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm10", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm10, dwarf_ymm10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm11", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm11, dwarf_ymm11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm12", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm12, dwarf_ymm12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm13", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm13, dwarf_ymm13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm14", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm14, dwarf_ymm14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"ymm15", - nullptr, - 32, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {dwarf_ymm15, dwarf_ymm15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"bnd0", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt64, - {dwarf_bnd0, dwarf_bnd0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"bnd1", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt64, - {dwarf_bnd1, dwarf_bnd1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"bnd2", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt64, - {dwarf_bnd2, dwarf_bnd2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"bnd3", - nullptr, - 16, - 0, - eEncodingVector, - eFormatVectorOfUInt64, - {dwarf_bnd3, dwarf_bnd3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"bndcfgu", - nullptr, - 8, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}, - {"bndstatus", - nullptr, - 8, - 0, - eEncodingVector, - eFormatVectorOfUInt8, - {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, - nullptr, - nullptr, - nullptr, - 0}}; + // clang-format off + // NAME ALT SZ OFF ENCODING FORMAT EH_FRAME DWARF GENERIC LLDB NATIVE + // ======== ======= == === ============= =================== ======================= ===================== =========================== ===================== ====================== + {"rax", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_rax, dwarf_rax, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rbx", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_rbx, dwarf_rbx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rcx", "arg4", 8, 0, eEncodingUint, eFormatHex, {dwarf_rcx, dwarf_rcx, LLDB_REGNUM_GENERIC_ARG4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rdx", "arg3", 8, 0, eEncodingUint, eFormatHex, {dwarf_rdx, dwarf_rdx, LLDB_REGNUM_GENERIC_ARG3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rsi", "arg2", 8, 0, eEncodingUint, eFormatHex, {dwarf_rsi, dwarf_rsi, LLDB_REGNUM_GENERIC_ARG2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rdi", "arg1", 8, 0, eEncodingUint, eFormatHex, {dwarf_rdi, dwarf_rdi, LLDB_REGNUM_GENERIC_ARG1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rbp", "fp", 8, 0, eEncodingUint, eFormatHex, {dwarf_rbp, dwarf_rbp, LLDB_REGNUM_GENERIC_FP, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rsp", "sp", 8, 0, eEncodingUint, eFormatHex, {dwarf_rsp, dwarf_rsp, LLDB_REGNUM_GENERIC_SP, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r8", "arg5", 8, 0, eEncodingUint, eFormatHex, {dwarf_r8, dwarf_r8, LLDB_REGNUM_GENERIC_ARG5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r9", "arg6", 8, 0, eEncodingUint, eFormatHex, {dwarf_r9, dwarf_r9, LLDB_REGNUM_GENERIC_ARG6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r10", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_r10, dwarf_r10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r11", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_r11, dwarf_r11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r12", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_r12, dwarf_r12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r13", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_r13, dwarf_r13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r14", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_r14, dwarf_r14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"r15", nullptr, 8, 0, eEncodingUint, eFormatHex, {dwarf_r15, dwarf_r15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rip", "pc", 8, 0, eEncodingUint, eFormatHex, {dwarf_rip, dwarf_rip, LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"rflags", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_REGNUM_GENERIC_FLAGS, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"cs", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ss", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ds", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"es", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"fs", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"gs", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm0", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm0, dwarf_stmm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm1", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm1, dwarf_stmm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm2", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm2, dwarf_stmm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm3", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm3, dwarf_stmm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm4", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm4, dwarf_stmm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm5", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm5, dwarf_stmm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm6", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm6, dwarf_stmm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"stmm7", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_stmm7, dwarf_stmm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"fctrl", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"fstat", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ftag", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"fiseg", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"fioff", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"foseg", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"fooff", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"fop", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm0", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm0, dwarf_xmm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm1", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm1, dwarf_xmm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm2", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm2, dwarf_xmm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm3", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm3, dwarf_xmm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm4", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm4, dwarf_xmm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm5", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm5, dwarf_xmm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm6", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm6, dwarf_xmm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm7", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm7, dwarf_xmm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm8", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm8, dwarf_xmm8, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm9", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm9, dwarf_xmm9, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm10", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm10, dwarf_xmm10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm11", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm11, dwarf_xmm11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm12", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm12, dwarf_xmm12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm13", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm13, dwarf_xmm13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm14", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm14, dwarf_xmm14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"xmm15", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_xmm15, dwarf_xmm15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"mxcsr", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm0", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm0, dwarf_ymm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm1", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm1, dwarf_ymm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm2", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm2, dwarf_ymm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm3", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm3, dwarf_ymm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm4", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm4, dwarf_ymm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm5", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm5, dwarf_ymm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm6", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm6, dwarf_ymm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm7", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm7, dwarf_ymm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm8", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm8, dwarf_ymm8, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm9", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm9, dwarf_ymm9, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm10", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm10, dwarf_ymm10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm11", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm11, dwarf_ymm11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm12", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm12, dwarf_ymm12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm13", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm13, dwarf_ymm13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm14", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm14, dwarf_ymm14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"ymm15", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {dwarf_ymm15, dwarf_ymm15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"bnd0", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64, {dwarf_bnd0, dwarf_bnd0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"bnd1", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64, {dwarf_bnd1, dwarf_bnd1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"bnd2", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64, {dwarf_bnd2, dwarf_bnd2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"bnd3", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64, {dwarf_bnd3, dwarf_bnd3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"bndcfgu", nullptr, 8, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + {"bndstatus",nullptr, 8, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, + // clang-format on +}; static const uint32_t k_num_register_infos = llvm::array_lengthof(g_register_infos); @@ -1085,14 +216,24 @@ size_t ABISysV_x86_64::GetRedZoneSize() const { return 128; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ABISP ABISysV_x86_64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { - if (arch.GetTriple().getArch() == llvm::Triple::x86_64) { - return ABISP(new ABISysV_x86_64(process_sp)); + const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); + const llvm::Triple::OSType os_type = arch.GetTriple().getOS(); + if (arch_type == llvm::Triple::x86_64) { + switch(os_type) { + case llvm::Triple::OSType::MacOSX: + case llvm::Triple::OSType::Linux: + case llvm::Triple::OSType::FreeBSD: + case llvm::Triple::OSType::NetBSD: + case llvm::Triple::OSType::Solaris: + case llvm::Triple::OSType::UnknownOS: + return ABISP(new ABISysV_x86_64(process_sp)); + default: + return ABISP(); + } } return ABISP(); } @@ -1500,19 +641,20 @@ if (*byte_size <= altivec_reg->byte_size) { ProcessSP process_sp(thread.GetProcess()); if (process_sp) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(altivec_reg, reg_value)) { Status error; if (reg_value.GetAsMemoryData( - altivec_reg, heap_data_ap->GetBytes(), - heap_data_ap->GetByteSize(), byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), - byte_order, process_sp->GetTarget() - .GetArchitecture() - .GetAddressByteSize()); + altivec_reg, heap_data_up->GetBytes(), + heap_data_up->GetByteSize(), byte_order, error)) { + DataExtractor data(DataBufferSP(heap_data_up.release()), + byte_order, + process_sp->GetTarget() + .GetArchitecture() + .GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( &thread, return_compiler_type, ConstString(""), data); } @@ -1524,7 +666,7 @@ if (altivec_reg2) { ProcessSP process_sp(thread.GetProcess()); if (process_sp) { - std::unique_ptr<DataBufferHeap> heap_data_ap( + std::unique_ptr<DataBufferHeap> heap_data_up( new DataBufferHeap(*byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; @@ -1534,17 +676,18 @@ Status error; if (reg_value.GetAsMemoryData( - altivec_reg, heap_data_ap->GetBytes(), + altivec_reg, heap_data_up->GetBytes(), altivec_reg->byte_size, byte_order, error) && reg_value2.GetAsMemoryData( altivec_reg2, - heap_data_ap->GetBytes() + altivec_reg->byte_size, - heap_data_ap->GetByteSize() - altivec_reg->byte_size, + heap_data_up->GetBytes() + altivec_reg->byte_size, + heap_data_up->GetByteSize() - altivec_reg->byte_size, byte_order, error)) { - DataExtractor data(DataBufferSP(heap_data_ap.release()), - byte_order, process_sp->GetTarget() - .GetArchitecture() - .GetAddressByteSize()); + DataExtractor data(DataBufferSP(heap_data_up.release()), + byte_order, + process_sp->GetTarget() + .GetArchitecture() + .GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( &thread, return_compiler_type, ConstString(""), data); } @@ -1559,6 +702,55 @@ return return_valobj_sp; } +// The compiler will flatten the nested aggregate type into single +// layer and push the value to stack +// This helper function will flatten an aggregate type +// and return true if it can be returned in register(s) by value +// return false if the aggregate is in memory +static bool FlattenAggregateType( + Thread &thread, ExecutionContext &exe_ctx, + CompilerType &return_compiler_type, + uint32_t data_byte_offset, + std::vector<uint32_t> &aggregate_field_offsets, + std::vector<CompilerType> &aggregate_compiler_types) { + + const uint32_t num_children = return_compiler_type.GetNumFields(); + for (uint32_t idx = 0; idx < num_children; ++idx) { + std::string name; + bool is_signed; + uint32_t count; + bool is_complex; + + uint64_t field_bit_offset = 0; + CompilerType field_compiler_type = return_compiler_type.GetFieldAtIndex( + idx, name, &field_bit_offset, nullptr, nullptr); + llvm::Optional<uint64_t> field_bit_width = + field_compiler_type.GetBitSize(&thread); + + // if we don't know the size of the field (e.g. invalid type), exit + if (!field_bit_width || *field_bit_width == 0) { + return false; + } + + uint32_t field_byte_offset = field_bit_offset / 8 + data_byte_offset; + + const uint32_t field_type_flags = field_compiler_type.GetTypeInfo(); + if (field_compiler_type.IsIntegerOrEnumerationType(is_signed) || + field_compiler_type.IsPointerType() || + field_compiler_type.IsFloatingPointType(count, is_complex)) { + aggregate_field_offsets.push_back(field_byte_offset); + aggregate_compiler_types.push_back(field_compiler_type); + } else if (field_type_flags & eTypeHasChildren) { + if (!FlattenAggregateType(thread, exe_ctx, field_compiler_type, + field_byte_offset, aggregate_field_offsets, + aggregate_compiler_types)) { + return false; + } + } + } + return true; +} + ValueObjectSP ABISysV_x86_64::GetReturnValueObjectImpl( Thread &thread, CompilerType &return_compiler_type) const { ValueObjectSP return_valobj_sp; @@ -1581,10 +773,17 @@ if (return_compiler_type.IsAggregateType()) { Target *target = exe_ctx.GetTargetPtr(); bool is_memory = true; - if (*bit_width <= 128) { - ByteOrder target_byte_order = target->GetArchitecture().GetByteOrder(); + std::vector<uint32_t> aggregate_field_offsets; + std::vector<CompilerType> aggregate_compiler_types; + if (return_compiler_type.GetTypeSystem()->CanPassInRegisters( + return_compiler_type) && + *bit_width <= 128 && + FlattenAggregateType(thread, exe_ctx, return_compiler_type, + 0, aggregate_field_offsets, + aggregate_compiler_types)) { + ByteOrder byte_order = target->GetArchitecture().GetByteOrder(); DataBufferSP data_sp(new DataBufferHeap(16, 0)); - DataExtractor return_ext(data_sp, target_byte_order, + DataExtractor return_ext(data_sp, byte_order, target->GetArchitecture().GetAddressByteSize()); const RegisterInfo *rax_info = @@ -1614,36 +813,27 @@ uint32_t integer_bytes = 0; // Tracks how much of the rax/rds registers we've consumed so far - const uint32_t num_children = return_compiler_type.GetNumFields(); + // in case of the returned type is a subclass of non-abstract-base class + // it will have a padding to skip the base content + if (aggregate_field_offsets.size()) { + fp_bytes = aggregate_field_offsets[0]; + integer_bytes = aggregate_field_offsets[0]; + } + + const uint32_t num_children = aggregate_compiler_types.size(); // Since we are in the small struct regime, assume we are not in memory. is_memory = false; - for (uint32_t idx = 0; idx < num_children; idx++) { - std::string name; - uint64_t field_bit_offset = 0; bool is_signed; - bool is_complex; uint32_t count; + bool is_complex; - CompilerType field_compiler_type = return_compiler_type.GetFieldAtIndex( - idx, name, &field_bit_offset, nullptr, nullptr); - llvm::Optional<uint64_t> field_bit_width = - field_compiler_type.GetBitSize(&thread); + CompilerType field_compiler_type = aggregate_compiler_types[idx]; + uint32_t field_byte_width = (uint32_t) (*field_compiler_type.GetByteSize(&thread)); + uint32_t field_byte_offset = aggregate_field_offsets[idx]; - // if we don't know the size of the field (e.g. invalid type), just - // bail out - if (!field_bit_width || *field_bit_width == 0) - break; - - // If there are any unaligned fields, this is stored in memory. - if (field_bit_offset % *field_bit_width != 0) { - is_memory = true; - break; - } - - uint32_t field_byte_width = *field_bit_width / 8; - uint32_t field_byte_offset = field_bit_offset / 8; + uint32_t field_bit_width = field_byte_width * 8; DataExtractor *copy_from_extractor = nullptr; uint32_t copy_from_offset = 0; @@ -1675,10 +865,10 @@ } } else if (field_compiler_type.IsFloatingPointType(count, is_complex)) { // Structs with long doubles are always passed in memory. - if (*field_bit_width == 128) { + if (field_bit_width == 128) { is_memory = true; break; - } else if (*field_bit_width == 64) { + } else if (field_bit_width == 64) { // These have to be in a single xmm register. if (fp_bytes == 0) copy_from_extractor = &xmm0_data; @@ -1687,7 +877,7 @@ copy_from_offset = 0; fp_bytes += field_byte_width; - } else if (*field_bit_width == 32) { + } else if (field_bit_width == 32) { // This one is kind of complicated. If we are in an "eightbyte" // with another float, we'll be stuffed into an xmm register with // it. If we are in an "eightbyte" with one or more ints, then we @@ -1696,18 +886,15 @@ if (field_byte_offset % 8 == 0) { // We are at the beginning of one of the eightbytes, so check the // next element (if any) - if (idx == num_children - 1) + if (idx == num_children - 1) { in_gpr = false; - else { - uint64_t next_field_bit_offset = 0; + } else { CompilerType next_field_compiler_type = - return_compiler_type.GetFieldAtIndex(idx + 1, name, - &next_field_bit_offset, - nullptr, nullptr); + aggregate_compiler_types[idx + 1]; if (next_field_compiler_type.IsIntegerOrEnumerationType( - is_signed)) + is_signed)) { in_gpr = true; - else { + } else { copy_from_offset = 0; in_gpr = false; } @@ -1716,18 +903,15 @@ // We are inside of an eightbyte, so see if the field before us // is floating point: This could happen if somebody put padding // in the structure. - if (idx == 0) + if (idx == 0) { in_gpr = false; - else { - uint64_t prev_field_bit_offset = 0; + } else { CompilerType prev_field_compiler_type = - return_compiler_type.GetFieldAtIndex(idx - 1, name, - &prev_field_bit_offset, - nullptr, nullptr); + aggregate_compiler_types[idx - 1]; if (prev_field_compiler_type.IsIntegerOrEnumerationType( - is_signed)) + is_signed)) { in_gpr = true; - else { + } else { copy_from_offset = 4; in_gpr = false; } @@ -1760,7 +944,6 @@ } } } - // These two tests are just sanity checks. If I somehow get the type // calculation wrong above it is better to just return nothing than to // assert or crash. @@ -1769,13 +952,11 @@ if (copy_from_offset + field_byte_width > copy_from_extractor->GetByteSize()) return return_valobj_sp; - copy_from_extractor->CopyByteOrderedData( copy_from_offset, field_byte_width, data_sp->GetBytes() + field_byte_offset, field_byte_width, - target_byte_order); + byte_order); } - if (!is_memory) { // The result is in our data buffer. Let's make a variable object out // of it: @@ -1896,9 +1077,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ABISysV_x86_64::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h b/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h index 4afc8c4..f6704af 100644 --- a/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h
@@ -1,9 +1,8 @@ //===-- ABISysV_x86_64.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -73,9 +72,7 @@ bool GetPointerReturnRegister(const char *&name) override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); @@ -85,9 +82,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/ABIWindows_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/ABIWindows_x86_64.cpp new file mode 100644 index 0000000..5dc7717 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/ABIWindows_x86_64.cpp
@@ -0,0 +1,1805 @@ +//===-- ABIWindows_x86_64.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 "ABIWindows_x86_64.h" + +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/ADT/Triple.h" + +#include "lldb/Core/Module.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Core/Value.h" +#include "lldb/Core/ValueObjectConstResult.h" +#include "lldb/Core/ValueObjectMemory.h" +#include "lldb/Core/ValueObjectRegister.h" +#include "lldb/Symbol/UnwindPlan.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/RegisterContext.h" +#include "lldb/Target/StackFrame.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Utility/ConstString.h" +#include "lldb/Utility/DataExtractor.h" +#include "lldb/Utility/Log.h" +#include "lldb/Utility/RegisterValue.h" +#include "lldb/Utility/Status.h" + +using namespace lldb; +using namespace lldb_private; + +enum dwarf_regnums { + dwarf_rax = 0, + dwarf_rdx, + dwarf_rcx, + dwarf_rbx, + dwarf_rsi, + dwarf_rdi, + dwarf_rbp, + dwarf_rsp, + dwarf_r8, + dwarf_r9, + dwarf_r10, + dwarf_r11, + dwarf_r12, + dwarf_r13, + dwarf_r14, + dwarf_r15, + dwarf_rip, + dwarf_xmm0, + dwarf_xmm1, + dwarf_xmm2, + dwarf_xmm3, + dwarf_xmm4, + dwarf_xmm5, + dwarf_xmm6, + dwarf_xmm7, + dwarf_xmm8, + dwarf_xmm9, + dwarf_xmm10, + dwarf_xmm11, + dwarf_xmm12, + dwarf_xmm13, + dwarf_xmm14, + dwarf_xmm15, + dwarf_stmm0, + dwarf_stmm1, + dwarf_stmm2, + dwarf_stmm3, + dwarf_stmm4, + dwarf_stmm5, + dwarf_stmm6, + dwarf_stmm7, + dwarf_ymm0, + dwarf_ymm1, + dwarf_ymm2, + dwarf_ymm3, + dwarf_ymm4, + dwarf_ymm5, + dwarf_ymm6, + dwarf_ymm7, + dwarf_ymm8, + dwarf_ymm9, + dwarf_ymm10, + dwarf_ymm11, + dwarf_ymm12, + dwarf_ymm13, + dwarf_ymm14, + dwarf_ymm15, + dwarf_bnd0 = 126, + dwarf_bnd1, + dwarf_bnd2, + dwarf_bnd3 +}; + +static RegisterInfo g_register_infos[] = { + // NAME ALT SZ OFF ENCODING FORMAT EH_FRAME + // DWARF GENERIC PROCESS PLUGIN + // LLDB NATIVE + // ======== ======= == === ============= =================== + // ======================= ===================== + // =========================== ===================== ====================== + {"rax", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rax, dwarf_rax, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rbx", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rbx, dwarf_rbx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rcx", + "arg1", + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rcx, dwarf_rcx, LLDB_REGNUM_GENERIC_ARG1, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rdx", + "arg2", + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rdx, dwarf_rdx, LLDB_REGNUM_GENERIC_ARG2, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rsi", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rsi, dwarf_rsi, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rdi", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rdi, dwarf_rdi, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rbp", + "fp", + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rbp, dwarf_rbp, LLDB_REGNUM_GENERIC_FP, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rsp", + "sp", + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rsp, dwarf_rsp, LLDB_REGNUM_GENERIC_SP, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r8", + "arg3", + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r8, dwarf_r8, LLDB_REGNUM_GENERIC_ARG3, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r9", + "arg4", + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r9, dwarf_r9, LLDB_REGNUM_GENERIC_ARG4, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r10", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r10, dwarf_r10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r11", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r11, dwarf_r11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r12", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r12, dwarf_r12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r13", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r13, dwarf_r13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r14", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r14, dwarf_r14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"r15", + nullptr, + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_r15, dwarf_r15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rip", + "pc", + 8, + 0, + eEncodingUint, + eFormatHex, + {dwarf_rip, dwarf_rip, LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"rflags", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_REGNUM_GENERIC_FLAGS, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"cs", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ss", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ds", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"es", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"fs", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"gs", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm0", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm0, dwarf_stmm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm1", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm1, dwarf_stmm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm2", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm2, dwarf_stmm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm3", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm3, dwarf_stmm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm4", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm4, dwarf_stmm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm5", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm5, dwarf_stmm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm6", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm6, dwarf_stmm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"stmm7", + nullptr, + 10, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_stmm7, dwarf_stmm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"fctrl", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"fstat", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ftag", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"fiseg", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"fioff", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"foseg", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"fooff", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"fop", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm0", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm0, dwarf_xmm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm1", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm1, dwarf_xmm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm2", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm2, dwarf_xmm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm3", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm3, dwarf_xmm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm4", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm4, dwarf_xmm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm5", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm5, dwarf_xmm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm6", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm6, dwarf_xmm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm7", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm7, dwarf_xmm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm8", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm8, dwarf_xmm8, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm9", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm9, dwarf_xmm9, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm10", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm10, dwarf_xmm10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm11", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm11, dwarf_xmm11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm12", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm12, dwarf_xmm12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm13", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm13, dwarf_xmm13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm14", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm14, dwarf_xmm14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"xmm15", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_xmm15, dwarf_xmm15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"mxcsr", + nullptr, + 4, + 0, + eEncodingUint, + eFormatHex, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm0", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm0, dwarf_ymm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm1", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm1, dwarf_ymm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm2", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm2, dwarf_ymm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm3", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm3, dwarf_ymm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm4", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm4, dwarf_ymm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm5", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm5, dwarf_ymm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm6", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm6, dwarf_ymm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm7", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm7, dwarf_ymm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm8", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm8, dwarf_ymm8, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm9", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm9, dwarf_ymm9, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm10", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm10, dwarf_ymm10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm11", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm11, dwarf_ymm11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm12", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm12, dwarf_ymm12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm13", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm13, dwarf_ymm13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm14", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm14, dwarf_ymm14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"ymm15", + nullptr, + 32, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {dwarf_ymm15, dwarf_ymm15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"bnd0", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt64, + {dwarf_bnd0, dwarf_bnd0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"bnd1", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt64, + {dwarf_bnd1, dwarf_bnd1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"bnd2", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt64, + {dwarf_bnd2, dwarf_bnd2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"bnd3", + nullptr, + 16, + 0, + eEncodingVector, + eFormatVectorOfUInt64, + {dwarf_bnd3, dwarf_bnd3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"bndcfgu", + nullptr, + 8, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}, + {"bndstatus", + nullptr, + 8, + 0, + eEncodingVector, + eFormatVectorOfUInt8, + {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, + nullptr, + nullptr, + nullptr, + 0}}; + +static const uint32_t k_num_register_infos = + llvm::array_lengthof(g_register_infos); +static bool g_register_info_names_constified = false; + +const lldb_private::RegisterInfo * +ABIWindows_x86_64::GetRegisterInfoArray(uint32_t &count) { + // Make the C-string names and alt_names for the register infos into const + // C-string values by having the ConstString unique the names in the global + // constant C-string pool. + if (!g_register_info_names_constified) { + g_register_info_names_constified = true; + for (uint32_t i = 0; i < k_num_register_infos; ++i) { + if (g_register_infos[i].name) + g_register_infos[i].name = + ConstString(g_register_infos[i].name).GetCString(); + if (g_register_infos[i].alt_name) + g_register_infos[i].alt_name = + ConstString(g_register_infos[i].alt_name).GetCString(); + } + } + count = k_num_register_infos; + return g_register_infos; +} + +bool ABIWindows_x86_64::GetPointerReturnRegister(const char *&name) { + name = "rax"; + return true; +} + +size_t ABIWindows_x86_64::GetRedZoneSize() const { return 0; } + +//------------------------------------------------------------------ +// Static Functions +//------------------------------------------------------------------ + +ABISP +ABIWindows_x86_64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { + if (arch.GetTriple().getArch() == llvm::Triple::x86_64 && + arch.GetTriple().isOSWindows()) { + return ABISP(new ABIWindows_x86_64(process_sp)); + } + return ABISP(); +} + +bool ABIWindows_x86_64::PrepareTrivialCall(Thread &thread, addr_t sp, + addr_t func_addr, addr_t return_addr, + llvm::ArrayRef<addr_t> args) const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + + if (log) { + StreamString s; + s.Printf("ABIWindows_x86_64::PrepareTrivialCall (tid = 0x%" PRIx64 + ", sp = 0x%" PRIx64 ", func_addr = 0x%" PRIx64 + ", return_addr = 0x%" PRIx64, + thread.GetID(), (uint64_t)sp, (uint64_t)func_addr, + (uint64_t)return_addr); + + for (size_t i = 0; i < args.size(); ++i) + s.Printf(", arg%" PRIu64 " = 0x%" PRIx64, static_cast<uint64_t>(i + 1), + args[i]); + s.PutCString(")"); + log->PutString(s.GetString()); + } + + RegisterContext *reg_ctx = thread.GetRegisterContext().get(); + if (!reg_ctx) + return false; + + const RegisterInfo *reg_info = nullptr; + + if (args.size() > 4) // Windows x64 only put first 4 arguments into registers + return false; + + for (size_t i = 0; i < args.size(); ++i) { + reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric, + LLDB_REGNUM_GENERIC_ARG1 + i); + if (log) + log->Printf("About to write arg%" PRIu64 " (0x%" PRIx64 ") into %s", + static_cast<uint64_t>(i + 1), args[i], reg_info->name); + if (!reg_ctx->WriteRegisterFromUnsigned(reg_info, args[i])) + return false; + } + + // First, align the SP + + if (log) + log->Printf("16-byte aligning SP: 0x%" PRIx64 " to 0x%" PRIx64, + (uint64_t)sp, (uint64_t)(sp & ~0xfull)); + + sp &= ~(0xfull); // 16-byte alignment + + sp -= 8; // return address + + Status error; + const RegisterInfo *pc_reg_info = + reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); + const RegisterInfo *sp_reg_info = + reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP); + ProcessSP process_sp(thread.GetProcess()); + + RegisterValue reg_value; + if (log) + log->Printf("Pushing the return address onto the stack: 0x%" PRIx64 + ": 0x%" PRIx64, + (uint64_t)sp, (uint64_t)return_addr); + + // Save return address onto the stack + if (!process_sp->WritePointerToMemory(sp, return_addr, error)) + return false; + + // %rsp is set to the actual stack value. + + if (log) + log->Printf("Writing SP: 0x%" PRIx64, (uint64_t)sp); + + if (!reg_ctx->WriteRegisterFromUnsigned(sp_reg_info, sp)) + return false; + + // %rip is set to the address of the called function. + + if (log) + log->Printf("Writing IP: 0x%" PRIx64, (uint64_t)func_addr); + + if (!reg_ctx->WriteRegisterFromUnsigned(pc_reg_info, func_addr)) + return false; + + return true; +} + +static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, + bool is_signed, Thread &thread, + uint32_t *argument_register_ids, + unsigned int ¤t_argument_register, + addr_t ¤t_stack_argument) { + if (bit_width > 64) + return false; // Scalar can't hold large integer arguments + + if (current_argument_register < 4) { // Windows pass first 4 arguments to register + scalar = thread.GetRegisterContext()->ReadRegisterAsUnsigned( + argument_register_ids[current_argument_register], 0); + current_argument_register++; + if (is_signed) + scalar.SignExtend(bit_width); + return true; + } + uint32_t byte_size = (bit_width + (CHAR_BIT - 1)) / CHAR_BIT; + Status error; + if (thread.GetProcess()->ReadScalarIntegerFromMemory( + current_stack_argument, byte_size, is_signed, scalar, error)) { + current_stack_argument += byte_size; + return true; + } + return false; +} + +bool ABIWindows_x86_64::GetArgumentValues(Thread &thread, + ValueList &values) const { + unsigned int num_values = values.GetSize(); + unsigned int value_index; + + // Extract the register context so we can read arguments from registers + + RegisterContext *reg_ctx = thread.GetRegisterContext().get(); + + if (!reg_ctx) + return false; + + // Get the pointer to the first stack argument so we have a place to start + // when reading data + + addr_t sp = reg_ctx->GetSP(0); + + if (!sp) + return false; + + addr_t current_stack_argument = sp + 8; // jump over return address + + uint32_t argument_register_ids[4]; + + argument_register_ids[0] = + reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1) + ->kinds[eRegisterKindLLDB]; + argument_register_ids[1] = + reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG2) + ->kinds[eRegisterKindLLDB]; + argument_register_ids[2] = + reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG3) + ->kinds[eRegisterKindLLDB]; + argument_register_ids[3] = + reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG4) + ->kinds[eRegisterKindLLDB]; + + unsigned int current_argument_register = 0; + + for (value_index = 0; value_index < num_values; ++value_index) { + Value *value = values.GetValueAtIndex(value_index); + + if (!value) + return false; + + CompilerType compiler_type = value->GetCompilerType(); + llvm::Optional<uint64_t> bit_size = compiler_type.GetBitSize(&thread); + if (!bit_size) + return false; + bool is_signed; + + if (compiler_type.IsIntegerOrEnumerationType(is_signed)) { + ReadIntegerArgument(value->GetScalar(), *bit_size, is_signed, thread, + argument_register_ids, current_argument_register, + current_stack_argument); + } else if (compiler_type.IsPointerType()) { + ReadIntegerArgument(value->GetScalar(), *bit_size, false, thread, + argument_register_ids, current_argument_register, + current_stack_argument); + } + } + + return true; +} + +Status ABIWindows_x86_64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; + if (!new_value_sp) { + error.SetErrorString("Empty value object for return value."); + return error; + } + + CompilerType compiler_type = new_value_sp->GetCompilerType(); + if (!compiler_type) { + error.SetErrorString("Null clang type for return value."); + return error; + } + + Thread *thread = frame_sp->GetThread().get(); + + bool is_signed; + uint32_t count; + bool is_complex; + + RegisterContext *reg_ctx = thread->GetRegisterContext().get(); + + bool set_it_simple = false; + if (compiler_type.IsIntegerOrEnumerationType(is_signed) || + compiler_type.IsPointerType()) { + const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("rax", 0); + + DataExtractor data; + Status data_error; + size_t num_bytes = new_value_sp->GetData(data, data_error); + if (data_error.Fail()) { + error.SetErrorStringWithFormat( + "Couldn't convert return value to raw data: %s", + data_error.AsCString()); + return error; + } + lldb::offset_t offset = 0; + if (num_bytes <= 8) { + uint64_t raw_value = data.GetMaxU64(&offset, num_bytes); + + if (reg_ctx->WriteRegisterFromUnsigned(reg_info, raw_value)) + set_it_simple = true; + } else { + error.SetErrorString("We don't support returning longer than 64 bit " + "integer values at present."); + } + } else if (compiler_type.IsFloatingPointType(count, is_complex)) { + if (is_complex) + error.SetErrorString( + "We don't support returning complex values at present"); + else { + llvm::Optional<uint64_t> bit_width = + compiler_type.GetBitSize(frame_sp.get()); + if (!bit_width) { + error.SetErrorString("can't get type size"); + return error; + } + if (*bit_width <= 64) { + const RegisterInfo *xmm0_info = + reg_ctx->GetRegisterInfoByName("xmm0", 0); + RegisterValue xmm0_value; + DataExtractor data; + Status data_error; + size_t num_bytes = new_value_sp->GetData(data, data_error); + if (data_error.Fail()) { + error.SetErrorStringWithFormat( + "Couldn't convert return value to raw data: %s", + data_error.AsCString()); + return error; + } + + unsigned char buffer[16]; + ByteOrder byte_order = data.GetByteOrder(); + + data.CopyByteOrderedData(0, num_bytes, buffer, 16, byte_order); + xmm0_value.SetBytes(buffer, 16, byte_order); + reg_ctx->WriteRegister(xmm0_info, xmm0_value); + set_it_simple = true; + } else { + // Windows doesn't support 80 bit FP + error.SetErrorString( + "Windows-x86_64 doesn't allow FP larger than 64 bits."); + } + } + } + + if (!set_it_simple) { + // Okay we've got a structure or something that doesn't fit in a simple + // register. + // TODO(wanyi): On Windows, if the return type is a struct: + // 1) smaller that 64 bits and return by value -> RAX + // 2) bigger than 64 bits, the caller will allocate memory for that struct + // and pass the struct pointer in RCX then return the pointer in RAX + error.SetErrorString("We only support setting simple integer and float " + "return types at present."); + } + + return error; +} + +ValueObjectSP ABIWindows_x86_64::GetReturnValueObjectSimple( + Thread &thread, CompilerType &return_compiler_type) const { + ValueObjectSP return_valobj_sp; + Value value; + + if (!return_compiler_type) + return return_valobj_sp; + + value.SetCompilerType(return_compiler_type); + + RegisterContext *reg_ctx = thread.GetRegisterContext().get(); + if (!reg_ctx) + return return_valobj_sp; + + const uint32_t type_flags = return_compiler_type.GetTypeInfo(); + if (type_flags & eTypeIsScalar) { + value.SetValueType(Value::eValueTypeScalar); + + bool success = false; + if (type_flags & eTypeIsInteger) { + // Extract the register context so we can read arguments from registers + llvm::Optional<uint64_t> byte_size = + return_compiler_type.GetByteSize(nullptr); + if (!byte_size) + return return_valobj_sp; + uint64_t raw_value = thread.GetRegisterContext()->ReadRegisterAsUnsigned( + reg_ctx->GetRegisterInfoByName("rax", 0), 0); + const bool is_signed = (type_flags & eTypeIsSigned) != 0; + switch (*byte_size) { + default: + break; + + case sizeof(uint64_t): + if (is_signed) + value.GetScalar() = (int64_t)(raw_value); + else + value.GetScalar() = (uint64_t)(raw_value); + success = true; + break; + + case sizeof(uint32_t): + if (is_signed) + value.GetScalar() = (int32_t)(raw_value & UINT32_MAX); + else + value.GetScalar() = (uint32_t)(raw_value & UINT32_MAX); + success = true; + break; + + case sizeof(uint16_t): + if (is_signed) + value.GetScalar() = (int16_t)(raw_value & UINT16_MAX); + else + value.GetScalar() = (uint16_t)(raw_value & UINT16_MAX); + success = true; + break; + + case sizeof(uint8_t): + if (is_signed) + value.GetScalar() = (int8_t)(raw_value & UINT8_MAX); + else + value.GetScalar() = (uint8_t)(raw_value & UINT8_MAX); + success = true; + break; + } + } else if (type_flags & eTypeIsFloat) { + if (type_flags & eTypeIsComplex) { + // Don't handle complex yet. + } else { + llvm::Optional<uint64_t> byte_size = + return_compiler_type.GetByteSize(nullptr); + if (byte_size && *byte_size <= sizeof(long double)) { + const RegisterInfo *xmm0_info = + reg_ctx->GetRegisterInfoByName("xmm0", 0); + RegisterValue xmm0_value; + if (reg_ctx->ReadRegister(xmm0_info, xmm0_value)) { + DataExtractor data; + if (xmm0_value.GetData(data)) { + lldb::offset_t offset = 0; + if (*byte_size == sizeof(float)) { + value.GetScalar() = (float)data.GetFloat(&offset); + success = true; + } else if (*byte_size == sizeof(double)) { + // double and long double are the same on windows + value.GetScalar() = (double)data.GetDouble(&offset); + success = true; + } + } + } + } + } + } + + if (success) + return_valobj_sp = ValueObjectConstResult::Create( + thread.GetStackFrameAtIndex(0).get(), value, ConstString("")); + } else if ((type_flags & eTypeIsPointer) || + (type_flags & eTypeInstanceIsPointer)) { + unsigned rax_id = + reg_ctx->GetRegisterInfoByName("rax", 0)->kinds[eRegisterKindLLDB]; + value.GetScalar() = + (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(rax_id, + 0); + value.SetValueType(Value::eValueTypeScalar); + return_valobj_sp = ValueObjectConstResult::Create( + thread.GetStackFrameAtIndex(0).get(), value, ConstString("")); + } else if (type_flags & eTypeIsVector) { + llvm::Optional<uint64_t> byte_size = + return_compiler_type.GetByteSize(nullptr); + if (byte_size && *byte_size > 0) { + const RegisterInfo *xmm_reg = + reg_ctx->GetRegisterInfoByName("xmm0", 0); + if (xmm_reg == nullptr) + xmm_reg = reg_ctx->GetRegisterInfoByName("mm0", 0); + + if (xmm_reg) { + if (*byte_size <= xmm_reg->byte_size) { + ProcessSP process_sp(thread.GetProcess()); + if (process_sp) { + std::unique_ptr<DataBufferHeap> heap_data_up( + new DataBufferHeap(*byte_size, 0)); + const ByteOrder byte_order = process_sp->GetByteOrder(); + RegisterValue reg_value; + if (reg_ctx->ReadRegister(xmm_reg, reg_value)) { + Status error; + if (reg_value.GetAsMemoryData( + xmm_reg, heap_data_up->GetBytes(), + heap_data_up->GetByteSize(), byte_order, error)) { + DataExtractor data(DataBufferSP(heap_data_up.release()), + byte_order, + process_sp->GetTarget() + .GetArchitecture() + .GetAddressByteSize()); + return_valobj_sp = ValueObjectConstResult::Create( + &thread, return_compiler_type, ConstString(""), data); + } + } + } + } + } + } + } + + return return_valobj_sp; +} + +// The compiler will flatten the nested aggregate type into single +// layer and push the value to stack +// This helper function will flatten an aggregate type +// and return true if it can be returned in register(s) by value +// return false if the aggregate is in memory +static bool FlattenAggregateType( + Thread &thread, ExecutionContext &exe_ctx, + CompilerType &return_compiler_type, + uint32_t data_byte_offset, + std::vector<uint32_t> &aggregate_field_offsets, + std::vector<CompilerType> &aggregate_compiler_types) { + + const uint32_t num_children = return_compiler_type.GetNumFields(); + for (uint32_t idx = 0; idx < num_children; ++idx) { + std::string name; + bool is_signed; + uint32_t count; + bool is_complex; + + uint64_t field_bit_offset = 0; + CompilerType field_compiler_type = return_compiler_type.GetFieldAtIndex( + idx, name, &field_bit_offset, nullptr, nullptr); + llvm::Optional<uint64_t> field_bit_width = + field_compiler_type.GetBitSize(&thread); + + // if we don't know the size of the field (e.g. invalid type), exit + if (!field_bit_width || *field_bit_width == 0) { + return false; + } + // If there are any unaligned fields, this is stored in memory. + if (field_bit_offset % *field_bit_width != 0) { + return false; + } + + // add overall offset + uint32_t field_byte_offset = field_bit_offset / 8 + data_byte_offset; + + const uint32_t field_type_flags = field_compiler_type.GetTypeInfo(); + if (field_compiler_type.IsIntegerOrEnumerationType(is_signed) || + field_compiler_type.IsPointerType() || + field_compiler_type.IsFloatingPointType(count, is_complex)) { + aggregate_field_offsets.push_back(field_byte_offset); + aggregate_compiler_types.push_back(field_compiler_type); + } else if (field_type_flags & eTypeHasChildren) { + if (!FlattenAggregateType(thread, exe_ctx, field_compiler_type, + field_byte_offset, aggregate_field_offsets, + aggregate_compiler_types)) { + return false; + } + } + } + return true; +} + +ValueObjectSP ABIWindows_x86_64::GetReturnValueObjectImpl( + Thread &thread, CompilerType &return_compiler_type) const { + ValueObjectSP return_valobj_sp; + + if (!return_compiler_type) { + return return_valobj_sp; + } + + // try extract value as if it's a simple type + return_valobj_sp = GetReturnValueObjectSimple(thread, return_compiler_type); + if (return_valobj_sp) { + return return_valobj_sp; + } + + RegisterContextSP reg_ctx_sp = thread.GetRegisterContext(); + if (!reg_ctx_sp) { + return return_valobj_sp; + } + + llvm::Optional<uint64_t> bit_width = return_compiler_type.GetBitSize(&thread); + if (!bit_width) { + return return_valobj_sp; + } + + // if it's not simple or aggregate type, then we don't know how to handle it + if (!return_compiler_type.IsAggregateType()) { + return return_valobj_sp; + } + + ExecutionContext exe_ctx(thread.shared_from_this()); + Target *target = exe_ctx.GetTargetPtr(); + uint32_t max_register_value_bit_width = 64; + + // The scenario here is to have a struct/class which is POD + // if the return struct/class size is larger than 64 bits, + // the caller will allocate memory for it and pass the return addr in RCX + // then return the address in RAX + + // if the struct is returned by value in register (RAX) + // its size has to be: 1, 2, 4, 8, 16, 32, or 64 bits (aligned) + // for floating point, the return value will be copied over to RAX + bool is_memory = *bit_width > max_register_value_bit_width || + *bit_width & (*bit_width - 1); + std::vector<uint32_t> aggregate_field_offsets; + std::vector<CompilerType> aggregate_compiler_types; + if (!is_memory && + FlattenAggregateType(thread, exe_ctx, return_compiler_type, + 0, aggregate_field_offsets, + aggregate_compiler_types)) { + ByteOrder byte_order = target->GetArchitecture().GetByteOrder(); + DataBufferSP data_sp( + new DataBufferHeap(max_register_value_bit_width / 8, 0)); + DataExtractor return_ext(data_sp, byte_order, + target->GetArchitecture().GetAddressByteSize()); + + // The only register used to return struct/class by value + const RegisterInfo *rax_info = + reg_ctx_sp->GetRegisterInfoByName("rax", 0); + RegisterValue rax_value; + reg_ctx_sp->ReadRegister(rax_info, rax_value); + DataExtractor rax_data; + rax_value.GetData(rax_data); + + uint32_t used_bytes = + 0; // Tracks how much of the rax registers we've consumed so far + + // in case of the returned type is a subclass of non-abstract-base class + // it will have a padding to skip the base content + if (aggregate_field_offsets.size()) + used_bytes = aggregate_field_offsets[0]; + + const uint32_t num_children = aggregate_compiler_types.size(); + for (uint32_t idx = 0; idx < num_children; idx++) { + bool is_signed; + bool is_complex; + uint32_t count; + + CompilerType field_compiler_type = aggregate_compiler_types[idx]; + uint32_t field_byte_width = (uint32_t) (*field_compiler_type.GetByteSize(&thread)); + uint32_t field_byte_offset = aggregate_field_offsets[idx]; + + // this is unlikely w/o the overall size being greater than 8 bytes + // For now, return a nullptr return value object. + if (used_bytes >= 8 || used_bytes + field_byte_width > 8) { + return return_valobj_sp; + } + + DataExtractor *copy_from_extractor = nullptr; + uint32_t copy_from_offset = 0; + if (field_compiler_type.IsIntegerOrEnumerationType(is_signed) || + field_compiler_type.IsPointerType() || + field_compiler_type.IsFloatingPointType(count, is_complex)) { + copy_from_extractor = &rax_data; + copy_from_offset = used_bytes; + used_bytes += field_byte_width; + } + // These two tests are just sanity checks. If I somehow get the type + // calculation wrong above it is better to just return nothing than to + // assert or crash. + if (!copy_from_extractor) { + return return_valobj_sp; + } + if (copy_from_offset + field_byte_width > + copy_from_extractor->GetByteSize()) { + return return_valobj_sp; + } + copy_from_extractor->CopyByteOrderedData(copy_from_offset, + field_byte_width, data_sp->GetBytes() + field_byte_offset, + field_byte_width, byte_order); + } + if (!is_memory) { + // The result is in our data buffer. Let's make a variable object out + // of it: + return_valobj_sp = ValueObjectConstResult::Create( + &thread, return_compiler_type, ConstString(""), return_ext); + } + } + + // The Windows x86_64 ABI specifies that the return address for MEMORY + // objects be placed in rax on exit from the function. + + // FIXME: This is just taking a guess, rax may very well no longer hold the + // return storage location. + // If we are going to do this right, when we make a new frame we should + // check to see if it uses a memory return, and if we are at the first + // instruction and if so stash away the return location. Then we would + // only return the memory return value if we know it is valid. + if (is_memory) { + unsigned rax_id = + reg_ctx_sp->GetRegisterInfoByName("rax", 0)->kinds[eRegisterKindLLDB]; + lldb::addr_t storage_addr = + (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(rax_id, + 0); + return_valobj_sp = ValueObjectMemory::Create( + &thread, "", Address(storage_addr, nullptr), return_compiler_type); + } + return return_valobj_sp; +} + +// This defines the CFA as rsp+8 +// the saved pc is at CFA-8 (i.e. rsp+0) +// The saved rsp is CFA+0 + +bool ABIWindows_x86_64::CreateFunctionEntryUnwindPlan(UnwindPlan &unwind_plan) { + unwind_plan.Clear(); + unwind_plan.SetRegisterKind(eRegisterKindDWARF); + + uint32_t sp_reg_num = dwarf_rsp; + uint32_t pc_reg_num = dwarf_rip; + + UnwindPlan::RowSP row(new UnwindPlan::Row); + row->GetCFAValue().SetIsRegisterPlusOffset(sp_reg_num, 8); + row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, -8, false); + row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true); + unwind_plan.AppendRow(row); + unwind_plan.SetSourceName("x86_64 at-func-entry default"); + unwind_plan.SetSourcedFromCompiler(eLazyBoolNo); + return true; +} + +// Windows-x86_64 doesn't use %rbp +// No available Unwind information for Windows-x86_64 (section .pdata) +// Let's use SysV-x86_64 one for now +bool ABIWindows_x86_64::CreateDefaultUnwindPlan(UnwindPlan &unwind_plan) { + unwind_plan.Clear(); + unwind_plan.SetRegisterKind(eRegisterKindDWARF); + + uint32_t fp_reg_num = dwarf_rbp; + uint32_t sp_reg_num = dwarf_rsp; + uint32_t pc_reg_num = dwarf_rip; + + UnwindPlan::RowSP row(new UnwindPlan::Row); + + const int32_t ptr_size = 8; + row->GetCFAValue().SetIsRegisterPlusOffset(dwarf_rbp, 2 * ptr_size); + row->SetOffset(0); + + row->SetRegisterLocationToAtCFAPlusOffset(fp_reg_num, ptr_size * -2, true); + row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, ptr_size * -1, true); + row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true); + + unwind_plan.AppendRow(row); + unwind_plan.SetSourceName("x86_64 default unwind plan"); + unwind_plan.SetSourcedFromCompiler(eLazyBoolNo); + unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo); + + return true; +} + +bool ABIWindows_x86_64::RegisterIsVolatile(const RegisterInfo *reg_info) { + return !RegisterIsCalleeSaved(reg_info); +} + +bool ABIWindows_x86_64::RegisterIsCalleeSaved(const RegisterInfo *reg_info) { + if (!reg_info) + return false; + assert(reg_info->name != nullptr && "unnamed register?"); + std::string Name = std::string(reg_info->name); + bool IsCalleeSaved = + llvm::StringSwitch<bool>(Name) + .Cases("rbx", "ebx", "rbp", "ebp", "rdi", "edi", "rsi", "esi", true) + .Cases("rsp", "esp", "r12", "r13", "r14", "r15", "sp", "fp", true) + .Cases("xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", + "xmm13", "xmm14", "xmm15", true) + .Default(false); + return IsCalleeSaved; +} + +void ABIWindows_x86_64::Initialize() { + PluginManager::RegisterPlugin( + GetPluginNameStatic(), "Windows ABI for x86_64 targets", CreateInstance); +} + +void ABIWindows_x86_64::Terminate() { + PluginManager::UnregisterPlugin(CreateInstance); +} + +lldb_private::ConstString ABIWindows_x86_64::GetPluginNameStatic() { + static ConstString g_name("windows-x86_64"); + return g_name; +} + +//------------------------------------------------------------------ +// PluginInterface protocol +//------------------------------------------------------------------ + +lldb_private::ConstString ABIWindows_x86_64::GetPluginName() { + return GetPluginNameStatic(); +} + +uint32_t ABIWindows_x86_64::GetPluginVersion() { return 1; }
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/ABIWindows_x86_64.h b/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/ABIWindows_x86_64.h new file mode 100644 index 0000000..9f6b2ce --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/ABIWindows_x86_64.h
@@ -0,0 +1,99 @@ +//===-- ABIWindows_x86_64.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 liblldb_ABIWindows_x86_64_h_ +#define liblldb_ABIWindows_x86_64_h_ + +#include "lldb/Target/ABI.h" +#include "lldb/lldb-private.h" + +class ABIWindows_x86_64 : public lldb_private::ABI { +public: + ~ABIWindows_x86_64() override = default; + + size_t GetRedZoneSize() const override; + + bool PrepareTrivialCall(lldb_private::Thread &thread, lldb::addr_t sp, + lldb::addr_t functionAddress, + lldb::addr_t returnAddress, + llvm::ArrayRef<lldb::addr_t> args) const override; + + bool GetArgumentValues(lldb_private::Thread &thread, + lldb_private::ValueList &values) const override; + + lldb_private::Status + SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value) override; + + lldb::ValueObjectSP + GetReturnValueObjectImpl(lldb_private::Thread &thread, + lldb_private::CompilerType &type) const override; + + bool + CreateFunctionEntryUnwindPlan(lldb_private::UnwindPlan &unwind_plan) override; + + bool CreateDefaultUnwindPlan(lldb_private::UnwindPlan &unwind_plan) override; + + bool RegisterIsVolatile(const lldb_private::RegisterInfo *reg_info) override; + + // In Windows_x86_64 ABI, stack will always be maintained 16-byte aligned + bool CallFrameAddressIsValid(lldb::addr_t cfa) override { + if (cfa & (16ull - 1ull)) + return false; // Not 16 byte aligned + if (cfa == 0) + return false; // Zero is not a valid stack address + return true; + } + + bool CodeAddressIsValid(lldb::addr_t pc) override { + // We have a 64 bit address space, so anything is valid as opcodes + // aren't fixed width... + return true; + } + + const lldb_private::RegisterInfo * + GetRegisterInfoArray(uint32_t &count) override; + + bool GetPointerReturnRegister(const char *&name) override; + + //------------------------------------------------------------------ + // Static Functions + //------------------------------------------------------------------ + + static void Initialize(); + + static void Terminate(); + + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); + + static lldb_private::ConstString GetPluginNameStatic(); + + //------------------------------------------------------------------ + // PluginInterface protocol + //------------------------------------------------------------------ + + lldb_private::ConstString GetPluginName() override; + + uint32_t GetPluginVersion() override; + +protected: + void CreateRegisterMapIfNeeded(); + + lldb::ValueObjectSP + GetReturnValueObjectSimple(lldb_private::Thread &thread, + lldb_private::CompilerType &ast_type) const; + + bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); + +private: + ABIWindows_x86_64(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { + // Call CreateInstance instead. + } +}; + +#endif // liblldb_ABISysV_x86_64_h_
diff --git a/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/CMakeLists.txt new file mode 100644 index 0000000..dab8736 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ABI/Windows-x86_64/CMakeLists.txt
@@ -0,0 +1,10 @@ +add_lldb_library(lldbPluginABIWindows_x86_64 PLUGIN + ABIWindows_x86_64.cpp + + LINK_LIBS + lldbCore + lldbSymbol + lldbTarget + LINK_COMPONENTS + Support + )
diff --git a/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.cpp b/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.cpp index 6993222..5b86df6 100644 --- a/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.cpp
@@ -1,9 +1,8 @@ //===-- ArchitectureArm.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.h b/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.h index 1a052c7..03e79ce 100644 --- a/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.h +++ b/src/llvm-project/lldb/source/Plugins/Architecture/Arm/ArchitectureArm.h
@@ -1,9 +1,8 @@ //===-- ArchitectureArm.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.cpp b/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.cpp index 0cbbd99..60f1a2e 100644 --- a/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.cpp +++ b/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.cpp
@@ -1,9 +1,8 @@ //===-- ArchitectureMips.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.h b/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.h index 2338daf..a15991f 100644 --- a/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.h +++ b/src/llvm-project/lldb/source/Plugins/Architecture/Mips/ArchitectureMips.h
@@ -1,9 +1,8 @@ //===-- ArchitectureMips.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.cpp b/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.cpp index 619de09..76eaa44 100644 --- a/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.cpp
@@ -1,9 +1,8 @@ //===-- ArchitecturePPC64.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,11 +35,10 @@ } std::unique_ptr<Architecture> ArchitecturePPC64::Create(const ArchSpec &arch) { - if ((arch.GetMachine() != llvm::Triple::ppc64 && - arch.GetMachine() != llvm::Triple::ppc64le) || - arch.GetTriple().getObjectFormat() != llvm::Triple::ObjectFormatType::ELF) - return nullptr; - return std::unique_ptr<Architecture>(new ArchitecturePPC64()); + if (arch.GetTriple().isPPC64() && + arch.GetTriple().getObjectFormat() == llvm::Triple::ObjectFormatType::ELF) + return std::unique_ptr<Architecture>(new ArchitecturePPC64()); + return nullptr; } ConstString ArchitecturePPC64::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.h b/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.h index 9563885..dc663b8 100644 --- a/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.h +++ b/src/llvm-project/lldb/source/Plugins/Architecture/PPC64/ArchitecturePPC64.h
@@ -1,9 +1,8 @@ //===-- ArchitecturePPC64.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,10 +24,8 @@ void OverrideStopInfo(Thread &thread) const override {} - //------------------------------------------------------------------ /// This method compares current address with current function's /// local entry point, returning the bytes to skip if they match. - //------------------------------------------------------------------ size_t GetBytesToSkip(Symbol &func, const Address &curr_addr) const override; void AdjustBreakpointAddress(const Symbol &func,
diff --git a/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp b/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp index 5df8422..44c75fc9 100644 --- a/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp +++ b/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp
@@ -1,9 +1,8 @@ //===-- DisassemblerLLVMC.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -357,7 +356,7 @@ return; else { const uint8_t *bytes = data.PeekData(offset, inst_size); - if (bytes == NULL) + if (bytes == nullptr) return; m_opcode_name.assign(".byte"); m_opcode.SetOpcodeBytes(bytes, inst_size); @@ -957,7 +956,7 @@ return Instance(); std::unique_ptr<llvm::MCContext> context_up( - new llvm::MCContext(asm_info_up.get(), reg_info_up.get(), 0)); + new llvm::MCContext(asm_info_up.get(), reg_info_up.get(), nullptr)); if (!context_up) return Instance(); @@ -1080,7 +1079,7 @@ DisassemblerLLVMC::DisassemblerLLVMC(const ArchSpec &arch, const char *flavor_string) - : Disassembler(arch, flavor_string), m_exe_ctx(NULL), m_inst(NULL), + : Disassembler(arch, flavor_string), m_exe_ctx(nullptr), m_inst(nullptr), m_data_from_file(false) { if (!FlavorValidForArchSpec(arch, m_flavor.c_str())) { m_flavor.assign("default"); @@ -1179,10 +1178,7 @@ break; } - if (triple.getArch() == llvm::Triple::mips || - triple.getArch() == llvm::Triple::mipsel || - triple.getArch() == llvm::Triple::mips64 || - triple.getArch() == llvm::Triple::mips64el) { + if (arch.IsMIPS()) { uint32_t arch_flags = arch.GetFlags(); if (arch_flags & ArchSpec::eMIPSAse_msa) features_str += "+msa,"; @@ -1192,12 +1188,17 @@ features_str += "+dspr2,"; } - // If any AArch64 variant, enable the ARMv8.2 ISA extensions so we can - // disassemble newer instructions. + // If any AArch64 variant, enable the ARMv8.5 ISA with SVE extensions so we + // can disassemble newer instructions. if (triple.getArch() == llvm::Triple::aarch64) - features_str += "+v8.2a"; + features_str += "+v8.5a,+sve2"; - // We use m_disasm_ap.get() to tell whether we are valid or not, so if this + if (triple.getArch() == llvm::Triple::aarch64 + && triple.getVendor() == llvm::Triple::Apple) { + cpu = "apple-latest"; + } + + // We use m_disasm_up.get() to tell whether we are valid or not, so if this // isn't good for some reason, we won't be valid and FindPlugin will fail and // we won't get used. m_disasm_up = MCDisasmInstance::Create(triple_str, cpu, features_str.c_str(), @@ -1215,10 +1216,7 @@ if (!m_alternate_disasm_up) m_disasm_up.reset(); - } else if (llvm_arch == llvm::Triple::mips || - llvm_arch == llvm::Triple::mipsel || - llvm_arch == llvm::Triple::mips64 || - llvm_arch == llvm::Triple::mips64el) { + } else if (arch.IsMIPS()) { /* Create alternate disassembler for MIPS16 and microMIPS */ uint32_t arch_flags = arch.GetFlags(); if (arch_flags & ArchSpec::eMIPSAse_mips16) @@ -1238,13 +1236,13 @@ Disassembler *DisassemblerLLVMC::CreateInstance(const ArchSpec &arch, const char *flavor) { if (arch.GetTriple().getArch() != llvm::Triple::UnknownArch) { - std::unique_ptr<DisassemblerLLVMC> disasm_ap( + std::unique_ptr<DisassemblerLLVMC> disasm_up( new DisassemblerLLVMC(arch, flavor)); - if (disasm_ap.get() && disasm_ap->IsValid()) - return disasm_ap.release(); + if (disasm_up.get() && disasm_up->IsValid()) + return disasm_up.release(); } - return NULL; + return nullptr; } size_t DisassemblerLLVMC::DecodeInstructions(const Address &base_addr, @@ -1331,7 +1329,7 @@ bool DisassemblerLLVMC::FlavorValidForArchSpec( const lldb_private::ArchSpec &arch, const char *flavor) { llvm::Triple triple = arch.GetTriple(); - if (flavor == NULL || strcmp(flavor, "default") == 0) + if (flavor == nullptr || strcmp(flavor, "default") == 0) return true; if (triple.getArch() == llvm::Triple::x86 || @@ -1360,7 +1358,7 @@ if (*type_ptr) { if (m_exe_ctx && m_inst) { // std::string remove_this_prior_to_checkin; - Target *target = m_exe_ctx ? m_exe_ctx->GetTargetPtr() : NULL; + Target *target = m_exe_ctx ? m_exe_ctx->GetTargetPtr() : nullptr; Address value_so_addr; Address pc_so_addr; if (m_inst->UsingFileAddress()) { @@ -1425,13 +1423,11 @@ } *type_ptr = LLVMDisassembler_ReferenceType_InOut_None; - *name = NULL; - return NULL; + *name = nullptr; + return nullptr; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString DisassemblerLLVMC::GetPluginName() { return GetPluginNameStatic(); } uint32_t DisassemblerLLVMC::GetPluginVersion() { return 1; }
diff --git a/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.h b/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.h index 8b9f7c3..fd57750 100644 --- a/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.h +++ b/src/llvm-project/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.h
@@ -1,9 +1,8 @@ //===-- DisassemblerLLVMC.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -27,9 +26,7 @@ ~DisassemblerLLVMC() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -44,9 +41,7 @@ lldb::offset_t data_offset, size_t num_instructions, bool append, bool data_from_file) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp index 3a80c68..242085a 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp
@@ -1,10 +1,9 @@ //===-- DynamicLoaderDarwinKernel.cpp -----------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,8 +15,8 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Host/Symbols.h" #include "lldb/Interpreter/OptionValueProperties.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/OperatingSystem.h" #include "lldb/Target/RegisterContext.h" @@ -32,6 +31,9 @@ #include "DynamicLoaderDarwinKernel.h" +#include <memory> +#include <algorithm> + //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN #ifdef ENABLE_DEBUG_PRINTF #include <stdio.h> @@ -71,9 +73,9 @@ "on 32-bit targets)."}}; static constexpr PropertyDefinition g_properties[] = { - {"load-kexts", OptionValue::eTypeBoolean, true, true, NULL, {}, + {"load-kexts", OptionValue::eTypeBoolean, true, true, nullptr, {}, "Automatically loads kext images when attaching to a kernel."}, - {"scan-type", OptionValue::eTypeEnum, true, eKASLRScanNearPC, NULL, + {"scan-type", OptionValue::eTypeEnum, true, eKASLRScanNearPC, nullptr, OptionEnumValues(g_kaslr_kernel_scan_enum_values), "Control how many reads lldb will make while searching for a Darwin " "kernel on attach."}}; @@ -88,22 +90,22 @@ } DynamicLoaderDarwinKernelProperties() : Properties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); } - virtual ~DynamicLoaderDarwinKernelProperties() {} + ~DynamicLoaderDarwinKernelProperties() override {} bool GetLoadKexts() const { const uint32_t idx = ePropertyLoadKexts; return m_collection_sp->GetPropertyAtIndexAsBoolean( - NULL, idx, g_properties[idx].default_uint_value != 0); + nullptr, idx, g_properties[idx].default_uint_value != 0); } KASLRScanType GetScanType() const { const uint32_t idx = ePropertyScanType; return (KASLRScanType)m_collection_sp->GetPropertyAtIndexAsEnumeration( - NULL, idx, g_properties[idx].default_uint_value); + nullptr, idx, g_properties[idx].default_uint_value); } }; @@ -113,15 +115,13 @@ static const DynamicLoaderDarwinKernelPropertiesSP &GetGlobalProperties() { static DynamicLoaderDarwinKernelPropertiesSP g_settings_sp; if (!g_settings_sp) - g_settings_sp.reset(new DynamicLoaderDarwinKernelProperties()); + g_settings_sp = std::make_shared<DynamicLoaderDarwinKernelProperties>(); return g_settings_sp; } -//---------------------------------------------------------------------- // Create an instance of this class. This function is filled into the plugin // info class that gets handed out by the plugin factory and allows the lldb to // instantiate an instance of this class. -//---------------------------------------------------------------------- DynamicLoader *DynamicLoaderDarwinKernel::CreateInstance(Process *process, bool force) { if (!force) { @@ -132,7 +132,7 @@ ObjectFile *object_file = exe_module->GetObjectFile(); if (object_file) { if (object_file->GetStrata() != ObjectFile::eStrataKernel) { - return NULL; + return nullptr; } } } @@ -149,7 +149,7 @@ case llvm::Triple::WatchOS: // NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS: if (triple_ref.getVendor() != llvm::Triple::Apple) { - return NULL; + return nullptr; } break; // If we have triple like armv7-unknown-unknown, we should try looking for @@ -157,7 +157,7 @@ case llvm::Triple::UnknownOS: break; default: - return NULL; + return nullptr; break; } } @@ -171,7 +171,7 @@ process->SetCanRunCode(false); return new DynamicLoaderDarwinKernel(process, kernel_load_address); } - return NULL; + return nullptr; } lldb::addr_t @@ -192,19 +192,17 @@ return kernel_load_address; } -//---------------------------------------------------------------------- // Check if the kernel binary is loaded in memory without a slide. First verify // that the ExecutableModule is a kernel before we proceed. Returns the address // of the kernel if one was found, else LLDB_INVALID_ADDRESS. -//---------------------------------------------------------------------- lldb::addr_t DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr(Process *process) { Module *exe_module = process->GetTarget().GetExecutableModulePointer(); - if (exe_module == NULL) + if (exe_module == nullptr) return LLDB_INVALID_ADDRESS; ObjectFile *exe_objfile = exe_module->GetObjectFile(); - if (exe_objfile == NULL) + if (exe_objfile == nullptr) return LLDB_INVALID_ADDRESS; if (exe_objfile->GetType() != ObjectFile::eTypeExecutable || @@ -222,11 +220,9 @@ return LLDB_INVALID_ADDRESS; } -//---------------------------------------------------------------------- // If the debug flag is included in the boot-args nvram setting, the kernel's // load address will be noted in the lowglo page at a fixed address Returns the // address of the kernel if one was found, else LLDB_INVALID_ADDRESS. -//---------------------------------------------------------------------- lldb::addr_t DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints(Process *process) { if (GetGlobalProperties()->GetScanType() == eKASLRScanNone) @@ -239,8 +235,7 @@ 0xffffff8000002010ULL, // oldest arm64 devices LLDB_INVALID_ADDRESS}; addr_t kernel_addresses_32[] = {0xffff0110, // 2016 and earlier armv7 devices - 0xffff1010, - LLDB_INVALID_ADDRESS}; + 0xffff1010, LLDB_INVALID_ADDRESS}; uint8_t uval[8]; if (process->GetAddressByteSize() == 8) { @@ -274,13 +269,11 @@ return LLDB_INVALID_ADDRESS; } -//---------------------------------------------------------------------- // If the kernel is currently executing when lldb attaches, and we don't have a // better way of finding the kernel's load address, try searching backwards // from the current pc value looking for the kernel's Mach header in memory. // Returns the address of the kernel if one was found, else // LLDB_INVALID_ADDRESS. -//---------------------------------------------------------------------- lldb::addr_t DynamicLoaderDarwinKernel::SearchForKernelNearPC(Process *process) { if (GetGlobalProperties()->GetScanType() == eKASLRScanNone || @@ -289,13 +282,15 @@ } ThreadSP thread = process->GetThreadList().GetSelectedThread(); - if (thread.get() == NULL) + if (thread.get() == nullptr) return LLDB_INVALID_ADDRESS; addr_t pc = thread->GetRegisterContext()->GetPC(LLDB_INVALID_ADDRESS); + int ptrsize = process->GetTarget().GetArchitecture().GetAddressByteSize(); + // The kernel is always loaded in high memory, if the top bit is zero, // this isn't a kernel. - if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8) { + if (ptrsize == 8) { if ((pc & (1ULL << 63)) == 0) { return LLDB_INVALID_ADDRESS; } @@ -308,37 +303,35 @@ if (pc == LLDB_INVALID_ADDRESS) return LLDB_INVALID_ADDRESS; - // The kernel will load at at one megabyte boundary (0x100000), or at that - // boundary plus an offset of one page (0x1000) or two, or four (0x4000), - // depending on the device. + int pagesize = 0x4000; // 16k pages on 64-bit targets + if (ptrsize == 4) + pagesize = 0x1000; // 4k pages on 32-bit targets - // Round the current pc down to the nearest one megabyte boundary - the place - // where we will start searching. - addr_t addr = pc & ~0xfffff; + // The kernel will be loaded on a page boundary. + // Round the current pc down to the nearest page boundary. + addr_t addr = pc & ~(pagesize - 1ULL); - // Search backwards 32 megabytes, looking for the start of the kernel at each - // one-megabyte boundary. - for (int i = 0; i < 32; i++, addr -= 0x100000) { - // x86_64 kernels are at offset 0 - if (CheckForKernelImageAtAddress(addr, process).IsValid()) + // Search backwards for 32 megabytes, or first memory read error. + while (pc - addr < 32 * 0x100000) { + bool read_error; + if (CheckForKernelImageAtAddress(addr, process, &read_error).IsValid()) return addr; - // 32-bit arm kernels are at offset 0x1000 (one 4k page) - if (CheckForKernelImageAtAddress(addr + 0x1000, process).IsValid()) - return addr + 0x1000; - // 64-bit arm kernels are at offset 0x4000 (one 16k page) - if (CheckForKernelImageAtAddress(addr + 0x4000, process).IsValid()) - return addr + 0x4000; + + // Stop scanning on the first read error we encounter; we've walked + // past this executable block of memory. + if (read_error == true) + break; + + addr -= pagesize; } return LLDB_INVALID_ADDRESS; } -//---------------------------------------------------------------------- // Scan through the valid address range for a kernel binary. This is uselessly // slow in 64-bit environments so we don't even try it. This scan is not // enabled by default even for 32-bit targets. Returns the address of the // kernel if one was found, else LLDB_INVALID_ADDRESS. -//---------------------------------------------------------------------- lldb::addr_t DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch( Process *process) { if (GetGlobalProperties()->GetScanType() != eKASLRScanExhaustiveScan) { @@ -378,21 +371,25 @@ return LLDB_INVALID_ADDRESS; } -//---------------------------------------------------------------------- // Read the mach_header struct out of memory and return it. // Returns true if the mach_header was successfully read, // Returns false if there was a problem reading the header, or it was not // a Mach-O header. -//---------------------------------------------------------------------- bool -DynamicLoaderDarwinKernel::ReadMachHeader(addr_t addr, Process *process, llvm::MachO::mach_header &header) { - Status read_error; +DynamicLoaderDarwinKernel::ReadMachHeader(addr_t addr, Process *process, llvm::MachO::mach_header &header, + bool *read_error) { + Status error; + if (read_error) + *read_error = false; // Read the mach header and see whether it looks like a kernel - if (process->DoReadMemory (addr, &header, sizeof(header), read_error) != - sizeof(header)) + if (process->DoReadMemory (addr, &header, sizeof(header), error) != + sizeof(header)) { + if (read_error) + *read_error = true; return false; + } const uint32_t magicks[] = { llvm::MachO::MH_MAGIC_64, llvm::MachO::MH_MAGIC, llvm::MachO::MH_CIGAM, llvm::MachO::MH_CIGAM_64}; @@ -418,18 +415,20 @@ return true; } -//---------------------------------------------------------------------- // Given an address in memory, look to see if there is a kernel image at that // address. // Returns a UUID; if a kernel was not found at that address, UUID.IsValid() // will be false. -//---------------------------------------------------------------------- lldb_private::UUID DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress(lldb::addr_t addr, - Process *process) { + Process *process, + bool *read_error) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); - if (addr == LLDB_INVALID_ADDRESS) + if (addr == LLDB_INVALID_ADDRESS) { + if (read_error) + *read_error = true; return UUID(); + } if (log) log->Printf("DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress: " @@ -438,7 +437,7 @@ llvm::MachO::mach_header header; - if (!ReadMachHeader(addr, process, header)) + if (!ReadMachHeader(addr, process, header, read_error)) return UUID(); // First try a quick test -- read the first 4 bytes and see if there is a @@ -455,7 +454,7 @@ return UUID(); ObjectFile *exe_objfile = memory_module_sp->GetObjectFile(); - if (exe_objfile == NULL) { + if (exe_objfile == nullptr) { if (log) log->Printf("DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress " "found a binary at 0x%" PRIx64 @@ -491,9 +490,7 @@ return UUID(); } -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel(Process *process, lldb::addr_t kernel_addr) : DynamicLoader(process), m_kernel_load_address(kernel_addr), m_kernel(), @@ -511,40 +508,32 @@ } } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel() { Clear(true); } void DynamicLoaderDarwinKernel::UpdateIfNeeded() { LoadKernelModuleIfNeeded(); SetNotificationBreakpointIfNeeded(); } -//------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. -//------------------------------------------------------------------ void DynamicLoaderDarwinKernel::DidAttach() { PrivateInitialize(m_process); UpdateIfNeeded(); } -//------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. -//------------------------------------------------------------------ void DynamicLoaderDarwinKernel::DidLaunch() { PrivateInitialize(m_process); UpdateIfNeeded(); } -//---------------------------------------------------------------------- // Clear out the state of this class. -//---------------------------------------------------------------------- void DynamicLoaderDarwinKernel::Clear(bool clear_process) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -552,7 +541,7 @@ m_process->ClearBreakpointSiteByID(m_break_id); if (clear_process) - m_process = NULL; + m_process = nullptr; m_kernel.Clear(); m_known_kexts.clear(); m_kext_summary_header_ptr_addr.Clear(); @@ -649,7 +638,7 @@ bool DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule( Process *process) { Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); - if (m_memory_module_sp.get() != NULL) + if (m_memory_module_sp.get() != nullptr) return true; if (m_load_address == LLDB_INVALID_ADDRESS) return false; @@ -669,7 +658,7 @@ ModuleSP memory_module_sp = process->ReadModuleFromMemory(file_spec, m_load_address, size_to_read); - if (memory_module_sp.get() == NULL) + if (memory_module_sp.get() == nullptr) return false; bool is_kernel = false; @@ -753,24 +742,24 @@ Target &target = process->GetTarget(); - // If we don't have / can't create a memory module for this kext, don't try - // to load it - we won't have the correct segment load addresses. - if (!ReadMemoryModule(process)) { - Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); - if (log) - log->Printf("Unable to read '%s' from memory at address 0x%" PRIx64 - " to get the segment load addresses.", - m_name.c_str(), m_load_address); - return false; + // kexts will have a uuid from the table. + // for the kernel, we'll need to read the load commands out of memory to get it. + if (m_uuid.IsValid() == false) { + if (ReadMemoryModule(process) == false) { + Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); + if (log) + log->Printf("Unable to read '%s' from memory at address 0x%" PRIx64 + " to get the segment load addresses.", + m_name.c_str(), m_load_address); + return false; + } } - bool uuid_is_valid = m_uuid.IsValid(); - - if (IsKernel() && uuid_is_valid && m_memory_module_sp.get()) { + if (IsKernel() && m_uuid.IsValid()) { Stream *s = target.GetDebugger().GetOutputFile().get(); if (s) { s->Printf("Kernel UUID: %s\n", - m_memory_module_sp->GetUUID().GetAsString().c_str()); + m_uuid.GetAsString().c_str()); s->Printf("Load Address: 0x%" PRIx64 "\n", m_load_address); } } @@ -782,7 +771,7 @@ m_module_sp = target_images.FindModule(m_uuid); // Search for the kext on the local filesystem via the UUID - if (!m_module_sp && uuid_is_valid) { + if (!m_module_sp && m_uuid.IsValid()) { ModuleSpec module_spec; module_spec.GetUUID() = m_uuid; module_spec.GetArchitecture() = target.GetArchitecture(); @@ -792,8 +781,8 @@ if (IsKernel()) { if (Symbols::DownloadObjectAndSymbolFile(module_spec, true)) { if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) { - m_module_sp.reset(new Module(module_spec.GetFileSpec(), - target.GetArchitecture())); + m_module_sp = std::make_shared<Module>(module_spec.GetFileSpec(), + target.GetArchitecture()); if (m_module_sp.get() && m_module_sp->MatchesModuleSpec(module_spec)) { ModuleList loaded_module_list; @@ -815,10 +804,11 @@ if (platform_name == g_platform_name) { ModuleSpec kext_bundle_module_spec(module_spec); FileSpec kext_filespec(m_name.c_str()); + FileSpecList search_paths = target.GetExecutableSearchPaths(); kext_bundle_module_spec.GetFileSpec() = kext_filespec; - platform_sp->GetSharedModule( - kext_bundle_module_spec, process, m_module_sp, - &target.GetExecutableSearchPaths(), NULL, NULL); + platform_sp->GetSharedModule(kext_bundle_module_spec, process, + m_module_sp, &search_paths, nullptr, + nullptr); } } @@ -828,7 +818,7 @@ // the DebugSymbols framework with the UUID to find the binary via its // search methods. if (!m_module_sp) { - m_module_sp = target.GetSharedModule(module_spec); + m_module_sp = target.GetOrCreateModule(module_spec, true /* notify */); } if (IsKernel() && !m_module_sp) { @@ -844,13 +834,7 @@ // images. If we also have a memory module, require that they have matching // UUIDs if (m_module_sp) { - bool uuid_match_ok = true; - if (m_memory_module_sp) { - if (m_module_sp->GetUUID() != m_memory_module_sp->GetUUID()) { - uuid_match_ok = false; - } - } - if (uuid_match_ok) { + if (m_uuid.IsValid() && m_module_sp->GetUUID() == m_uuid) { target.GetImages().AppendIfNeeded(m_module_sp); if (IsKernel() && target.GetExecutableModulePointer() != m_module_sp.get()) { @@ -860,13 +844,10 @@ } } - if (!m_module_sp && !IsKernel() && m_uuid.IsValid() && !m_name.empty()) { - Stream *s = target.GetDebugger().GetOutputFile().get(); - if (s) { - s->Printf("warning: Can't find binary/dSYM for %s (%s)\n", m_name.c_str(), - m_uuid.GetAsString().c_str()); - } - } + // If we've found a binary, read the load commands out of memory so we + // can set the segment load addresses. + if (m_module_sp) + ReadMemoryModule (process); static ConstString g_section_name_LINKEDIT("__LINKEDIT"); @@ -981,11 +962,9 @@ return lldb_private::ArchSpec(); } -//---------------------------------------------------------------------- // Load the kernel module and initialize the "m_kernel" member. Return true // _only_ if the kernel is loaded the first time through (subsequent calls to // this function should return false after the kernel has been already loaded). -//---------------------------------------------------------------------- void DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() { if (!m_kext_summary_header_ptr_addr.IsValid()) { m_kernel.Clear(); @@ -1037,7 +1016,7 @@ m_kernel.LoadImageAtFileAddress(m_process); } } - + // The operating system plugin gets loaded and initialized in // LoadImageUsingMemoryModule when we discover the kernel dSYM. For a core // file in particular, that's the wrong place to do this, since we haven't @@ -1060,12 +1039,10 @@ } } -//---------------------------------------------------------------------- // Static callback function that gets called when our DYLD notification // breakpoint gets hit. We update all of our image infos and then let our super // class DynamicLoader class decide if we should stop or not (based on global // preference). -//---------------------------------------------------------------------- bool DynamicLoaderDarwinKernel::BreakpointHitCallback( void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { @@ -1239,9 +1216,9 @@ // If this "kext" entry is actually an alias for the kernel -- the kext was // compiled into the kernel or something -- then we don't want to load the // kernel's text section at a different address. Ignore this kext entry. - if (kext_summaries[new_kext].GetUUID().IsValid() - && m_kernel.GetUUID().IsValid() - && kext_summaries[new_kext].GetUUID() == m_kernel.GetUUID()) { + if (kext_summaries[new_kext].GetUUID().IsValid() && + m_kernel.GetUUID().IsValid() && + kext_summaries[new_kext].GetUUID() == m_kernel.GetUUID()) { to_be_added[new_kext] = false; break; } @@ -1283,6 +1260,8 @@ } } + // Build up a list of <kext-name, uuid> for any kexts that fail to load + std::vector<std::pair<std::string, UUID>> kexts_failed_to_load; if (number_of_new_kexts_being_added > 0) { ModuleList loaded_module_list; @@ -1290,9 +1269,14 @@ for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++) { if (to_be_added[new_kext]) { KextImageInfo &image_info = kext_summaries[new_kext]; + bool kext_successfully_added = true; if (load_kexts) { if (!image_info.LoadImageUsingMemoryModule(m_process)) { + kexts_failed_to_load.push_back(std::pair<std::string, UUID>( + kext_summaries[new_kext].GetName(), + kext_summaries[new_kext].GetUUID())); image_info.LoadImageAtFileAddress(m_process); + kext_successfully_added = false; } } @@ -1302,8 +1286,12 @@ m_process->GetStopID() == image_info.GetProcessStopId()) loaded_module_list.AppendIfNeeded(image_info.GetModule()); - if (s && load_kexts) - s->Printf("."); + if (s && load_kexts) { + if (kext_successfully_added) + s->Printf("."); + else + s->Printf("-"); + } if (log) kext_summaries[new_kext].PutToLog(log); @@ -1338,6 +1326,24 @@ if (s && load_kexts) { s->Printf(" done.\n"); + if (kexts_failed_to_load.size() > 0 && number_of_new_kexts_being_added > 0) { + s->Printf("Failed to load %d of %d kexts:\n", + (int)kexts_failed_to_load.size(), + number_of_new_kexts_being_added); + // print a sorted list of <kext-name, uuid> kexts which failed to load + unsigned longest_name = 0; + std::sort(kexts_failed_to_load.begin(), kexts_failed_to_load.end()); + for (const auto &ku : kexts_failed_to_load) { + if (ku.first.size() > longest_name) + longest_name = ku.first.size(); + } + for (const auto &ku : kexts_failed_to_load) { + std::string uuid; + if (ku.second.IsValid()) + uuid = ku.second.GetAsString(); + s->Printf (" %-*s %s\n", longest_name, ku.first.c_str(), uuid.c_str()); + } + } s->Flush(); } @@ -1372,7 +1378,7 @@ lldb::offset_t offset = kext_summary_offset; const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME); - if (name_data == NULL) + if (name_data == nullptr) break; image_infos[i].SetName((const char *)name_data); UUID uuid = UUID::fromOptionalData(extractor.GetData(&offset, 16), 16); @@ -1406,9 +1412,7 @@ return false; } -//---------------------------------------------------------------------- // Dump an image info structure to the file handle provided. -//---------------------------------------------------------------------- void DynamicLoaderDarwinKernel::KextImageInfo::PutToLog(Log *log) const { if (m_load_address == LLDB_INVALID_ADDRESS) { LLDB_LOG(log, "uuid={0} name=\"{1}\" (UNLOADED)", m_uuid.GetAsString(), @@ -1419,12 +1423,10 @@ } } -//---------------------------------------------------------------------- // Dump the _dyld_all_image_infos members and all current image infos that we // have parsed to the file handle provided. -//---------------------------------------------------------------------- void DynamicLoaderDarwinKernel::PutToLog(Log *log) const { - if (log == NULL) + if (log == nullptr) return; std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -1462,7 +1464,7 @@ module_spec_list.Append(m_kernel.GetModule()->GetFileSpec()); Breakpoint *bp = m_process->GetTarget() - .CreateBreakpoint(&module_spec_list, NULL, + .CreateBreakpoint(&module_spec_list, nullptr, "OSKextLoadedKextSummariesUpdated", eFunctionNameTypeFull, eLanguageTypeUnknown, 0, skip_prologue, internal_bp, hardware) @@ -1474,9 +1476,7 @@ } } -//---------------------------------------------------------------------- // Member function that gets called when the process state changes. -//---------------------------------------------------------------------- void DynamicLoaderDarwinKernel::PrivateProcessStateChanged(Process *process, StateType state) { DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, @@ -1553,9 +1553,7 @@ "in the MacOSX kernel."; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString DynamicLoaderDarwinKernel::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h index 7aacebd..eb31c40 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderDarwinKernel.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,9 +28,7 @@ ~DynamicLoaderDarwinKernel() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -47,12 +44,10 @@ static lldb::addr_t SearchForDarwinKernel(lldb_private::Process *process); - //------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. - //------------------------------------------------------------------ void DidAttach() override; void DidLaunch() override; @@ -62,9 +57,7 @@ lldb_private::Status CanLoadImage() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -247,7 +240,7 @@ image_infos_addr = LLDB_INVALID_ADDRESS; } - bool IsValid() const { return version >= 1 || version <= 2; } + bool IsValid() const { return version >= 1 && version <= 2; } }; void RegisterNotificationCallbacks(); @@ -284,11 +277,13 @@ SearchForKernelViaExhaustiveSearch(lldb_private::Process *process); static bool - ReadMachHeader(lldb::addr_t addr, lldb_private::Process *process, llvm::MachO::mach_header &mh); + ReadMachHeader(lldb::addr_t addr, lldb_private::Process *process, llvm::MachO::mach_header &mh, + bool *read_error = nullptr); static lldb_private::UUID CheckForKernelImageAtAddress(lldb::addr_t addr, - lldb_private::Process *process); + lldb_private::Process *process, + bool *read_error = nullptr); lldb::addr_t m_kernel_load_address; KextImageInfo m_kernel; // Info about the current kernel image being used
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp index 81eab8f..23c8416 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp
@@ -1,9 +1,8 @@ //===-- DynamicLoaderHexagonDYLD.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,6 +20,8 @@ #include "DynamicLoaderHexagonDYLD.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -58,7 +59,7 @@ for (size_t i = 0; i < symtab->GetNumSymbols(); i++) { const Symbol *sym = symtab->SymbolAtIndex(i); assert(sym != nullptr); - const ConstString &symName = sym->GetName(); + ConstString symName = sym->GetName(); if (ConstString::Compare(findName, symName) == 0) { Address addr = sym->GetAddress(); @@ -103,7 +104,7 @@ if (create) return new DynamicLoaderHexagonDYLD(process); - return NULL; + return nullptr; } DynamicLoaderHexagonDYLD::DynamicLoaderHexagonDYLD(Process *process) @@ -198,7 +199,7 @@ return executable; // TODO: What case is this code used? - executable = target.GetSharedModule(module_spec); + executable = target.GetOrCreateModule(module_spec, true /* notify */); if (executable.get() != target.GetExecutableModulePointer()) { // Don't load dependent images since we are in dyld where we will know and // find out about all images that are loaded @@ -242,9 +243,9 @@ } } -/// Removes the loaded sections from the target in @p module. +/// Removes the loaded sections from the target in \p module. /// -/// @param module The module to traverse. +/// \param module The module to traverse. void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) { Target &target = m_process->GetTarget(); const SectionList *sections = GetSectionListFromModule(module); @@ -419,7 +420,7 @@ const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol); Symbol *sym = context.symbol; - if (sym == NULL || !sym->IsTrampoline()) + if (sym == nullptr || !sym->IsTrampoline()) return thread_plan_sp; const ConstString sym_name = sym->GetMangled().GetName( @@ -455,7 +456,8 @@ llvm::sort(start, end); addrs.erase(std::unique(start, end), end); - thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop)); + thread_plan_sp = + std::make_shared<ThreadPlanRunToAddress>(thread, addrs, stop); } return thread_plan_sp;
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h index d39f14e..c171513 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderHexagonDYLD.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,9 +31,7 @@ static lldb_private::DynamicLoader * CreateInstance(lldb_private::Process *process, bool force); - //------------------------------------------------------------------ // DynamicLoader protocol - //------------------------------------------------------------------ void DidAttach() override; @@ -49,9 +46,7 @@ const lldb::ThreadSP thread, lldb::addr_t tls_file_addr) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -87,21 +82,21 @@ /// of loaded modules. void RefreshModules(); - /// Updates the load address of every allocatable section in @p module. + /// Updates the load address of every allocatable section in \p module. /// - /// @param module The module to traverse. + /// \param module The module to traverse. /// - /// @param link_map_addr The virtual address of the link map for the @p + /// \param link_map_addr The virtual address of the link map for the @p /// module. /// - /// @param base_addr The virtual base address @p module is loaded at. + /// \param base_addr The virtual base address \p module is loaded at. void UpdateLoadedSections(lldb::ModuleSP module, lldb::addr_t link_map_addr, lldb::addr_t base_addr, bool base_addr_is_offset) override; - /// Removes the loaded sections from the target in @p module. + /// Removes the loaded sections from the target in \p module. /// - /// @param module The module to traverse. + /// \param module The module to traverse. void UnloadSections(const lldb::ModuleSP module) override; /// Callback routine invoked when we hit the breakpoint on process entry.
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp index d5f60e0..844a06c 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp
@@ -1,9 +1,8 @@ //===-- HexagonDYLDRendezvous.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.h index 758f358..70fc12b 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.h
@@ -1,9 +1,8 @@ //===-- HexagonDYLDRendezvous.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,7 +21,7 @@ class Process; } -/// @class HexagonDYLDRendezvous +/// \class HexagonDYLDRendezvous /// Interface to the runtime linker. /// /// A structure is present in a processes memory space which is updated by the @@ -66,36 +65,36 @@ /// This method should be called once one start up, then once each time the /// runtime linker enters the function given by GetBreakAddress(). /// - /// @returns true on success and false on failure. + /// \returns true on success and false on failure. /// - /// @see GetBreakAddress(). + /// \see GetBreakAddress(). bool Resolve(); - /// @returns true if this rendezvous has been located in the inferiors + /// \returns true if this rendezvous has been located in the inferiors /// address space and false otherwise. bool IsValid(); - /// @returns the address of the rendezvous structure in the inferiors + /// \returns the address of the rendezvous structure in the inferiors /// address space. lldb::addr_t GetRendezvousAddress() const { return m_rendezvous_addr; } /// Provide the dyld structure address void SetRendezvousAddress(lldb::addr_t); - /// @returns the version of the rendezvous protocol being used. + /// \returns the version of the rendezvous protocol being used. uint64_t GetVersion() const { return m_current.version; } - /// @returns address in the inferiors address space containing the linked + /// \returns address in the inferiors address space containing the linked /// list of shared object descriptors. lldb::addr_t GetLinkMapAddress() const { return m_current.map_addr; } /// A breakpoint should be set at this address and Resolve called on each /// hit. /// - /// @returns the address of a function called by the runtime linker each + /// \returns the address of a function called by the runtime linker each /// time a module is loaded/unloaded, or about to be loaded/unloaded. /// - /// @see Resolve() + /// \see Resolve() lldb::addr_t GetBreakAddress() const { return m_current.brk; } /// In hexagon it is possible that we can know the dyld breakpoint without @@ -106,18 +105,18 @@ /// Returns the current state of the rendezvous structure. uint64_t GetState() const { return m_current.state; } - /// @returns the base address of the runtime linker in the inferiors address + /// \returns the base address of the runtime linker in the inferiors address /// space. lldb::addr_t GetLDBase() const { return m_current.ldbase; } - /// @returns the thread layout metadata from the inferiors thread library. + /// \returns the thread layout metadata from the inferiors thread library. const ThreadInfo &GetThreadInfo(); - /// @returns true if modules have been loaded into the inferior since the + /// \returns true if modules have been loaded into the inferior since the /// last call to Resolve(). bool ModulesDidLoad() const { return !m_added_soentries.empty(); } - /// @returns true if modules have been unloaded from the inferior since the + /// \returns true if modules have been unloaded from the inferior since the /// last call to Resolve(). bool ModulesDidUnload() const { return !m_removed_soentries.empty(); } @@ -125,7 +124,7 @@ /// Constants describing the state of the rendezvous. /// - /// @see GetState(). + /// \see GetState(). enum RendezvousState { eConsistent = 0, eAdd, @@ -208,15 +207,15 @@ /// Threading metadata read from the inferior. ThreadInfo m_thread_info; - /// Reads an unsigned integer of @p size bytes from the inferior's address - /// space starting at @p addr. + /// Reads an unsigned integer of \p size bytes from the inferior's address + /// space starting at \p addr. /// - /// @returns addr + size if the read was successful and false otherwise. + /// \returns addr + size if the read was successful and false otherwise. lldb::addr_t ReadWord(lldb::addr_t addr, uint64_t *dst, size_t size); - /// Reads an address from the inferior's address space starting at @p addr. + /// Reads an address from the inferior's address space starting at \p addr. /// - /// @returns addr + target address size if the read was successful and + /// \returns addr + target address size if the read was successful and /// 0 otherwise. lldb::addr_t ReadPointer(lldb::addr_t addr, lldb::addr_t *dst); @@ -224,7 +223,7 @@ /// addr. std::string ReadStringFromMemory(lldb::addr_t addr); - /// Reads an SOEntry starting at @p addr. + /// Reads an SOEntry starting at \p addr. bool ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry); /// Updates the current set of SOEntries, the set of added entries, and the
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp index 944be96..57d87eb 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
@@ -1,9 +1,8 @@ //===-- DynamicLoaderDarwin.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,6 @@ #include "lldb/Symbol/Function.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/ABI.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" @@ -33,6 +31,8 @@ #include "lldb/Utility/Log.h" #include "lldb/Utility/State.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN #ifdef ENABLE_DEBUG_PRINTF #include <stdio.h> @@ -47,53 +47,45 @@ #include <uuid/uuid.h> #endif +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- DynamicLoaderDarwin::DynamicLoaderDarwin(Process *process) : DynamicLoader(process), m_dyld_module_wp(), m_libpthread_module_wp(), m_pthread_getspecific_addr(), m_tid_to_tls_map(), m_dyld_image_infos(), m_dyld_image_infos_stop_id(UINT32_MAX), m_dyld(), m_mutex() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- DynamicLoaderDarwin::~DynamicLoaderDarwin() {} -//------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. -//------------------------------------------------------------------ void DynamicLoaderDarwin::DidAttach() { PrivateInitialize(m_process); DoInitialImageFetch(); SetNotificationBreakpoint(); } -//------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. -//------------------------------------------------------------------ void DynamicLoaderDarwin::DidLaunch() { PrivateInitialize(m_process); DoInitialImageFetch(); SetNotificationBreakpoint(); } -//---------------------------------------------------------------------- // Clear out the state of this class. -//---------------------------------------------------------------------- void DynamicLoaderDarwin::Clear(bool clear_process) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (clear_process) - m_process = NULL; + m_process = nullptr; m_dyld_image_infos.clear(); m_dyld_image_infos_stop_id = UINT32_MAX; m_dyld.Clear(false); @@ -121,8 +113,10 @@ if (!module_sp) { if (can_create) { - module_sp = target.GetSharedModule(module_spec); - if (!module_sp || module_sp->GetObjectFile() == NULL) + // We'll call Target::ModulesDidLoad after all the modules have been + // added to the target, don't let it be called for every one. + module_sp = target.GetOrCreateModule(module_spec, false /* notify */); + if (!module_sp || module_sp->GetObjectFile() == nullptr) module_sp = m_process->ReadModuleFromMemory(image_info.file_spec, image_info.address); @@ -217,10 +211,8 @@ } } -//---------------------------------------------------------------------- // Update the load addresses for all segments in MODULE using the updated INFO // that is passed in. -//---------------------------------------------------------------------- bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module, ImageInfo &info) { bool changed = false; @@ -256,15 +248,7 @@ changed = m_process->GetTarget().SetSectionLoadAddress( section_sp, new_section_load_addr, warn_multiple); - } else { - Host::SystemLog( - Host::eSystemLogWarning, - "warning: unable to find and load segment named '%s' at " - "0x%" PRIx64 " in '%s' in macosx dynamic loader plug-in.\n", - info.segments[i].name.AsCString("<invalid>"), - (uint64_t)new_section_load_addr, - image_object_file->GetFileSpec().GetPath().c_str()); - } + } } } @@ -305,9 +289,7 @@ return changed; } -//---------------------------------------------------------------------- // Unload the segments in MODULE using the INFO that is passed in. -//---------------------------------------------------------------------- bool DynamicLoaderDarwin::UnloadModuleSections(Module *module, ImageInfo &info) { bool changed = false; @@ -477,7 +459,7 @@ image_infos[i].segments.push_back(segment); } - image_infos[i].uuid.SetFromStringRef( + image_infos[i].uuid.SetFromOptionalStringRef( image->GetValueForKey("uuid")->GetAsString()->GetValue()); // All sections listed in the dyld image info structure will all either be @@ -493,7 +475,7 @@ // that starts of file offset zero and that has bytes in the file... if ((image_infos[i].segments[k].fileoff == 0 && image_infos[i].segments[k].filesize > 0) || - (image_infos[i].segments[k].name == ConstString("__TEXT"))) { + (image_infos[i].segments[k].name == "__TEXT")) { image_infos[i].slide = image_infos[i].address - image_infos[i].segments[k].vmaddr; // We have found the slide amount, so we can exit this for loop. @@ -552,8 +534,8 @@ if (exe_idx != UINT32_MAX) { const bool can_create = true; - ModuleSP exe_module_sp( - FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, NULL)); + ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx], + can_create, nullptr)); if (exe_module_sp) { if (log) log->Printf("Found executable module: %s", @@ -568,8 +550,8 @@ if (dyld_idx != UINT32_MAX) { const bool can_create = true; - ModuleSP dyld_sp = - FindTargetModuleForImageInfo(image_infos[dyld_idx], can_create, NULL); + ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_infos[dyld_idx], + can_create, nullptr); if (dyld_sp.get()) { if (log) log->Printf("Found dyld module: %s", @@ -586,7 +568,7 @@ if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) { const bool can_create = true; ModuleSP dyld_sp = - FindTargetModuleForImageInfo(image_info, can_create, NULL); + FindTargetModuleForImageInfo(image_info, can_create, nullptr); if (dyld_sp.get()) { Target &target = m_process->GetTarget(); target.GetImages().AppendIfNeeded(dyld_sp); @@ -624,7 +606,7 @@ m_dyld_image_infos.push_back(image_infos[idx]); ModuleSP image_module_sp( - FindTargetModuleForImageInfo(image_infos[idx], true, NULL)); + FindTargetModuleForImageInfo(image_infos[idx], true, nullptr)); if (image_module_sp) { ObjectFile *objfile = image_module_sp->GetObjectFile(); @@ -644,9 +626,10 @@ module_spec.SetObjectOffset(objfile->GetFileOffset() + commpage_section->GetFileOffset()); module_spec.SetObjectSize(objfile->GetByteSize()); - commpage_image_module_sp = target.GetSharedModule(module_spec); + commpage_image_module_sp = target.GetOrCreateModule(module_spec, + true /* notify */); if (!commpage_image_module_sp || - commpage_image_module_sp->GetObjectFile() == NULL) { + commpage_image_module_sp->GetObjectFile() == nullptr) { commpage_image_module_sp = m_process->ReadModuleFromMemory( image_infos[idx].file_spec, image_infos[idx].address); // Always load a memory image right away in the target in case @@ -687,7 +670,6 @@ return true; } -//---------------------------------------------------------------------- // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch // functions written in hand-written assembly, and also have hand-written // unwind information in the eh_frame section. Normally we prefer analyzing @@ -699,27 +681,25 @@ // extensible so they could have an Apple-specific flag) which indicates that // the instructions are asynchronous -- accurate at every instruction, instead // of our normal default assumption that they are not. -//---------------------------------------------------------------------- bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) { ModuleSP module_sp; if (sym_ctx.symbol) { module_sp = sym_ctx.symbol->GetAddressRef().GetModule(); } - if (module_sp.get() == NULL && sym_ctx.function) { + if (module_sp.get() == nullptr && sym_ctx.function) { module_sp = sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule(); } - if (module_sp.get() == NULL) + if (module_sp.get() == nullptr) return false; - ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime(); - return objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary(module_sp); + ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*m_process); + return objc_runtime != nullptr && + objc_runtime->IsModuleObjCLibrary(module_sp); } -//---------------------------------------------------------------------- // Dump a Segment to the file handle provided. -//---------------------------------------------------------------------- void DynamicLoaderDarwin::Segment::PutToLog(Log *log, lldb::addr_t slide) const { if (log) { @@ -735,18 +715,16 @@ } const DynamicLoaderDarwin::Segment * -DynamicLoaderDarwin::ImageInfo::FindSegment(const ConstString &name) const { +DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const { const size_t num_segments = segments.size(); for (size_t i = 0; i < num_segments; ++i) { if (segments[i].name == name) return &segments[i]; } - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Dump an image info structure to the file handle provided. -//---------------------------------------------------------------------- void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const { if (!log) return; @@ -769,9 +747,7 @@ m_process->GetTarget().ClearAllLoadedSections(); } -//---------------------------------------------------------------------- // Member function that gets called when the process state changes. -//---------------------------------------------------------------------- void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process, StateType state) { DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__, @@ -817,11 +793,11 @@ Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); TargetSP target_sp(thread.CalculateTarget()); - if (current_symbol != NULL) { + if (current_symbol != nullptr) { std::vector<Address> addresses; if (current_symbol->IsTrampoline()) { - const ConstString &trampoline_name = current_symbol->GetMangled().GetName( + ConstString trampoline_name = current_symbol->GetMangled().GetName( current_symbol->GetLanguage(), Mangled::ePreferMangled); if (trampoline_name) { @@ -948,8 +924,8 @@ load_addrs.push_back(address.GetLoadAddress(target_sp.get())); } } - thread_plan_sp.reset( - new ThreadPlanRunToAddress(thread, load_addrs, stop_others)); + thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>( + thread, load_addrs, stop_others); } } else { if (log) @@ -962,7 +938,7 @@ size_t DynamicLoaderDarwin::FindEquivalentSymbols( lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images, lldb_private::SymbolContextList &equivalent_symbols) { - const ConstString &trampoline_name = original_symbol->GetMangled().GetName( + ConstString trampoline_name = original_symbol->GetMangled().GetName( original_symbol->GetLanguage(), Mangled::ePreferMangled); if (!trampoline_name) return 0;
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h index 690253b..aac0a5d 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderDarwin.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,14 +28,12 @@ public: DynamicLoaderDarwin(lldb_private::Process *process); - virtual ~DynamicLoaderDarwin() override; + ~DynamicLoaderDarwin() override; - //------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. - //------------------------------------------------------------------ void DidAttach() override; void DidLaunch() override; @@ -158,7 +155,7 @@ header.cputype, header.cpusubtype); } - const Segment *FindSegment(const lldb_private::ConstString &name) const; + const Segment *FindSegment(lldb_private::ConstString name) const; void PutToLog(lldb_private::Log *log) const;
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.cpp index 1ff0ec2..6bc65ec 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.cpp
@@ -1,9 +1,8 @@ //===-- DynamicLoaderMacOS.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,11 +27,9 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Create an instance of this class. This function is filled into the plugin // info class that gets handed out by the plugin factory and allows the lldb to // instantiate an instance of this class. -//---------------------------------------------------------------------- DynamicLoader *DynamicLoaderMacOS::CreateInstance(Process *process, bool force) { bool create = force; @@ -71,20 +68,16 @@ if (create) return new DynamicLoaderMacOS(process); - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- DynamicLoaderMacOS::DynamicLoaderMacOS(Process *process) : DynamicLoaderDarwin(process), m_image_infos_stop_id(UINT32_MAX), m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(), m_maybe_image_infos_address(LLDB_INVALID_ADDRESS) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- DynamicLoaderMacOS::~DynamicLoaderMacOS() { if (LLDB_BREAK_ID_IS_VALID(m_break_id)) m_process->GetTarget().RemoveBreakpointByID(m_break_id); @@ -118,7 +111,7 @@ const Symbol *symbol = frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol; if (symbol) { - if (symbol->GetName() == ConstString("_dyld_start")) + if (symbol->GetName() == "_dyld_start") did_exec = true; } } @@ -134,9 +127,7 @@ return did_exec; } -//---------------------------------------------------------------------- // Clear out the state of this class. -//---------------------------------------------------------------------- void DynamicLoaderMacOS::DoClear() { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -146,9 +137,7 @@ m_break_id = LLDB_INVALID_BREAK_ID; } -//---------------------------------------------------------------------- // Check if we have found DYLD yet -//---------------------------------------------------------------------- bool DynamicLoaderMacOS::DidSetNotificationBreakpoint() { return LLDB_BREAK_ID_IS_VALID(m_break_id); } @@ -160,12 +149,10 @@ } } -//---------------------------------------------------------------------- // Try and figure out where dyld is by first asking the Process if it knows // (which currently calls down in the lldb::Process to get the DYLD info // (available on SnowLeopard only). If that fails, then check in the default // addresses. -//---------------------------------------------------------------------- void DynamicLoaderMacOS::DoInitialImageFetch() { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); @@ -201,12 +188,10 @@ bool DynamicLoaderMacOS::NeedToDoInitialImageFetch() { return true; } -//---------------------------------------------------------------------- // Static callback function that gets called when our DYLD notification // breakpoint gets hit. We update all of our image infos and then let our super // class DynamicLoader class decide if we should stop or not (based on global // preference). -//---------------------------------------------------------------------- bool DynamicLoaderMacOS::NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, @@ -348,9 +333,8 @@ // Dump the _dyld_all_image_infos members and all current image infos that we // have parsed to the file handle provided. -//---------------------------------------------------------------------- void DynamicLoaderMacOS::PutToLog(Log *log) const { - if (log == NULL) + if (log == nullptr) return; } @@ -538,9 +522,7 @@ "in MacOSX user processes."; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString DynamicLoaderMacOS::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.h index 6303c06..9ccb3bc 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderMacOS.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,11 +32,9 @@ public: DynamicLoaderMacOS(lldb_private::Process *process); - virtual ~DynamicLoaderMacOS() override; + ~DynamicLoaderMacOS() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -49,12 +46,10 @@ static lldb_private::DynamicLoader * CreateInstance(lldb_private::Process *process, bool force); - //------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. - //------------------------------------------------------------------ bool ProcessDidExec() override; lldb_private::Status CanLoadImage() override; @@ -64,9 +59,7 @@ lldb_private::LazyBool &using_shared_cache, lldb_private::LazyBool &private_shared_cache) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp index ec459a7..53424f0 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp
@@ -1,9 +1,8 @@ //===-- DynamicLoaderMacOSXDYLD.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,7 +16,6 @@ #include "lldb/Symbol/Function.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/ABI.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" @@ -31,6 +29,8 @@ #include "DynamicLoaderDarwin.h" #include "DynamicLoaderMacOSXDYLD.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN #ifdef ENABLE_DEBUG_PRINTF #include <stdio.h> @@ -48,11 +48,9 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Create an instance of this class. This function is filled into the plugin // info class that gets handed out by the plugin factory and allows the lldb to // instantiate an instance of this class. -//---------------------------------------------------------------------- DynamicLoader *DynamicLoaderMacOSXDYLD::CreateInstance(Process *process, bool force) { bool create = force; @@ -91,12 +89,10 @@ if (create) return new DynamicLoaderMacOSXDYLD(process); - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD(Process *process) : DynamicLoaderDarwin(process), m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS), @@ -104,9 +100,7 @@ m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(), m_process_image_addr_is_all_images_infos(false) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD() { if (LLDB_BREAK_ID_IS_VALID(m_break_id)) m_process->GetTarget().RemoveBreakpointByID(m_break_id); @@ -143,7 +137,7 @@ const Symbol *symbol = frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol; if (symbol) { - if (symbol->GetName() == ConstString("_dyld_start")) + if (symbol->GetName() == "_dyld_start") did_exec = true; } } @@ -159,9 +153,7 @@ return did_exec; } -//---------------------------------------------------------------------- // Clear out the state of this class. -//---------------------------------------------------------------------- void DynamicLoaderMacOSXDYLD::DoClear() { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -173,9 +165,7 @@ m_break_id = LLDB_INVALID_BREAK_ID; } -//---------------------------------------------------------------------- // Check if we have found DYLD yet -//---------------------------------------------------------------------- bool DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() { return LLDB_BREAK_ID_IS_VALID(m_break_id); } @@ -186,12 +176,10 @@ } } -//---------------------------------------------------------------------- // Try and figure out where dyld is by first asking the Process if it knows // (which currently calls down in the lldb::Process to get the DYLD info // (available on SnowLeopard only). If that fails, then check in the default // addresses. -//---------------------------------------------------------------------- void DynamicLoaderMacOSXDYLD::DoInitialImageFetch() { if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) { // Check the image info addr as it might point to the mach header for dyld, @@ -255,9 +243,7 @@ return; } -//---------------------------------------------------------------------- // Assume that dyld is in memory at ADDR and try to parse it's load commands -//---------------------------------------------------------------------- bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback( lldb::addr_t addr) { std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex()); @@ -313,12 +299,10 @@ return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS; } -//---------------------------------------------------------------------- // Static callback function that gets called when our DYLD notification // breakpoint gets hit. We update all of our image infos and then let our super // class DynamicLoader class decide if we should stop or not (based on global // preference). -//---------------------------------------------------------------------- bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit( void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id) { @@ -625,7 +609,7 @@ // We'll remove them all at one go later on. ModuleSP unload_image_module_sp( - FindTargetModuleForImageInfo(image_infos[idx], false, NULL)); + FindTargetModuleForImageInfo(image_infos[idx], false, nullptr)); if (unload_image_module_sp.get()) { // When we unload, be sure to use the image info from the old list, // since that has sections correctly filled in. @@ -702,12 +686,10 @@ } } -//---------------------------------------------------------------------- // If we have found where the "_dyld_all_image_infos" lives in memory, read the // current info from it, and then update all image load addresses (or lack // thereof). Only do this if this is the first time we're reading the dyld // infos. Return true if we actually read anything, and false otherwise. -//---------------------------------------------------------------------- bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); @@ -769,12 +751,10 @@ return false; } -//---------------------------------------------------------------------- // Read a mach_header at ADDR into HEADER, and also fill in the load command // data into LOAD_COMMAND_DATA if it is non-NULL. // // Returns true if we succeed, false if we fail for any reason. -//---------------------------------------------------------------------- bool DynamicLoaderMacOSXDYLD::ReadMachHeader(lldb::addr_t addr, llvm::MachO::mach_header *header, DataExtractor *load_command_data) { @@ -815,7 +795,7 @@ if (data.GetU32(&offset, &header->cputype, (sizeof(llvm::MachO::mach_header) / sizeof(uint32_t)) - 1)) { - if (load_command_data == NULL) + if (load_command_data == nullptr) return true; // We were able to read the mach_header and weren't asked // to read the load command bytes @@ -841,9 +821,7 @@ return false; // We failed the read the mach_header } -//---------------------------------------------------------------------- // Parse the load commands for an image -//---------------------------------------------------------------------- uint32_t DynamicLoaderMacOSXDYLD::ParseLoadCommands(const DataExtractor &data, ImageInfo &dylib_info, FileSpec *lc_id_dylinker) { @@ -921,7 +899,7 @@ // starts of file offset zero and that has bytes in the file... if ((dylib_info.segments[i].fileoff == 0 && dylib_info.segments[i].filesize > 0) || - (dylib_info.segments[i].name == ConstString("__TEXT"))) { + (dylib_info.segments[i].name == "__TEXT")) { dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr; // We have found the slide amount, so we can exit this for loop. break; @@ -930,10 +908,8 @@ return cmd_idx; } -//---------------------------------------------------------------------- // Read the mach_header and load commands for each image that the // _dyld_all_image_infos structure points to and cache the results. -//---------------------------------------------------------------------- void DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands( ImageInfo::collection &image_infos, uint32_t infos_count, @@ -947,7 +923,7 @@ &data)) continue; - ParseLoadCommands(data, image_infos[i], NULL); + ParseLoadCommands(data, image_infos[i], nullptr); if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) exe_idx = i; @@ -958,8 +934,8 @@ if (exe_idx < image_infos.size()) { const bool can_create = true; - ModuleSP exe_module_sp( - FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, NULL)); + ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx], + can_create, nullptr)); if (exe_module_sp) { UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]); @@ -991,12 +967,10 @@ } } -//---------------------------------------------------------------------- // Dump the _dyld_all_image_infos members and all current image infos that we // have parsed to the file handle provided. -//---------------------------------------------------------------------- void DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const { - if (log == NULL) + if (log == nullptr) return; std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -1160,9 +1134,7 @@ "in MacOSX user processes."; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h index 3dc0f15..00b2ebf 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderMacOSXDYLD.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -37,11 +36,9 @@ public: DynamicLoaderMacOSXDYLD(lldb_private::Process *process); - virtual ~DynamicLoaderMacOSXDYLD() override; + ~DynamicLoaderMacOSXDYLD() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -53,12 +50,10 @@ static lldb_private::DynamicLoader * CreateInstance(lldb_private::Process *process, bool force); - //------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. - //------------------------------------------------------------------ bool ProcessDidExec() override; lldb_private::Status CanLoadImage() override; @@ -68,9 +63,7 @@ lldb_private::LazyBool &using_shared_cache, lldb_private::LazyBool &private_shared_cache) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -128,7 +121,7 @@ dyldImageLoadAddress = LLDB_INVALID_ADDRESS; } - bool IsValid() const { return version >= 1 || version <= 6; } + bool IsValid() const { return version >= 1 && version <= 6; } }; static lldb::ByteOrder GetByteOrderFromMagic(uint32_t magic);
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.cpp deleted file mode 100644 index 8068795..0000000 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.cpp +++ /dev/null
@@ -1,142 +0,0 @@ -//===-- AuxVector.cpp -------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "AuxVector.h" -#include "lldb/Target/Process.h" -#include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Log.h" - -using namespace lldb; -using namespace lldb_private; - -static bool GetMaxU64(DataExtractor &data, lldb::offset_t *offset_ptr, - uint64_t *value, unsigned int byte_size) { - lldb::offset_t saved_offset = *offset_ptr; - *value = data.GetMaxU64(offset_ptr, byte_size); - return *offset_ptr != saved_offset; -} - -static bool ParseAuxvEntry(DataExtractor &data, AuxVector::Entry &entry, - lldb::offset_t *offset_ptr, unsigned int byte_size) { - if (!GetMaxU64(data, offset_ptr, &entry.type, byte_size)) - return false; - - if (!GetMaxU64(data, offset_ptr, &entry.value, byte_size)) - return false; - - return true; -} - -DataBufferSP AuxVector::GetAuxvData() { - if (m_process) - return m_process->GetAuxvData(); - else - return DataBufferSP(); -} - -void AuxVector::ParseAuxv(DataExtractor &data) { - const unsigned int byte_size = m_process->GetAddressByteSize(); - lldb::offset_t offset = 0; - - for (;;) { - Entry entry; - - if (!ParseAuxvEntry(data, entry, &offset, byte_size)) - break; - - if (entry.type == AUXV_AT_NULL) - break; - - if (entry.type == AUXV_AT_IGNORE) - continue; - - m_auxv.push_back(entry); - } -} - -AuxVector::AuxVector(Process *process) : m_process(process) { - DataExtractor data; - Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); - - data.SetData(GetAuxvData()); - data.SetByteOrder(m_process->GetByteOrder()); - data.SetAddressByteSize(m_process->GetAddressByteSize()); - - ParseAuxv(data); - - if (log) - DumpToLog(log); -} - -AuxVector::iterator AuxVector::FindEntry(EntryType type) const { - for (iterator I = begin(); I != end(); ++I) { - if (I->type == static_cast<uint64_t>(type)) - return I; - } - - return end(); -} - -void AuxVector::DumpToLog(Log *log) const { - if (!log) - return; - - log->PutCString("AuxVector: "); - for (iterator I = begin(); I != end(); ++I) { - log->Printf(" %s [%" PRIu64 "]: %" PRIx64, GetEntryName(*I), I->type, - I->value); - } -} - -const char *AuxVector::GetEntryName(EntryType type) { - const char *name = "AT_???"; - -#define ENTRY_NAME(_type) \ - _type: \ - name = &#_type[5] - switch (type) { - case ENTRY_NAME(AUXV_AT_NULL); break; - case ENTRY_NAME(AUXV_AT_IGNORE); break; - case ENTRY_NAME(AUXV_AT_EXECFD); break; - case ENTRY_NAME(AUXV_AT_PHDR); break; - case ENTRY_NAME(AUXV_AT_PHENT); break; - case ENTRY_NAME(AUXV_AT_PHNUM); break; - case ENTRY_NAME(AUXV_AT_PAGESZ); break; - case ENTRY_NAME(AUXV_AT_BASE); break; - case ENTRY_NAME(AUXV_AT_FLAGS); break; - case ENTRY_NAME(AUXV_AT_ENTRY); break; - case ENTRY_NAME(AUXV_AT_NOTELF); break; - case ENTRY_NAME(AUXV_AT_UID); break; - case ENTRY_NAME(AUXV_AT_EUID); break; - case ENTRY_NAME(AUXV_AT_GID); break; - case ENTRY_NAME(AUXV_AT_EGID); break; - case ENTRY_NAME(AUXV_AT_CLKTCK); break; - case ENTRY_NAME(AUXV_AT_PLATFORM); break; - case ENTRY_NAME(AUXV_AT_HWCAP); break; - case ENTRY_NAME(AUXV_AT_FPUCW); break; - case ENTRY_NAME(AUXV_AT_DCACHEBSIZE); break; - case ENTRY_NAME(AUXV_AT_ICACHEBSIZE); break; - case ENTRY_NAME(AUXV_AT_UCACHEBSIZE); break; - case ENTRY_NAME(AUXV_AT_IGNOREPPC); break; - case ENTRY_NAME(AUXV_AT_SECURE); break; - case ENTRY_NAME(AUXV_AT_BASE_PLATFORM); break; - case ENTRY_NAME(AUXV_AT_RANDOM); break; - case ENTRY_NAME(AUXV_AT_EXECFN); break; - case ENTRY_NAME(AUXV_AT_SYSINFO); break; - case ENTRY_NAME(AUXV_AT_SYSINFO_EHDR); break; - case ENTRY_NAME(AUXV_AT_L1I_CACHESHAPE); break; - case ENTRY_NAME(AUXV_AT_L1D_CACHESHAPE); break; - case ENTRY_NAME(AUXV_AT_L2_CACHESHAPE); break; - case ENTRY_NAME(AUXV_AT_L3_CACHESHAPE); break; - } -#undef ENTRY_NAME - - return name; -}
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.h deleted file mode 100644 index 25446e3..0000000 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.h +++ /dev/null
@@ -1,109 +0,0 @@ -//===-- AuxVector.h ---------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_AuxVector_H_ -#define liblldb_AuxVector_H_ - -#include <vector> - -#include "lldb/lldb-forward.h" - -namespace lldb_private { -class DataExtractor; -} - -/// @class AuxVector -/// Represents a processes auxiliary vector. -/// -/// When a process is loaded on Linux a vector of values is placed onto the -/// stack communicating operating system specific information. On -/// construction this class locates and parses this information and provides a -/// simple read-only interface to the entries found. -class AuxVector { - -public: - AuxVector(lldb_private::Process *process); - - struct Entry { - uint64_t type; - uint64_t value; - - Entry() : type(0), value(0) {} - }; - - /// Constants describing the type of entry. - /// On Linux, running "LD_SHOW_AUXV=1 ./executable" will spew AUX - /// information. Added AUXV prefix to avoid potential conflicts with system- - /// defined macros - enum EntryType { - AUXV_AT_NULL = 0, ///< End of auxv. - AUXV_AT_IGNORE = 1, ///< Ignore entry. - AUXV_AT_EXECFD = 2, ///< File descriptor of program. - AUXV_AT_PHDR = 3, ///< Program headers. - AUXV_AT_PHENT = 4, ///< Size of program header. - AUXV_AT_PHNUM = 5, ///< Number of program headers. - AUXV_AT_PAGESZ = 6, ///< Page size. - AUXV_AT_BASE = 7, ///< Interpreter base address. - AUXV_AT_FLAGS = 8, ///< Flags. - AUXV_AT_ENTRY = 9, ///< Program entry point. - AUXV_AT_NOTELF = 10, ///< Set if program is not an ELF. - AUXV_AT_UID = 11, ///< UID. - AUXV_AT_EUID = 12, ///< Effective UID. - AUXV_AT_GID = 13, ///< GID. - AUXV_AT_EGID = 14, ///< Effective GID. - AUXV_AT_CLKTCK = 17, ///< Clock frequency (e.g. times(2)). - AUXV_AT_PLATFORM = 15, ///< String identifying platform. - AUXV_AT_HWCAP = 16, ///< Machine dependent hints about processor capabilities. - AUXV_AT_FPUCW = 18, ///< Used FPU control word. - AUXV_AT_DCACHEBSIZE = 19, ///< Data cache block size. - AUXV_AT_ICACHEBSIZE = 20, ///< Instruction cache block size. - AUXV_AT_UCACHEBSIZE = 21, ///< Unified cache block size. - AUXV_AT_IGNOREPPC = 22, ///< Entry should be ignored. - AUXV_AT_SECURE = 23, ///< Boolean, was exec setuid-like? - AUXV_AT_BASE_PLATFORM = 24, ///< String identifying real platforms. - AUXV_AT_RANDOM = 25, ///< Address of 16 random bytes. - AUXV_AT_EXECFN = 31, ///< Filename of executable. - AUXV_AT_SYSINFO = 32, ///< Pointer to the global system page used for system - ///calls and other nice things. - AUXV_AT_SYSINFO_EHDR = 33, - AUXV_AT_L1I_CACHESHAPE = 34, ///< Shapes of the caches. - AUXV_AT_L1D_CACHESHAPE = 35, - AUXV_AT_L2_CACHESHAPE = 36, - AUXV_AT_L3_CACHESHAPE = 37, - }; - -private: - typedef std::vector<Entry> EntryVector; - -public: - typedef EntryVector::const_iterator iterator; - - iterator begin() const { return m_auxv.begin(); } - iterator end() const { return m_auxv.end(); } - - iterator FindEntry(EntryType type) const; - - static const char *GetEntryName(const Entry &entry) { - return GetEntryName(static_cast<EntryType>(entry.type)); - } - - static const char *GetEntryName(EntryType type); - - void DumpToLog(lldb_private::Log *log) const; - -private: - lldb_private::Process *m_process; - EntryVector m_auxv; - - lldb::DataBufferSP GetAuxvData(); - - void ParseAuxv(lldb_private::DataExtractor &data); -}; - -#endif
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/CMakeLists.txt index 409ba92..c1e00b2 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/CMakeLists.txt
@@ -1,5 +1,4 @@ add_lldb_library(lldbPluginDynamicLoaderPosixDYLD PLUGIN - AuxVector.cpp DYLDRendezvous.cpp DynamicLoaderPOSIXDYLD.cpp @@ -10,6 +9,7 @@ lldbSymbol lldbTarget lldbPluginProcessElfCore + lldbPluginProcessUtility LINK_COMPONENTS Support )
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp index b30a1ab..0d73673 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp
@@ -1,9 +1,8 @@ //===-- DYLDRendezvous.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -489,10 +488,7 @@ const ArchSpec &arch = m_process->GetTarget().GetArchitecture(); if ((arch.GetTriple().getOS() == llvm::Triple::FreeBSD || arch.GetTriple().getOS() == llvm::Triple::NetBSD) && - (arch.GetMachine() == llvm::Triple::mips || - arch.GetMachine() == llvm::Triple::mipsel || - arch.GetMachine() == llvm::Triple::mips64 || - arch.GetMachine() == llvm::Triple::mips64el)) { + arch.IsMIPS()) { addr_t mips_l_offs; if (!(addr = ReadPointer(addr, &mips_l_offs))) return false;
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.h index f1a62c3..993e62f 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.h
@@ -1,9 +1,8 @@ //===-- DYLDRendezvous.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,7 +24,7 @@ class Process; } -/// @class DYLDRendezvous +/// \class DYLDRendezvous /// Interface to the runtime linker. /// /// A structure is present in a processes memory space which is updated by the @@ -67,50 +66,50 @@ /// This method should be called once one start up, then once each time the /// runtime linker enters the function given by GetBreakAddress(). /// - /// @returns true on success and false on failure. + /// \returns true on success and false on failure. /// - /// @see GetBreakAddress(). + /// \see GetBreakAddress(). bool Resolve(); - /// @returns true if this rendezvous has been located in the inferiors + /// \returns true if this rendezvous has been located in the inferiors /// address space and false otherwise. bool IsValid(); - /// @returns the address of the rendezvous structure in the inferiors + /// \returns the address of the rendezvous structure in the inferiors /// address space. lldb::addr_t GetRendezvousAddress() const { return m_rendezvous_addr; } - /// @returns the version of the rendezvous protocol being used. + /// \returns the version of the rendezvous protocol being used. uint64_t GetVersion() const { return m_current.version; } - /// @returns address in the inferiors address space containing the linked + /// \returns address in the inferiors address space containing the linked /// list of shared object descriptors. lldb::addr_t GetLinkMapAddress() const { return m_current.map_addr; } /// A breakpoint should be set at this address and Resolve called on each /// hit. /// - /// @returns the address of a function called by the runtime linker each + /// \returns the address of a function called by the runtime linker each /// time a module is loaded/unloaded, or about to be loaded/unloaded. /// - /// @see Resolve() + /// \see Resolve() lldb::addr_t GetBreakAddress() const { return m_current.brk; } /// Returns the current state of the rendezvous structure. uint64_t GetState() const { return m_current.state; } - /// @returns the base address of the runtime linker in the inferiors address + /// \returns the base address of the runtime linker in the inferiors address /// space. lldb::addr_t GetLDBase() const { return m_current.ldbase; } - /// @returns the thread layout metadata from the inferiors thread library. + /// \returns the thread layout metadata from the inferiors thread library. const ThreadInfo &GetThreadInfo(); - /// @returns true if modules have been loaded into the inferior since the + /// \returns true if modules have been loaded into the inferior since the /// last call to Resolve(). bool ModulesDidLoad() const { return !m_added_soentries.empty(); } - /// @returns true if modules have been unloaded from the inferior since the + /// \returns true if modules have been unloaded from the inferior since the /// last call to Resolve(). bool ModulesDidUnload() const { return !m_removed_soentries.empty(); } @@ -118,7 +117,7 @@ /// Constants describing the state of the rendezvous. /// - /// @see GetState(). + /// \see GetState(). enum RendezvousState { eConsistent, eAdd, eDelete }; /// Structure representing the shared objects currently loaded into the @@ -202,15 +201,15 @@ /// Threading metadata read from the inferior. ThreadInfo m_thread_info; - /// Reads an unsigned integer of @p size bytes from the inferior's address - /// space starting at @p addr. + /// Reads an unsigned integer of \p size bytes from the inferior's address + /// space starting at \p addr. /// - /// @returns addr + size if the read was successful and false otherwise. + /// \returns addr + size if the read was successful and false otherwise. lldb::addr_t ReadWord(lldb::addr_t addr, uint64_t *dst, size_t size); - /// Reads an address from the inferior's address space starting at @p addr. + /// Reads an address from the inferior's address space starting at \p addr. /// - /// @returns addr + target address size if the read was successful and + /// \returns addr + target address size if the read was successful and /// 0 otherwise. lldb::addr_t ReadPointer(lldb::addr_t addr, lldb::addr_t *dst); @@ -218,7 +217,7 @@ /// addr. std::string ReadStringFromMemory(lldb::addr_t addr); - /// Reads an SOEntry starting at @p addr. + /// Reads an SOEntry starting at \p addr. bool ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry); /// Updates the current set of SOEntries, the set of added entries, and the
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp index 6774b4f..b556608 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp
@@ -1,17 +1,14 @@ //===-- DynamicLoaderPOSIXDYLD.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // Main header include #include "DynamicLoaderPOSIXDYLD.h" -#include "AuxVector.h" - #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" @@ -21,12 +18,13 @@ #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/Platform.h" -#include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlanRunToAddress.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" +#include <memory> using namespace lldb; using namespace lldb_private; @@ -68,7 +66,7 @@ if (create) return new DynamicLoaderPOSIXDYLD(process); - return NULL; + return nullptr; } DynamicLoaderPOSIXDYLD::DynamicLoaderPOSIXDYLD(Process *process) @@ -90,8 +88,8 @@ if (log) log->Printf("DynamicLoaderPOSIXDYLD::%s() pid %" PRIu64, __FUNCTION__, m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID); + m_auxv = llvm::make_unique<AuxVector>(m_process->GetAuxvData()); - m_auxv.reset(new AuxVector(m_process)); if (log) log->Printf("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " reloaded auxv data", __FUNCTION__, @@ -150,11 +148,6 @@ true); LoadAllCurrentModules(); - if (!SetRendezvousBreakpoint()) { - // If we cannot establish rendezvous breakpoint right now we'll try again - // at entry point. - ProbeEntry(); - } m_process->GetTarget().ModulesDidLoad(module_list); if (log) { @@ -169,6 +162,14 @@ } } } + + if (executable_sp.get()) { + if (!SetRendezvousBreakpoint()) { + // If we cannot establish rendezvous breakpoint right now we'll try again + // at entry point. + ProbeEntry(); + } + } } void DynamicLoaderPOSIXDYLD::DidLaunch() { @@ -179,7 +180,7 @@ ModuleSP executable; addr_t load_offset; - m_auxv.reset(new AuxVector(m_process)); + m_auxv = llvm::make_unique<AuxVector>(m_process->GetAuxvData()); executable = GetTargetExecutable(); load_offset = ComputeLoadOffset(); @@ -463,7 +464,7 @@ const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol); Symbol *sym = context.symbol; - if (sym == NULL || !sym->IsTrampoline()) + if (sym == nullptr || !sym->IsTrampoline()) return thread_plan_sp; ConstString sym_name = sym->GetName(); @@ -498,7 +499,8 @@ llvm::sort(start, end); addrs.erase(std::unique(start, end), end); - thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop)); + thread_plan_sp = + std::make_shared<ThreadPlanRunToAddress>(thread, addrs, stop); } return thread_plan_sp; @@ -542,7 +544,8 @@ FileSpec file(info.GetName().GetCString()); ModuleSpec module_spec(file, target.GetArchitecture()); - if (ModuleSP module_sp = target.GetSharedModule(module_spec)) { + if (ModuleSP module_sp = target.GetOrCreateModule(module_spec, + true /* notify */)) { UpdateLoadedSections(module_sp, LLDB_INVALID_ADDRESS, m_interpreter_base, false); return module_sp; @@ -623,28 +626,28 @@ } void DynamicLoaderPOSIXDYLD::EvalSpecialModulesStatus() { - auto I = m_auxv->FindEntry(AuxVector::AUXV_AT_SYSINFO_EHDR); - if (I != m_auxv->end() && I->value != 0) - m_vdso_base = I->value; + if (llvm::Optional<uint64_t> vdso_base = + m_auxv->GetAuxValue(AuxVector::AUXV_AT_SYSINFO_EHDR)) + m_vdso_base = *vdso_base; - I = m_auxv->FindEntry(AuxVector::AUXV_AT_BASE); - if (I != m_auxv->end() && I->value != 0) - m_interpreter_base = I->value; + if (llvm::Optional<uint64_t> interpreter_base = + m_auxv->GetAuxValue(AuxVector::AUXV_AT_BASE)) + m_interpreter_base = *interpreter_base; } addr_t DynamicLoaderPOSIXDYLD::GetEntryPoint() { if (m_entry_point != LLDB_INVALID_ADDRESS) return m_entry_point; - if (m_auxv.get() == NULL) + if (m_auxv == nullptr) return LLDB_INVALID_ADDRESS; - AuxVector::iterator I = m_auxv->FindEntry(AuxVector::AUXV_AT_ENTRY); - - if (I == m_auxv->end()) + llvm::Optional<uint64_t> entry_point = + m_auxv->GetAuxValue(AuxVector::AUXV_AT_ENTRY); + if (!entry_point) return LLDB_INVALID_ADDRESS; - m_entry_point = static_cast<addr_t>(I->value); + m_entry_point = static_cast<addr_t>(*entry_point); const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h index c5f2d3b..0630d1e 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderPOSIXDYLD.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,6 +13,7 @@ #include <memory> #include "DYLDRendezvous.h" +#include "Plugins/Process/Utility/AuxVector.h" #include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Core/ModuleList.h" #include "lldb/Target/DynamicLoader.h" @@ -37,9 +37,7 @@ static lldb_private::DynamicLoader * CreateInstance(lldb_private::Process *process, bool force); - //------------------------------------------------------------------ // DynamicLoader protocol - //------------------------------------------------------------------ void DidAttach() override; @@ -54,9 +52,7 @@ const lldb::ThreadSP thread, lldb::addr_t tls_file_addr) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -103,21 +99,21 @@ /// of loaded modules. void RefreshModules(); - /// Updates the load address of every allocatable section in @p module. + /// Updates the load address of every allocatable section in \p module. /// - /// @param module The module to traverse. + /// \param module The module to traverse. /// - /// @param link_map_addr The virtual address of the link map for the @p + /// \param link_map_addr The virtual address of the link map for the @p /// module. /// - /// @param base_addr The virtual base address @p module is loaded at. + /// \param base_addr The virtual base address \p module is loaded at. void UpdateLoadedSections(lldb::ModuleSP module, lldb::addr_t link_map_addr, lldb::addr_t base_addr, bool base_addr_is_offset) override; - /// Removes the loaded sections from the target in @p module. + /// Removes the loaded sections from the target in \p module. /// - /// @param module The module to traverse. + /// \param module The module to traverse. void UnloadSections(const lldb::ModuleSP module) override; /// Resolves the entry point for the current inferior process and sets a
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp index 2960e39..6bc951c 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp
@@ -1,9 +1,8 @@ //===-- DynamicLoaderStatic.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,11 +17,9 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Create an instance of this class. This function is filled into the plugin // info class that gets handed out by the plugin factory and allows the lldb to // instantiate an instance of this class. -//---------------------------------------------------------------------- DynamicLoader *DynamicLoaderStatic::CreateInstance(Process *process, bool force) { bool create = force; @@ -46,34 +43,26 @@ if (create) return new DynamicLoaderStatic(process); - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- DynamicLoaderStatic::DynamicLoaderStatic(Process *process) : DynamicLoader(process) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- DynamicLoaderStatic::~DynamicLoaderStatic() {} -//------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. -//------------------------------------------------------------------ void DynamicLoaderStatic::DidAttach() { LoadAllImagesAtFileAddresses(); } -//------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. -//------------------------------------------------------------------ void DynamicLoaderStatic::DidLaunch() { LoadAllImagesAtFileAddresses(); } void DynamicLoaderStatic::LoadAllImagesAtFileAddresses() { @@ -157,9 +146,7 @@ "addresses contained in each image."; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString DynamicLoaderStatic::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h index 7f8f82c..fa9aded 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderStatic.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,9 +20,7 @@ ~DynamicLoaderStatic() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -35,12 +32,10 @@ static lldb_private::DynamicLoader * CreateInstance(lldb_private::Process *process, bool force); - //------------------------------------------------------------------ /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. - //------------------------------------------------------------------ void DidAttach() override; void DidLaunch() override; @@ -50,9 +45,7 @@ lldb_private::Status CanLoadImage() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp index 9405b1a..fa3fbe0 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp
@@ -1,10 +1,9 @@ //===-- DynamicLoaderWindowsDYLD.cpp --------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,6 +12,7 @@ #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Target.h" @@ -62,6 +62,64 @@ return nullptr; } +void DynamicLoaderWindowsDYLD::OnLoadModule(lldb::ModuleSP module_sp, + const ModuleSpec module_spec, + lldb::addr_t module_addr) { + + // Resolve the module unless we already have one. + if (!module_sp) { + Status error; + module_sp = m_process->GetTarget().GetOrCreateModule(module_spec, + true /* notify */, &error); + if (error.Fail()) + return; + } + + m_loaded_modules[module_sp] = module_addr; + UpdateLoadedSectionsCommon(module_sp, module_addr, false); + ModuleList module_list; + module_list.Append(module_sp); + m_process->GetTarget().ModulesDidLoad(module_list); +} + +void DynamicLoaderWindowsDYLD::OnUnloadModule(lldb::addr_t module_addr) { + Address resolved_addr; + if (!m_process->GetTarget().ResolveLoadAddress(module_addr, resolved_addr)) + return; + + ModuleSP module_sp = resolved_addr.GetModule(); + if (module_sp) { + m_loaded_modules.erase(module_sp); + UnloadSectionsCommon(module_sp); + ModuleList module_list; + module_list.Append(module_sp); + m_process->GetTarget().ModulesDidUnload(module_list, false); + } +} + +lldb::addr_t DynamicLoaderWindowsDYLD::GetLoadAddress(ModuleSP executable) { + // First, see if the load address is already cached. + auto it = m_loaded_modules.find(executable); + if (it != m_loaded_modules.end() && it->second != LLDB_INVALID_ADDRESS) + return it->second; + + lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; + + // Second, try to get it through the process plugins. For a remote process, + // the remote platform will be responsible for providing it. + FileSpec file_spec(executable->GetPlatformFileSpec()); + bool is_loaded = false; + Status status = + m_process->GetFileLoadAddress(file_spec, is_loaded, load_addr); + // Servers other than lldb server could respond with a bogus address. + if (status.Success() && is_loaded && load_addr != LLDB_INVALID_ADDRESS) { + m_loaded_modules[executable] = load_addr; + return load_addr; + } + + return LLDB_INVALID_ADDRESS; +} + void DynamicLoaderWindowsDYLD::DidAttach() { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); if (log) @@ -74,21 +132,17 @@ // Try to fetch the load address of the file from the process, since there // could be randomization of the load address. + lldb::addr_t load_addr = GetLoadAddress(executable); + if (load_addr == LLDB_INVALID_ADDRESS) + return; - // It might happen that the remote has a different dir for the file, so we - // only send the basename of the executable in the query. I think this is safe - // because I doubt that two executables with the same basenames are loaded in - // memory... - FileSpec file_spec( - executable->GetPlatformFileSpec().GetFilename().GetCString()); - bool is_loaded; - addr_t base_addr = 0; - lldb::addr_t load_addr; - Status error = m_process->GetFileLoadAddress(file_spec, is_loaded, load_addr); - if (error.Success() && is_loaded) { - base_addr = load_addr; - UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, base_addr, false); - } + // Request the process base address. + lldb::addr_t image_base = m_process->GetImageInfoAddress(); + if (image_base == load_addr) + return; + + // Rebase the process's modules if there is a mismatch. + UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_addr, false); ModuleList module_list; module_list.Append(executable); @@ -96,7 +150,26 @@ m_process->LoadModules(); } -void DynamicLoaderWindowsDYLD::DidLaunch() {} +void DynamicLoaderWindowsDYLD::DidLaunch() { + Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); + if (log) + log->Printf("DynamicLoaderWindowsDYLD::%s()", __FUNCTION__); + + ModuleSP executable = GetTargetExecutable(); + if (!executable.get()) + return; + + lldb::addr_t load_addr = GetLoadAddress(executable); + if (load_addr != LLDB_INVALID_ADDRESS) { + // Update the loaded sections so that the breakpoints can be resolved. + UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_addr, false); + + ModuleList module_list; + module_list.Append(executable); + m_process->GetTarget().ModulesDidLoad(module_list); + m_process->LoadModules(); + } +} Status DynamicLoaderWindowsDYLD::CanLoadImage() { return Status(); }
diff --git a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h index 342b32b..100689a 100644 --- a/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h +++ b/src/llvm-project/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h
@@ -1,9 +1,8 @@ //===-- DynamicLoaderWindowsDYLD.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,6 +12,8 @@ #include "lldb/Target/DynamicLoader.h" #include "lldb/lldb-forward.h" +#include <map> + namespace lldb_private { class DynamicLoaderWindowsDYLD : public DynamicLoader { @@ -28,6 +29,10 @@ static DynamicLoader *CreateInstance(Process *process, bool force); + void OnLoadModule(lldb::ModuleSP module_sp, const ModuleSpec module_spec, + lldb::addr_t module_addr); + void OnUnloadModule(lldb::addr_t module_addr); + void DidAttach() override; void DidLaunch() override; Status CanLoadImage() override; @@ -36,6 +41,12 @@ ConstString GetPluginName() override; uint32_t GetPluginVersion() override; + +protected: + lldb::addr_t GetLoadAddress(lldb::ModuleSP executable); + +private: + std::map<lldb::ModuleSP, lldb::addr_t> m_loaded_modules; }; } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/ExpressionParser/CMakeLists.txt index 78db827..17c40ae 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/CMakeLists.txt
@@ -1,2 +1 @@ add_subdirectory(Clang) -add_subdirectory(Rust)
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.cpp index 0d619e4..369f883 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.cpp
@@ -1,9 +1,8 @@ //===-- ASTDumper.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -86,7 +85,7 @@ memcpy(str, m_dump.c_str(), len); - char *end = NULL; + char *end = nullptr; end = strchr(str, '\n');
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.h index 58ba197..ddf055d 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.h
@@ -1,9 +1,8 @@ //===-- ASTDumper.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.cpp index c2bc18a..526ef90 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.cpp
@@ -1,9 +1,8 @@ //===-- ASTResultSynthesizer.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,8 +34,9 @@ ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough, bool top_level, Target &target) - : m_ast_context(NULL), m_passthrough(passthrough), m_passthrough_sema(NULL), - m_target(target), m_sema(NULL), m_top_level(top_level) { + : m_ast_context(nullptr), m_passthrough(passthrough), + m_passthrough_sema(nullptr), m_target(target), m_sema(nullptr), + m_top_level(top_level) { if (!m_passthrough) return; @@ -239,7 +239,7 @@ break; last_expr = implicit_cast->getSubExpr(); - } while (0); + } while (false); // is_lvalue is used to record whether the expression returns an assignable // Lvalue or an Rvalue. This is relevant because they are handled @@ -312,7 +312,7 @@ (is_lvalue ? "lvalue" : "rvalue"), s.c_str()); } - clang::VarDecl *result_decl = NULL; + clang::VarDecl *result_decl = nullptr; if (is_lvalue) { IdentifierInfo *result_ptr_id; @@ -330,14 +330,14 @@ QualType ptr_qual_type; - if (expr_qual_type->getAs<ObjCObjectType>() != NULL) + if (expr_qual_type->getAs<ObjCObjectType>() != nullptr) ptr_qual_type = Ctx.getObjCObjectPointerType(expr_qual_type); else ptr_qual_type = Ctx.getPointerType(expr_qual_type); result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), - result_ptr_id, ptr_qual_type, NULL, SC_Static); + result_ptr_id, ptr_qual_type, nullptr, SC_Static); if (!result_decl) return false; @@ -351,8 +351,9 @@ } else { IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result"); - result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), - &result_id, expr_qual_type, NULL, SC_Static); + result_decl = + VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), &result_id, + expr_qual_type, nullptr, SC_Static); if (!result_decl) return false; @@ -508,7 +509,7 @@ } void ASTResultSynthesizer::ForgetSema() { - m_sema = NULL; + m_sema = nullptr; if (m_passthrough_sema) m_passthrough_sema->ForgetSema();
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.h index 859a1df..670ba6d 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.h
@@ -1,9 +1,8 @@ //===-- ASTResultSynthesizer.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,8 +15,7 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class ASTResultSynthesizer ASTResultSynthesizer.h +/// \class ASTResultSynthesizer ASTResultSynthesizer.h /// "lldb/Expression/ASTResultSynthesizer.h" Adds a result variable /// declaration to the ASTs for an expression. /// @@ -29,165 +27,126 @@ /// ASTResultSynthesizer's job is to add the variable and its initialization /// to the ASTs for the expression, and it does so by acting as a SemaConsumer /// for Clang. -//---------------------------------------------------------------------- class ASTResultSynthesizer : public clang::SemaConsumer { public: - //---------------------------------------------------------------------- /// Constructor /// - /// @param[in] passthrough + /// \param[in] passthrough /// Since the ASTs must typically go through to the Clang code generator /// in order to produce LLVM IR, this SemaConsumer must allow them to /// pass to the next step in the chain after processing. Passthrough is /// the next ASTConsumer, or NULL if none is required. /// - /// @param[in] top_level + /// \param[in] top_level /// If true, register all top-level Decls and don't try to handle the /// main function. /// - /// @param[in] target + /// \param[in] target /// The target, which contains the persistent variable store and the /// AST importer. - //---------------------------------------------------------------------- ASTResultSynthesizer(clang::ASTConsumer *passthrough, bool top_level, Target &target); - //---------------------------------------------------------------------- /// Destructor - //---------------------------------------------------------------------- ~ASTResultSynthesizer() override; - //---------------------------------------------------------------------- /// Link this consumer with a particular AST context /// - /// @param[in] Context + /// \param[in] Context /// This AST context will be used for types and identifiers, and also /// forwarded to the passthrough consumer, if one exists. - //---------------------------------------------------------------------- void Initialize(clang::ASTContext &Context) override; - //---------------------------------------------------------------------- /// Examine a list of Decls to find the function $__lldb_expr and transform /// its code /// - /// @param[in] D + /// \param[in] D /// The list of Decls to search. These may contain LinkageSpecDecls, /// which need to be searched recursively. That job falls to /// TransformTopLevelDecl. - //---------------------------------------------------------------------- bool HandleTopLevelDecl(clang::DeclGroupRef D) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void HandleTranslationUnit(clang::ASTContext &Ctx) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void HandleTagDeclDefinition(clang::TagDecl *D) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void CompleteTentativeDefinition(clang::VarDecl *D) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void HandleVTable(clang::CXXRecordDecl *RD) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void PrintStats() override; - //---------------------------------------------------------------------- /// Set the Sema object to use when performing transforms, and pass it on /// - /// @param[in] S + /// \param[in] S /// The Sema to use. Because Sema isn't externally visible, this class /// casts it to an Action for actual use. - //---------------------------------------------------------------------- void InitializeSema(clang::Sema &S) override; - //---------------------------------------------------------------------- /// Reset the Sema to NULL now that transformations are done - //---------------------------------------------------------------------- void ForgetSema() override; - //---------------------------------------------------------------------- /// The parse has succeeded, so record its persistent decls - //---------------------------------------------------------------------- void CommitPersistentDecls(); private: - //---------------------------------------------------------------------- /// Hunt the given Decl for FunctionDecls named $__lldb_expr, recursing as /// necessary through LinkageSpecDecls, and calling SynthesizeResult on /// anything that was found /// - /// @param[in] D + /// \param[in] D /// The Decl to hunt. - //---------------------------------------------------------------------- void TransformTopLevelDecl(clang::Decl *D); - //---------------------------------------------------------------------- /// Process an Objective-C method and produce the result variable and /// initialization /// - /// @param[in] MethodDecl + /// \param[in] MethodDecl /// The method to process. - //---------------------------------------------------------------------- bool SynthesizeObjCMethodResult(clang::ObjCMethodDecl *MethodDecl); - //---------------------------------------------------------------------- /// Process a function and produce the result variable and initialization /// - /// @param[in] FunDecl + /// \param[in] FunDecl /// The function to process. - //---------------------------------------------------------------------- bool SynthesizeFunctionResult(clang::FunctionDecl *FunDecl); - //---------------------------------------------------------------------- /// Process a function body and produce the result variable and /// initialization /// - /// @param[in] Body + /// \param[in] Body /// The body of the function. /// - /// @param[in] DC + /// \param[in] DC /// The DeclContext of the function, into which the result variable /// is inserted. - //---------------------------------------------------------------------- bool SynthesizeBodyResult(clang::CompoundStmt *Body, clang::DeclContext *DC); - //---------------------------------------------------------------------- /// Given a DeclContext for a function or method, find all types declared in /// the context and record any persistent types found. /// - /// @param[in] FunDeclCtx + /// \param[in] FunDeclCtx /// The context for the function to process. - //---------------------------------------------------------------------- void RecordPersistentTypes(clang::DeclContext *FunDeclCtx); - //---------------------------------------------------------------------- /// Given a TypeDecl, if it declares a type whose name starts with a dollar /// sign, register it as a pointer type in the target's scratch /// AST context. /// - /// @param[in] Body + /// \param[in] Body /// The body of the function. - //---------------------------------------------------------------------- void MaybeRecordPersistentType(clang::TypeDecl *D); - //---------------------------------------------------------------------- /// Given a NamedDecl, register it as a pointer type in the target's scratch /// AST context. /// - /// @param[in] Body + /// \param[in] Body /// The body of the function. - //---------------------------------------------------------------------- void RecordPersistentDecl(clang::NamedDecl *D); clang::ASTContext
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.cpp index 2faeecd..190eaca 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.cpp
@@ -1,9 +1,8 @@ //===-- ASTStructExtractor.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,9 +29,9 @@ ASTStructExtractor::ASTStructExtractor(ASTConsumer *passthrough, const char *struct_name, ClangFunctionCaller &function) - : m_ast_context(NULL), m_passthrough(passthrough), m_passthrough_sema(NULL), - m_sema(NULL), m_action(NULL), m_function(function), - m_struct_name(struct_name) { + : m_ast_context(nullptr), m_passthrough(passthrough), + m_passthrough_sema(nullptr), m_sema(nullptr), m_action(nullptr), + m_function(function), m_struct_name(struct_name) { if (!m_passthrough) return; @@ -58,7 +57,7 @@ if (!body_compound_stmt) return; // do we have to handle this? - RecordDecl *struct_decl = NULL; + RecordDecl *struct_decl = nullptr; StringRef desired_name(m_struct_name); @@ -178,8 +177,8 @@ } void ASTStructExtractor::ForgetSema() { - m_sema = NULL; - m_action = NULL; + m_sema = nullptr; + m_action = nullptr; if (m_passthrough_sema) m_passthrough_sema->ForgetSema();
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.h index 65f4b00..7aef2e2 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTStructExtractor.h
@@ -1,9 +1,8 @@ //===-- ASTStructExtractor.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,8 +17,7 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class ASTStructExtractor ASTStructExtractor.h +/// \class ASTStructExtractor ASTStructExtractor.h /// "lldb/Expression/ASTStructExtractor.h" Extracts and describes the argument /// structure for a wrapped function. /// @@ -33,112 +31,85 @@ /// The definition of this struct is itself in the body of the wrapper /// function, so Clang does the structure layout itself. ASTStructExtractor /// reads through the AST for the wrapper function and finds the struct. -//---------------------------------------------------------------------- class ASTStructExtractor : public clang::SemaConsumer { public: - //---------------------------------------------------------------------- /// Constructor /// - /// @param[in] passthrough + /// \param[in] passthrough /// Since the ASTs must typically go through to the Clang code generator /// in order to produce LLVM IR, this SemaConsumer must allow them to /// pass to the next step in the chain after processing. Passthrough is /// the next ASTConsumer, or NULL if none is required. /// - /// @param[in] struct_name + /// \param[in] struct_name /// The name of the structure to extract from the wrapper function. /// - /// @param[in] function + /// \param[in] function /// The caller object whose members should be populated with information /// about the argument struct. ClangFunctionCaller friends /// ASTStructExtractor /// for this purpose. - //---------------------------------------------------------------------- ASTStructExtractor(clang::ASTConsumer *passthrough, const char *struct_name, ClangFunctionCaller &function); - //---------------------------------------------------------------------- /// Destructor - //---------------------------------------------------------------------- ~ASTStructExtractor() override; - //---------------------------------------------------------------------- /// Link this consumer with a particular AST context /// - /// @param[in] Context + /// \param[in] Context /// This AST context will be used for types and identifiers, and also /// forwarded to the passthrough consumer, if one exists. - //---------------------------------------------------------------------- void Initialize(clang::ASTContext &Context) override; - //---------------------------------------------------------------------- /// Examine a list of Decls to find the function $__lldb_expr and transform /// its code /// - /// @param[in] D + /// \param[in] D /// The list of Decls to search. These may contain LinkageSpecDecls, /// which need to be searched recursively. That job falls to /// TransformTopLevelDecl. - //---------------------------------------------------------------------- bool HandleTopLevelDecl(clang::DeclGroupRef D) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void HandleTranslationUnit(clang::ASTContext &Ctx) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void HandleTagDeclDefinition(clang::TagDecl *D) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void CompleteTentativeDefinition(clang::VarDecl *D) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void HandleVTable(clang::CXXRecordDecl *RD) override; - //---------------------------------------------------------------------- /// Passthrough stub - //---------------------------------------------------------------------- void PrintStats() override; - //---------------------------------------------------------------------- /// Set the Sema object to use when performing transforms, and pass it on /// - /// @param[in] S + /// \param[in] S /// The Sema to use. Because Sema isn't externally visible, this class /// casts it to an Action for actual use. - //---------------------------------------------------------------------- void InitializeSema(clang::Sema &S) override; - //---------------------------------------------------------------------- /// Reset the Sema to NULL now that transformations are done - //---------------------------------------------------------------------- void ForgetSema() override; private: - //---------------------------------------------------------------------- /// Hunt the given FunctionDecl for the argument struct and place /// information about it into m_function /// - /// @param[in] F + /// \param[in] F /// The FunctionDecl to hunt. - //---------------------------------------------------------------------- void ExtractFromFunctionDecl(clang::FunctionDecl *F); - //---------------------------------------------------------------------- /// Hunt the given Decl for FunctionDecls named the same as the wrapper /// function name, recursing as necessary through LinkageSpecDecls, and /// calling ExtractFromFunctionDecl on anything that was found /// - /// @param[in] D + /// \param[in] D /// The Decl to hunt. - //---------------------------------------------------------------------- void ExtractFromTopLevelDecl(clang::Decl *D); clang::ASTContext
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp new file mode 100644 index 0000000..bbdf4e3 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp
@@ -0,0 +1,26 @@ +//===-- ASTUtils.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 "ASTUtils.h" + +lldb_private::ExternalASTSourceWrapper::~ExternalASTSourceWrapper() {} + +void lldb_private::ExternalASTSourceWrapper::PrintStats() { + m_Source->PrintStats(); +} + +lldb_private::ASTConsumerForwarder::~ASTConsumerForwarder() {} + +void lldb_private::ASTConsumerForwarder::PrintStats() { m_c->PrintStats(); } + +lldb_private::SemaSourceWithPriorities::~SemaSourceWithPriorities() {} + +void lldb_private::SemaSourceWithPriorities::PrintStats() { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->PrintStats(); +}
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h new file mode 100644 index 0000000..d429e8c --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h
@@ -0,0 +1,579 @@ +//===-- ASTUtils.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 liblldb_ASTUtils_h_ +#define liblldb_ASTUtils_h_ + +#include "clang/Sema/Lookup.h" +#include "clang/Sema/MultiplexExternalSemaSource.h" +#include "clang/Sema/Sema.h" +#include "clang/Sema/SemaConsumer.h" + +namespace lldb_private { + +/// Wraps an ExternalASTSource into an ExternalSemaSource. Doesn't take +/// ownership of the provided source. +class ExternalASTSourceWrapper : public clang::ExternalSemaSource { + ExternalASTSource *m_Source; + +public: + ExternalASTSourceWrapper(ExternalASTSource *Source) : m_Source(Source) { + assert(m_Source && "Can't wrap nullptr ExternalASTSource"); + } + + ~ExternalASTSourceWrapper() override; + + clang::Decl *GetExternalDecl(uint32_t ID) override { + return m_Source->GetExternalDecl(ID); + } + + clang::Selector GetExternalSelector(uint32_t ID) override { + return m_Source->GetExternalSelector(ID); + } + + uint32_t GetNumExternalSelectors() override { + return m_Source->GetNumExternalSelectors(); + } + + clang::Stmt *GetExternalDeclStmt(uint64_t Offset) override { + return m_Source->GetExternalDeclStmt(Offset); + } + + clang::CXXCtorInitializer ** + GetExternalCXXCtorInitializers(uint64_t Offset) override { + return m_Source->GetExternalCXXCtorInitializers(Offset); + } + + clang::CXXBaseSpecifier * + GetExternalCXXBaseSpecifiers(uint64_t Offset) override { + return m_Source->GetExternalCXXBaseSpecifiers(Offset); + } + + void updateOutOfDateIdentifier(clang::IdentifierInfo &II) override { + m_Source->updateOutOfDateIdentifier(II); + } + + bool FindExternalVisibleDeclsByName(const clang::DeclContext *DC, + clang::DeclarationName Name) override { + return m_Source->FindExternalVisibleDeclsByName(DC, Name); + } + + void completeVisibleDeclsMap(const clang::DeclContext *DC) override { + m_Source->completeVisibleDeclsMap(DC); + } + + clang::Module *getModule(unsigned ID) override { + return m_Source->getModule(ID); + } + + llvm::Optional<ASTSourceDescriptor> + getSourceDescriptor(unsigned ID) override { + return m_Source->getSourceDescriptor(ID); + } + + ExtKind hasExternalDefinitions(const clang::Decl *D) override { + return m_Source->hasExternalDefinitions(D); + } + + void FindExternalLexicalDecls( + const clang::DeclContext *DC, + llvm::function_ref<bool(clang::Decl::Kind)> IsKindWeWant, + llvm::SmallVectorImpl<clang::Decl *> &Result) override { + m_Source->FindExternalLexicalDecls(DC, IsKindWeWant, Result); + } + + void + FindFileRegionDecls(clang::FileID File, unsigned Offset, unsigned Length, + llvm::SmallVectorImpl<clang::Decl *> &Decls) override { + m_Source->FindFileRegionDecls(File, Offset, Length, Decls); + } + + void CompleteRedeclChain(const clang::Decl *D) override { + m_Source->CompleteRedeclChain(D); + } + + void CompleteType(clang::TagDecl *Tag) override { + m_Source->CompleteType(Tag); + } + + void CompleteType(clang::ObjCInterfaceDecl *Class) override { + m_Source->CompleteType(Class); + } + + void ReadComments() override { m_Source->ReadComments(); } + + void StartedDeserializing() override { m_Source->StartedDeserializing(); } + + void FinishedDeserializing() override { m_Source->FinishedDeserializing(); } + + void StartTranslationUnit(clang::ASTConsumer *Consumer) override { + m_Source->StartTranslationUnit(Consumer); + } + + void PrintStats() override; + + bool layoutRecordType( + const clang::RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, + llvm::DenseMap<const clang::FieldDecl *, uint64_t> &FieldOffsets, + llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> + &BaseOffsets, + llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> + &VirtualBaseOffsets) override { + return m_Source->layoutRecordType(Record, Size, Alignment, FieldOffsets, + BaseOffsets, VirtualBaseOffsets); + } +}; + +/// Wraps an ASTConsumer into an SemaConsumer. Doesn't take ownership of the +/// provided consumer. If the provided ASTConsumer is also a SemaConsumer, +/// the wrapper will also forward SemaConsumer functions. +class ASTConsumerForwarder : public clang::SemaConsumer { + clang::ASTConsumer *m_c; + clang::SemaConsumer *m_sc; + +public: + ASTConsumerForwarder(clang::ASTConsumer *c) : m_c(c) { + m_sc = llvm::dyn_cast<clang::SemaConsumer>(m_c); + } + + ~ASTConsumerForwarder() override; + + void Initialize(clang::ASTContext &Context) override { + m_c->Initialize(Context); + } + + bool HandleTopLevelDecl(clang::DeclGroupRef D) override { + return m_c->HandleTopLevelDecl(D); + } + + void HandleInlineFunctionDefinition(clang::FunctionDecl *D) override { + m_c->HandleInlineFunctionDefinition(D); + } + + void HandleInterestingDecl(clang::DeclGroupRef D) override { + m_c->HandleInterestingDecl(D); + } + + void HandleTranslationUnit(clang::ASTContext &Ctx) override { + m_c->HandleTranslationUnit(Ctx); + } + + void HandleTagDeclDefinition(clang::TagDecl *D) override { + m_c->HandleTagDeclDefinition(D); + } + + void HandleTagDeclRequiredDefinition(const clang::TagDecl *D) override { + m_c->HandleTagDeclRequiredDefinition(D); + } + + void HandleCXXImplicitFunctionInstantiation(clang::FunctionDecl *D) override { + m_c->HandleCXXImplicitFunctionInstantiation(D); + } + + void HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef D) override { + m_c->HandleTopLevelDeclInObjCContainer(D); + } + + void HandleImplicitImportDecl(clang::ImportDecl *D) override { + m_c->HandleImplicitImportDecl(D); + } + + void CompleteTentativeDefinition(clang::VarDecl *D) override { + m_c->CompleteTentativeDefinition(D); + } + + void AssignInheritanceModel(clang::CXXRecordDecl *RD) override { + m_c->AssignInheritanceModel(RD); + } + + void HandleCXXStaticMemberVarInstantiation(clang::VarDecl *D) override { + m_c->HandleCXXStaticMemberVarInstantiation(D); + } + + void HandleVTable(clang::CXXRecordDecl *RD) override { + m_c->HandleVTable(RD); + } + + clang::ASTMutationListener *GetASTMutationListener() override { + return m_c->GetASTMutationListener(); + } + + clang::ASTDeserializationListener *GetASTDeserializationListener() override { + return m_c->GetASTDeserializationListener(); + } + + void PrintStats() override; + + void InitializeSema(clang::Sema &S) override { + if (m_sc) + m_sc->InitializeSema(S); + } + + /// Inform the semantic consumer that Sema is no longer available. + void ForgetSema() override { + if (m_sc) + m_sc->ForgetSema(); + } + + bool shouldSkipFunctionBody(clang::Decl *D) override { + return m_c->shouldSkipFunctionBody(D); + } +}; + +/// A ExternalSemaSource multiplexer that prioritizes its sources. +/// +/// This ExternalSemaSource will forward all requests to its attached sources. +/// However, unlike a normal multiplexer it will not forward a request to all +/// sources, but instead give priority to certain sources. If a source with a +/// higher priority can fulfill a request, all sources with a lower priority +/// will not receive the request. +/// +/// This class is mostly use to multiplex between sources of different +/// 'quality', e.g. a C++ modules and debug information. The C++ module will +/// provide more accurate replies to the requests, but might not be able to +/// answer all requests. The debug information will be used as a fallback then +/// to provide information that is not in the C++ module. +class SemaSourceWithPriorities : public clang::ExternalSemaSource { + +private: + /// The sources ordered in decreasing priority. + llvm::SmallVector<clang::ExternalSemaSource *, 2> Sources; + +public: + /// Construct a SemaSourceWithPriorities with a 'high quality' source that + /// has the higher priority and a 'low quality' source that will be used + /// as a fallback. + SemaSourceWithPriorities(clang::ExternalSemaSource &high_quality_source, + clang::ExternalSemaSource &low_quality_source) { + Sources.push_back(&high_quality_source); + Sources.push_back(&low_quality_source); + } + + ~SemaSourceWithPriorities() override; + + void addSource(clang::ExternalSemaSource &source) { + Sources.push_back(&source); + } + + //===--------------------------------------------------------------------===// + // ExternalASTSource. + //===--------------------------------------------------------------------===// + + clang::Decl *GetExternalDecl(uint32_t ID) override { + for (size_t i = 0; i < Sources.size(); ++i) + if (clang::Decl *Result = Sources[i]->GetExternalDecl(ID)) + return Result; + return nullptr; + } + + void CompleteRedeclChain(const clang::Decl *D) override { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->CompleteRedeclChain(D); + } + + clang::Selector GetExternalSelector(uint32_t ID) override { + clang::Selector Sel; + for (size_t i = 0; i < Sources.size(); ++i) { + Sel = Sources[i]->GetExternalSelector(ID); + if (!Sel.isNull()) + return Sel; + } + return Sel; + } + + uint32_t GetNumExternalSelectors() override { + for (size_t i = 0; i < Sources.size(); ++i) + if (uint32_t total = Sources[i]->GetNumExternalSelectors()) + return total; + return 0; + } + + clang::Stmt *GetExternalDeclStmt(uint64_t Offset) override { + for (size_t i = 0; i < Sources.size(); ++i) + if (clang::Stmt *Result = Sources[i]->GetExternalDeclStmt(Offset)) + return Result; + return nullptr; + } + + clang::CXXBaseSpecifier * + GetExternalCXXBaseSpecifiers(uint64_t Offset) override { + for (size_t i = 0; i < Sources.size(); ++i) + if (clang::CXXBaseSpecifier *R = + Sources[i]->GetExternalCXXBaseSpecifiers(Offset)) + return R; + return nullptr; + } + + clang::CXXCtorInitializer ** + GetExternalCXXCtorInitializers(uint64_t Offset) override { + for (auto *S : Sources) + if (auto *R = S->GetExternalCXXCtorInitializers(Offset)) + return R; + return nullptr; + } + + ExtKind hasExternalDefinitions(const clang::Decl *D) override { + for (const auto &S : Sources) + if (auto EK = S->hasExternalDefinitions(D)) + if (EK != EK_ReplyHazy) + return EK; + return EK_ReplyHazy; + } + + bool FindExternalVisibleDeclsByName(const clang::DeclContext *DC, + clang::DeclarationName Name) override { + for (size_t i = 0; i < Sources.size(); ++i) + if (Sources[i]->FindExternalVisibleDeclsByName(DC, Name)) + return true; + return false; + } + + void completeVisibleDeclsMap(const clang::DeclContext *DC) override { + // FIXME: Only one source should be able to complete the decls map. + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->completeVisibleDeclsMap(DC); + } + + void FindExternalLexicalDecls( + const clang::DeclContext *DC, + llvm::function_ref<bool(clang::Decl::Kind)> IsKindWeWant, + llvm::SmallVectorImpl<clang::Decl *> &Result) override { + for (size_t i = 0; i < Sources.size(); ++i) { + Sources[i]->FindExternalLexicalDecls(DC, IsKindWeWant, Result); + if (!Result.empty()) + return; + } + } + + void + FindFileRegionDecls(clang::FileID File, unsigned Offset, unsigned Length, + llvm::SmallVectorImpl<clang::Decl *> &Decls) override { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->FindFileRegionDecls(File, Offset, Length, Decls); + } + + void CompleteType(clang::TagDecl *Tag) override { + while (!Tag->isCompleteDefinition()) + for (size_t i = 0; i < Sources.size(); ++i) { + // FIXME: We are technically supposed to loop here too until + // Tag->isCompleteDefinition() is true, but if our low quality source + // is failing to complete the tag this code will deadlock. + Sources[i]->CompleteType(Tag); + if (Tag->isCompleteDefinition()) + break; + } + } + + void CompleteType(clang::ObjCInterfaceDecl *Class) override { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->CompleteType(Class); + } + + void ReadComments() override { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->ReadComments(); + } + + void StartedDeserializing() override { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->StartedDeserializing(); + } + + void FinishedDeserializing() override { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->FinishedDeserializing(); + } + + void StartTranslationUnit(clang::ASTConsumer *Consumer) override { + for (size_t i = 0; i < Sources.size(); ++i) + Sources[i]->StartTranslationUnit(Consumer); + } + + void PrintStats() override; + + clang::Module *getModule(unsigned ID) override { + for (size_t i = 0; i < Sources.size(); ++i) + if (auto M = Sources[i]->getModule(ID)) + return M; + return nullptr; + } + + bool DeclIsFromPCHWithObjectFile(const clang::Decl *D) override { + for (auto *S : Sources) + if (S->DeclIsFromPCHWithObjectFile(D)) + return true; + return false; + } + + bool layoutRecordType( + const clang::RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, + llvm::DenseMap<const clang::FieldDecl *, uint64_t> &FieldOffsets, + llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> + &BaseOffsets, + llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> + &VirtualBaseOffsets) override { + for (size_t i = 0; i < Sources.size(); ++i) + if (Sources[i]->layoutRecordType(Record, Size, Alignment, FieldOffsets, + BaseOffsets, VirtualBaseOffsets)) + return true; + return false; + } + + void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override { + for (auto &Source : Sources) + Source->getMemoryBufferSizes(sizes); + } + + //===--------------------------------------------------------------------===// + // ExternalSemaSource. + //===--------------------------------------------------------------------===// + + void InitializeSema(clang::Sema &S) override { + for (auto &Source : Sources) + Source->InitializeSema(S); + } + + void ForgetSema() override { + for (auto &Source : Sources) + Source->ForgetSema(); + } + + void ReadMethodPool(clang::Selector Sel) override { + for (auto &Source : Sources) + Source->ReadMethodPool(Sel); + } + + void updateOutOfDateSelector(clang::Selector Sel) override { + for (auto &Source : Sources) + Source->updateOutOfDateSelector(Sel); + } + + void ReadKnownNamespaces( + llvm::SmallVectorImpl<clang::NamespaceDecl *> &Namespaces) override { + for (auto &Source : Sources) + Source->ReadKnownNamespaces(Namespaces); + } + + void ReadUndefinedButUsed( + llvm::MapVector<clang::NamedDecl *, clang::SourceLocation> &Undefined) + override { + for (auto &Source : Sources) + Source->ReadUndefinedButUsed(Undefined); + } + + void ReadMismatchingDeleteExpressions( + llvm::MapVector<clang::FieldDecl *, + llvm::SmallVector<std::pair<clang::SourceLocation, bool>, + 4>> &Exprs) override { + for (auto &Source : Sources) + Source->ReadMismatchingDeleteExpressions(Exprs); + } + + bool LookupUnqualified(clang::LookupResult &R, clang::Scope *S) override { + for (auto &Source : Sources) { + Source->LookupUnqualified(R, S); + if (!R.empty()) + break; + } + + return !R.empty(); + } + + void ReadTentativeDefinitions( + llvm::SmallVectorImpl<clang::VarDecl *> &Defs) override { + for (auto &Source : Sources) + Source->ReadTentativeDefinitions(Defs); + } + + void ReadUnusedFileScopedDecls( + llvm::SmallVectorImpl<const clang::DeclaratorDecl *> &Decls) override { + for (auto &Source : Sources) + Source->ReadUnusedFileScopedDecls(Decls); + } + + void ReadDelegatingConstructors( + llvm::SmallVectorImpl<clang::CXXConstructorDecl *> &Decls) override { + for (auto &Source : Sources) + Source->ReadDelegatingConstructors(Decls); + } + + void ReadExtVectorDecls( + llvm::SmallVectorImpl<clang::TypedefNameDecl *> &Decls) override { + for (auto &Source : Sources) + Source->ReadExtVectorDecls(Decls); + } + + void ReadUnusedLocalTypedefNameCandidates( + llvm::SmallSetVector<const clang::TypedefNameDecl *, 4> &Decls) override { + for (auto &Source : Sources) + Source->ReadUnusedLocalTypedefNameCandidates(Decls); + } + + void ReadReferencedSelectors( + llvm::SmallVectorImpl<std::pair<clang::Selector, clang::SourceLocation>> + &Sels) override { + for (auto &Source : Sources) + Source->ReadReferencedSelectors(Sels); + } + + void ReadWeakUndeclaredIdentifiers( + llvm::SmallVectorImpl<std::pair<clang::IdentifierInfo *, clang::WeakInfo>> + &WI) override { + for (auto &Source : Sources) + Source->ReadWeakUndeclaredIdentifiers(WI); + } + + void ReadUsedVTables( + llvm::SmallVectorImpl<clang::ExternalVTableUse> &VTables) override { + for (auto &Source : Sources) + Source->ReadUsedVTables(VTables); + } + + void ReadPendingInstantiations( + llvm::SmallVectorImpl< + std::pair<clang::ValueDecl *, clang::SourceLocation>> &Pending) + override { + for (auto &Source : Sources) + Source->ReadPendingInstantiations(Pending); + } + + void ReadLateParsedTemplates( + llvm::MapVector<const clang::FunctionDecl *, + std::unique_ptr<clang::LateParsedTemplate>> &LPTMap) + override { + for (auto &Source : Sources) + Source->ReadLateParsedTemplates(LPTMap); + } + + clang::TypoCorrection + CorrectTypo(const clang::DeclarationNameInfo &Typo, int LookupKind, + clang::Scope *S, clang::CXXScopeSpec *SS, + clang::CorrectionCandidateCallback &CCC, + clang::DeclContext *MemberContext, bool EnteringContext, + const clang::ObjCObjectPointerType *OPT) override { + for (auto &Source : Sources) { + if (clang::TypoCorrection C = + Source->CorrectTypo(Typo, LookupKind, S, SS, CCC, + MemberContext, EnteringContext, OPT)) + return C; + } + return clang::TypoCorrection(); + } + + bool MaybeDiagnoseMissingCompleteType(clang::SourceLocation Loc, + clang::QualType T) override { + for (auto &Source : Sources) { + if (Source->MaybeDiagnoseMissingCompleteType(Loc, T)) + return true; + } + return false; + } +}; + +} // namespace lldb_private +#endif // liblldb_ASTUtils_h_
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/CMakeLists.txt index ec4f6d5..950dae6 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/CMakeLists.txt
@@ -6,9 +6,11 @@ ASTDumper.cpp ASTResultSynthesizer.cpp ASTStructExtractor.cpp + ASTUtils.cpp ClangASTSource.cpp ClangExpressionDeclMap.cpp ClangExpressionParser.cpp + ClangExpressionSourceCode.cpp ClangExpressionVariable.cpp ClangFunctionCaller.cpp ClangHost.cpp @@ -17,6 +19,7 @@ ClangUserExpression.cpp ClangUtilityFunction.cpp IRForTarget.cpp + IRDynamicChecks.cpp DEPENDS ${tablegen_deps} @@ -41,6 +44,7 @@ lldbTarget lldbUtility lldbPluginCPlusPlusLanguage + lldbPluginCPPRuntime LINK_COMPONENTS Core ExecutionEngine
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp index 84771e5..c5778f8 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp
@@ -1,9 +1,8 @@ //===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,21 +20,21 @@ #include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/SymbolVendor.h" #include "lldb/Symbol/TaggedASTType.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Utility/Log.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecordLayout.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + +#include <memory> #include <vector> using namespace clang; using namespace lldb_private; -//------------------------------------------------------------------ // Scoped class that will remove an active lexical decl from the set when it // goes out of scope. -//------------------------------------------------------------------ namespace { class ScopedLexicalDeclEraser { public: @@ -53,7 +52,7 @@ ClangASTSource::ClangASTSource(const lldb::TargetSP &target) : m_import_in_progress(false), m_lookups_enabled(false), m_target(target), - m_ast_context(NULL), m_active_lexical_decls(), m_active_lookups() { + m_ast_context(nullptr), m_active_lexical_decls(), m_active_lookups() { if (!target->GetUseModernTypeLookup()) { m_ast_importer_sp = m_target->GetClangASTImporter(); } @@ -92,7 +91,7 @@ if (!process) break; - ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime()); + ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); if (!language_runtime) break; @@ -103,7 +102,7 @@ break; sources.push_back(runtime_decl_vendor->GetImporterSource()); - } while (0); + } while (false); do { DeclVendor *modules_decl_vendor = @@ -113,7 +112,7 @@ break; sources.push_back(modules_decl_vendor->GetImporterSource()); - } while (0); + } while (false); if (!is_shared_context) { // Update the scratch AST context's merger to reflect any new sources we @@ -127,7 +126,9 @@ sources.push_back({*scratch_ast_context->getASTContext(), *scratch_ast_context->getFileManager(), scratch_ast_context->GetOriginMap()}); - } while (0); + } + while (false) + ; m_merger_up = llvm::make_unique<clang::ExternalASTMerger>(target, sources); @@ -443,8 +444,8 @@ return; } - Decl *original_decl = NULL; - ASTContext *original_ctx = NULL; + Decl *original_decl = nullptr; + ASTContext *original_ctx = nullptr; if (m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl, &original_ctx)) { @@ -477,12 +478,12 @@ lldb::ProcessSP process(m_target->GetProcessSP()); if (!process) - return NULL; + return nullptr; - ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime()); + ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); if (!language_runtime) - return NULL; + return nullptr; ConstString class_name(interface_decl->getNameAsString().c_str()); @@ -490,7 +491,7 @@ language_runtime->LookupInCompleteClassCache(class_name)); if (!complete_type_sp) - return NULL; + return nullptr; TypeFromUser complete_type = TypeFromUser(complete_type_sp->GetFullCompilerType()); @@ -498,7 +499,7 @@ complete_type.GetOpaqueQualType(); if (!complete_opaque_type) - return NULL; + return nullptr; const clang::Type *complete_clang_type = QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr(); @@ -506,7 +507,7 @@ dyn_cast<ObjCInterfaceType>(complete_clang_type); if (!complete_interface_type) - return NULL; + return nullptr; ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl()); @@ -571,8 +572,8 @@ current_id, static_cast<const void *>(m_ast_context)); } - Decl *original_decl = NULL; - ASTContext *original_ctx = NULL; + Decl *original_decl = nullptr; + ASTContext *original_ctx = nullptr; if (!m_ast_importer_sp->ResolveDeclOrigin(context_decl, &original_decl, &original_ctx)) @@ -611,10 +612,15 @@ if (!original_decl_context) return; + // Indicates whether we skipped any Decls of the original DeclContext. + bool SkippedDecls = false; for (TagDecl::decl_iterator iter = original_decl_context->decls_begin(); iter != original_decl_context->decls_end(); ++iter) { Decl *decl = *iter; + // The predicate function returns true if the passed declaration kind is + // the one we are looking for. + // See clang::ExternalASTSource::FindExternalLexicalDecls() if (predicate(decl->getKind())) { if (log) { ASTDumper ast_dumper(decl); @@ -639,21 +645,22 @@ m_ast_importer_sp->RequireCompleteType(copied_field_type); } - - DeclContext *decl_context_non_const = - const_cast<DeclContext *>(decl_context); - - if (copied_decl->getDeclContext() != decl_context) { - if (copied_decl->getDeclContext()->containsDecl(copied_decl)) - copied_decl->getDeclContext()->removeDecl(copied_decl); - copied_decl->setDeclContext(decl_context_non_const); - } - - if (!decl_context_non_const->containsDecl(copied_decl)) - decl_context_non_const->addDeclInternal(copied_decl); + } else { + SkippedDecls = true; } } + // CopyDecl may build a lookup table which may set up ExternalLexicalStorage + // to false. However, since we skipped some of the external Decls we must + // set it back! + if (SkippedDecls) { + decl_context->setHasExternalLexicalStorage(true); + // This sets HasLazyExternalLexicalLookups to true. By setting this bit we + // ensure that the lookup table is rebuilt, which means the external source + // is consulted again when a clang::DeclContext::lookup is called. + const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable(); + } + return; } @@ -708,7 +715,7 @@ return; // otherwise we may need to fall back } - context.m_namespace_map.reset(new ClangASTImporter::NamespaceMap); + context.m_namespace_map = std::make_shared<ClangASTImporter::NamespaceMap>(); if (const NamespaceDecl *namespace_context = dyn_cast<NamespaceDecl>(context.m_decl_context)) { @@ -763,6 +770,10 @@ } } +clang::Sema *ClangASTSource::getSema() { + return ClangASTContext::GetASTContext(m_ast_context)->getSema(); +} + bool ClangASTSource::IgnoreName(const ConstString name, bool ignore_all_dollar_names) { static const ConstString id_name("id"); @@ -932,7 +943,7 @@ context.m_found.type = true; } } - } while (0); + } while (false); } if (!context.m_found.type) { @@ -946,7 +957,7 @@ break; ObjCLanguageRuntime *language_runtime( - process->GetObjCLanguageRuntime()); + ObjCLanguageRuntime::Get(*process)); if (!language_runtime) break; @@ -983,17 +994,17 @@ } context.AddNamedDecl(copied_named_decl); - } while (0); + } while (false); } - } while (0); + } while (false); } template <class D> class TaggedASTDecl { public: - TaggedASTDecl() : decl(NULL) {} + TaggedASTDecl() : decl(nullptr) {} TaggedASTDecl(D *_decl) : decl(_decl) {} - bool IsValid() const { return (decl != NULL); } + bool IsValid() const { return (decl != nullptr); } bool IsInvalid() const { return !IsValid(); } D *operator->() const { return decl; } D *decl; @@ -1026,7 +1037,7 @@ template <class D> DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) { DeclFromUser<> origin_decl; - source.ResolveDeclOrigin(this->decl, &origin_decl.decl, NULL); + source.ResolveDeclOrigin(this->decl, &origin_decl.decl, nullptr); if (origin_decl.IsInvalid()) return DeclFromUser<D>(); return DeclFromUser<D>(dyn_cast<D>(origin_decl.decl)); @@ -1156,8 +1167,8 @@ return; do { - Decl *original_decl = NULL; - ASTContext *original_ctx = NULL; + Decl *original_decl = nullptr; + ASTContext *original_ctx = nullptr; m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl, &original_ctx); @@ -1171,7 +1182,7 @@ if (FindObjCMethodDeclsWithOrigin(current_id, context, original_interface_decl, "at origin")) return; // found it, no need to look any further - } while (0); + } while (false); StreamString ss; @@ -1276,7 +1287,7 @@ if (*cursor == ' ' || *cursor == '(') sc_list.Append(candidate_sc); } - } while (0); + } while (false); if (sc_list.GetSize()) { // We found a good function symbol. Use that. @@ -1359,7 +1370,7 @@ "in debug info"); return; - } while (0); + } while (false); do { // Check the modules only if the debug information didn't have a complete @@ -1386,7 +1397,7 @@ current_id, context, interface_decl_from_modules, "in modules")) return; } - } while (0); + } while (false); do { // Check the runtime only if the debug information didn't have a complete @@ -1397,7 +1408,7 @@ if (!process) break; - ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime()); + ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); if (!language_runtime) break; @@ -1423,7 +1434,7 @@ FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl, "in runtime"); - } while (0); + } while (false); } static bool FindObjCPropertyAndIvarDeclsWithOrigin( @@ -1542,7 +1553,7 @@ complete_iface_decl); return; - } while (0); + } while (false); do { // Check the modules only if the debug information didn't have a complete @@ -1578,7 +1589,7 @@ if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, interface_decl_from_modules)) return; - } while (0); + } while (false); do { // Check the runtime only if the debug information didn't have a complete @@ -1589,7 +1600,7 @@ if (!process) return; - ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime()); + ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); if (!language_runtime) return; @@ -1623,7 +1634,7 @@ if (FindObjCPropertyAndIvarDeclsWithOrigin( current_id, context, *this, interface_decl_from_runtime)) return; - } while (0); + } while (false); } typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap; @@ -1836,7 +1847,7 @@ } void ClangASTSource::CompleteNamespaceMap( - ClangASTImporter::NamespaceMapSP &namespace_map, const ConstString &name, + ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name, ClangASTImporter::NamespaceMapSP &parent_map) const { static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; @@ -1966,7 +1977,14 @@ return QualType(); } - return merger.ImporterForOrigin(from_context).Import(type); + if (llvm::Expected<QualType> type_or_error = + merger.ImporterForOrigin(from_context).Import(type)) { + return *type_or_error; + } else { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + LLDB_LOG_ERROR(log, type_or_error.takeError(), "Couldn't import type: {0}"); + return QualType(); + } } clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) { @@ -1979,7 +1997,16 @@ return nullptr; } - return m_merger_up->ImporterForOrigin(from_context).Import(src_decl); + if (llvm::Expected<Decl *> decl_or_error = + m_merger_up->ImporterForOrigin(from_context).Import(src_decl)) { + return *decl_or_error; + } else { + Log *log = + lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + LLDB_LOG_ERROR(log, decl_or_error.takeError(), + "Couldn't import decl: {0}"); + return nullptr; + } } else { lldbassert(0 && "No mechanism for copying a decl!"); return nullptr; @@ -2045,12 +2072,12 @@ assert(type && "Type for variable must be valid!"); if (!type.IsValid()) - return NULL; + return nullptr; ClangASTContext *lldb_ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); if (!lldb_ast) - return NULL; + return nullptr; IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo(); @@ -2058,7 +2085,7 @@ clang::NamedDecl *Decl = VarDecl::Create( *ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(), - SourceLocation(), ii, ClangUtil::GetQualType(type), 0, SC_Static); + SourceLocation(), ii, ClangUtil::GetQualType(type), nullptr, SC_Static); m_decls.push_back(Decl); return Decl; @@ -2069,15 +2096,15 @@ assert(type && "Type for variable must be valid!"); if (!type.IsValid()) - return NULL; + return nullptr; if (m_function_types.count(type)) - return NULL; + return nullptr; ClangASTContext *lldb_ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); if (!lldb_ast) - return NULL; + return nullptr; m_function_types.insert(type); @@ -2106,8 +2133,8 @@ clang::FunctionDecl *func_decl = FunctionDecl::Create( *ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type, - NULL, SC_Extern, isInlineSpecified, hasWrittenPrototype, - isConstexprSpecified); + nullptr, SC_Extern, isInlineSpecified, hasWrittenPrototype, + isConstexprSpecified ? CSK_constexpr : CSK_unspecified); // We have to do more than just synthesize the FunctionDecl. We have to // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do @@ -2125,9 +2152,10 @@ for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) { QualType arg_qual_type(func_proto_type->getParamType(ArgIndex)); - parm_var_decls.push_back(ParmVarDecl::Create( - *ast, const_cast<DeclContext *>(context), SourceLocation(), - SourceLocation(), NULL, arg_qual_type, NULL, SC_Static, NULL)); + parm_var_decls.push_back( + ParmVarDecl::Create(*ast, const_cast<DeclContext *>(context), + SourceLocation(), SourceLocation(), nullptr, + arg_qual_type, nullptr, SC_Static, nullptr)); } func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls)); @@ -2148,7 +2176,7 @@ ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) { if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount( false, op_kind, func_proto_type->getNumParams())) - return NULL; + return nullptr; } m_decls.push_back(func_decl); @@ -2196,7 +2224,7 @@ return (NamedDecl *)interface_decl; } } - return NULL; + return nullptr; } void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) {
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h index a42422b..7a8bacf 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h
@@ -1,9 +1,8 @@ //===-- ClangASTSource.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,8 +22,7 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class ClangASTSource ClangASTSource.h "lldb/Expression/ClangASTSource.h" +/// \class ClangASTSource ClangASTSource.h "lldb/Expression/ClangASTSource.h" /// Provider for named objects defined in the debug info for Clang /// /// As Clang parses an expression, it may encounter names that are not defined @@ -32,37 +30,30 @@ /// knows the name it is looking for, but nothing else. The ExternalSemaSource /// class provides Decls (VarDecl, FunDecl, TypeDecl) to Clang for these /// names, consulting the ClangExpressionDeclMap to do the actual lookups. -//---------------------------------------------------------------------- class ClangASTSource : public ClangExternalASTSourceCommon, public ClangASTImporter::MapCompleter { public: - //------------------------------------------------------------------ /// Constructor /// /// Initializes class variables. /// - /// @param[in] target + /// \param[in] target /// A reference to the target containing debug information to use. - //------------------------------------------------------------------ ClangASTSource(const lldb::TargetSP &target); - //------------------------------------------------------------------ /// Destructor - //------------------------------------------------------------------ ~ClangASTSource() override; - //------------------------------------------------------------------ /// Interface stubs. - //------------------------------------------------------------------ - clang::Decl *GetExternalDecl(uint32_t) override { return NULL; } - clang::Stmt *GetExternalDeclStmt(uint64_t) override { return NULL; } + clang::Decl *GetExternalDecl(uint32_t) override { return nullptr; } + clang::Stmt *GetExternalDeclStmt(uint64_t) override { return nullptr; } clang::Selector GetExternalSelector(uint32_t) override { return clang::Selector(); } uint32_t GetNumExternalSelectors() override { return 0; } clang::CXXBaseSpecifier * GetExternalCXXBaseSpecifiers(uint64_t Offset) override { - return NULL; + return nullptr; } void MaterializeVisibleDecls(const clang::DeclContext *DC) { return; } @@ -74,7 +65,6 @@ // APIs for ExternalASTSource // - //------------------------------------------------------------------ /// Look up all Decls that match a particular name. Only handles /// Identifiers and DeclContexts that are either NamespaceDecls or /// TranslationUnitDecls. Calls SetExternalVisibleDeclsForName with the @@ -83,69 +73,64 @@ /// The work for this function is done by /// void FindExternalVisibleDecls (NameSearchContext &); /// - /// @param[in] DC + /// \param[in] DC /// The DeclContext to register the found Decls in. /// - /// @param[in] Name + /// \param[in] Name /// The name to find entries for. /// - /// @return + /// \return /// Whatever SetExternalVisibleDeclsForName returns. - //------------------------------------------------------------------ bool FindExternalVisibleDeclsByName(const clang::DeclContext *DC, clang::DeclarationName Name) override; - //------------------------------------------------------------------ /// Enumerate all Decls in a given lexical context. /// - /// @param[in] DC + /// \param[in] DC /// The DeclContext being searched. /// - /// @param[in] isKindWeWant + /// \param[in] isKindWeWant /// A callback function that returns true given the /// DeclKinds of desired Decls, and false otherwise. /// - /// @param[in] Decls + /// \param[in] Decls /// A vector that is filled in with matching Decls. - //------------------------------------------------------------------ void FindExternalLexicalDecls( const clang::DeclContext *DC, llvm::function_ref<bool(clang::Decl::Kind)> IsKindWeWant, llvm::SmallVectorImpl<clang::Decl *> &Decls) override; - //------------------------------------------------------------------ /// Specify the layout of the contents of a RecordDecl. /// - /// @param[in] Record + /// \param[in] Record /// The record (in the parser's AST context) that needs to be /// laid out. /// - /// @param[out] Size + /// \param[out] Size /// The total size of the record in bits. /// - /// @param[out] Alignment + /// \param[out] Alignment /// The alignment of the record in bits. /// - /// @param[in] FieldOffsets + /// \param[in] FieldOffsets /// A map that must be populated with pairs of the record's /// fields (in the parser's AST context) and their offsets /// (measured in bits). /// - /// @param[in] BaseOffsets + /// \param[in] BaseOffsets /// A map that must be populated with pairs of the record's /// C++ concrete base classes (in the parser's AST context, /// and only if the record is a CXXRecordDecl and has base /// classes) and their offsets (measured in bytes). /// - /// @param[in] VirtualBaseOffsets + /// \param[in] VirtualBaseOffsets /// A map that must be populated with pairs of the record's /// C++ virtual base classes (in the parser's AST context, /// and only if the record is a CXXRecordDecl and has base /// classes) and their offsets (measured in bytes). /// - /// @return + /// \return /// True <=> the layout is valid. - //----------------------------------------------------------------- bool layoutRecordType( const clang::RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, llvm::DenseMap<const clang::FieldDecl *, uint64_t> &FieldOffsets, @@ -154,52 +139,44 @@ llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &VirtualBaseOffsets) override; - //------------------------------------------------------------------ /// Complete a TagDecl. /// - /// @param[in] Tag + /// \param[in] Tag /// The Decl to be completed in place. - //------------------------------------------------------------------ void CompleteType(clang::TagDecl *Tag) override; - //------------------------------------------------------------------ /// Complete an ObjCInterfaceDecl. /// - /// @param[in] Class + /// \param[in] Class /// The Decl to be completed in place. - //------------------------------------------------------------------ void CompleteType(clang::ObjCInterfaceDecl *Class) override; - //------------------------------------------------------------------ /// Called on entering a translation unit. Tells Clang by calling /// setHasExternalVisibleStorage() and setHasExternalLexicalStorage() that /// this object has something to say about undefined names. /// - /// @param[in] ASTConsumer + /// \param[in] ASTConsumer /// Unused. - //------------------------------------------------------------------ void StartTranslationUnit(clang::ASTConsumer *Consumer) override; // // APIs for NamespaceMapCompleter // - //------------------------------------------------------------------ /// Look up the modules containing a given namespace and put the appropriate /// entries in the namespace map. /// - /// @param[in] namespace_map + /// \param[in] namespace_map /// The map to be completed. /// - /// @param[in] name + /// \param[in] name /// The name of the namespace to be found. /// - /// @param[in] parent_map + /// \param[in] parent_map /// The map for the namespace's parent namespace, if there is /// one. - //------------------------------------------------------------------ void CompleteNamespaceMap( - ClangASTImporter::NamespaceMapSP &namespace_map, const ConstString &name, + ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name, ClangASTImporter::NamespaceMapSP &parent_map) const override; // @@ -210,14 +187,14 @@ AddNamespace(NameSearchContext &context, ClangASTImporter::NamespaceMapSP &namespace_decls); - //------------------------------------------------------------------ /// The worker function for FindExternalVisibleDeclsByName. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when filing results. - //------------------------------------------------------------------ virtual void FindExternalVisibleDecls(NameSearchContext &context); + clang::Sema *getSema(); + void SetImportInProgress(bool import_in_progress) { m_import_in_progress = import_in_progress; } @@ -228,13 +205,11 @@ } bool GetLookupsEnabled() { return m_lookups_enabled; } - //---------------------------------------------------------------------- - /// @class ClangASTSourceProxy ClangASTSource.h + /// \class ClangASTSourceProxy ClangASTSource.h /// "lldb/Expression/ClangASTSource.h" Proxy for ClangASTSource /// /// Clang AST contexts like to own their AST sources, so this is a state- /// free proxy object. - //---------------------------------------------------------------------- class ClangASTSourceProxy : public ClangExternalASTSourceCommon { public: ClangASTSourceProxy(ClangASTSource &original) : m_original(original) {} @@ -295,157 +270,135 @@ } protected: - //------------------------------------------------------------------ /// Look for the complete version of an Objective-C interface, and return it /// if found. /// - /// @param[in] interface_decl + /// \param[in] interface_decl /// An ObjCInterfaceDecl that may not be the complete one. /// - /// @return + /// \return /// NULL if the complete interface couldn't be found; /// the complete interface otherwise. - //------------------------------------------------------------------ clang::ObjCInterfaceDecl * GetCompleteObjCInterface(const clang::ObjCInterfaceDecl *interface_decl); - //------------------------------------------------------------------ /// Find all entities matching a given name in a given module, using a /// NameSearchContext to make Decls for them. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext that can construct Decls for this name. /// - /// @param[in] module + /// \param[in] module /// If non-NULL, the module to query. /// - /// @param[in] namespace_decl + /// \param[in] namespace_decl /// If valid and module is non-NULL, the parent namespace. /// - /// @param[in] current_id + /// \param[in] current_id /// The ID for the current FindExternalVisibleDecls invocation, /// for logging purposes. - //------------------------------------------------------------------ void FindExternalVisibleDecls(NameSearchContext &context, lldb::ModuleSP module, CompilerDeclContext &namespace_decl, unsigned int current_id); - //------------------------------------------------------------------ /// Find all Objective-C methods matching a given selector. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext that can construct Decls for this name. /// Its m_decl_name contains the selector and its m_decl_context /// is the containing object. - //------------------------------------------------------------------ void FindObjCMethodDecls(NameSearchContext &context); - //------------------------------------------------------------------ /// Find all Objective-C properties and ivars with a given name. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext that can construct Decls for this name. /// Its m_decl_name contains the name and its m_decl_context /// is the containing object. - //------------------------------------------------------------------ void FindObjCPropertyAndIvarDecls(NameSearchContext &context); - //------------------------------------------------------------------ /// A wrapper for ClangASTContext::CopyType that sets a flag that /// indicates that we should not respond to queries during import. /// - /// @param[in] dest_context + /// \param[in] dest_context /// The target AST context, typically the parser's AST context. /// - /// @param[in] source_context + /// \param[in] source_context /// The source AST context, typically the AST context of whatever /// symbol file the type was found in. /// - /// @param[in] src_type + /// \param[in] src_type /// The source type. /// - /// @return + /// \return /// The imported type. - //------------------------------------------------------------------ CompilerType GuardedCopyType(const CompilerType &src_type); public: - //------------------------------------------------------------------ /// Returns true if a name should be ignored by name lookup. /// - /// @param[in] name + /// \param[in] name /// The name to be considered. /// - /// @param[in] ignore_all_dollar_nmmes + /// \param[in] ignore_all_dollar_nmmes /// True if $-names of all sorts should be ignored. /// - /// @return + /// \return /// True if the name is one of a class of names that are ignored by /// global lookup for performance reasons. - //------------------------------------------------------------------ bool IgnoreName(const ConstString name, bool ignore_all_dollar_names); public: - //------------------------------------------------------------------ /// Copies a single Decl into the parser's AST context. /// - /// @param[in] src_decl + /// \param[in] src_decl /// The Decl to copy. /// - /// @return + /// \return /// A copy of the Decl in m_ast_context, or NULL if the copy failed. - //------------------------------------------------------------------ clang::Decl *CopyDecl(clang::Decl *src_decl); - //------------------------------------------------------------------ /// Copies a single Type to the target of the given ExternalASTMerger. /// - /// @param[in] src_context + /// \param[in] src_context /// The ASTContext containing the type. /// - /// @param[in] merger + /// \param[in] merger /// The merger to use. This isn't just *m_merger_up because it might be /// the persistent AST context's merger. /// - /// @param[in] type + /// \param[in] type /// The type to copy. /// - /// @return + /// \return /// A copy of the Type in the merger's target context. - //------------------------------------------------------------------ clang::QualType CopyTypeWithMerger(clang::ASTContext &src_context, clang::ExternalASTMerger &merger, clang::QualType type); - //------------------------------------------------------------------ /// Determined the origin of a single Decl, if it can be found. /// - /// @param[in] decl + /// \param[in] decl /// The Decl whose origin is to be found. /// - /// @param[out] original_decl + /// \param[out] original_decl /// A pointer whose target is filled in with the original Decl. /// - /// @param[in] original_ctx + /// \param[in] original_ctx /// A pointer whose target is filled in with the original's ASTContext. /// - /// @return + /// \return /// True if lookup succeeded; false otherwise. - //------------------------------------------------------------------ bool ResolveDeclOrigin(const clang::Decl *decl, clang::Decl **original_decl, clang::ASTContext **original_ctx); - //------------------------------------------------------------------ /// Returns m_merger_up. Only call this if the target is configured to use /// modern lookup, - //------------------------------------------------------------------ clang::ExternalASTMerger &GetMergerUnchecked(); - //------------------------------------------------------------------ /// Returns true if there is a merger. This only occurs if the target is /// using modern lookup. - //------------------------------------------------------------------ bool HasMerger() { return (bool)m_merger_up; } protected: @@ -471,15 +424,13 @@ std::set<const char *> m_active_lookups; }; -//---------------------------------------------------------------------- -/// @class NameSearchContext ClangASTSource.h +/// \class NameSearchContext ClangASTSource.h /// "lldb/Expression/ClangASTSource.h" Container for all objects relevant to a /// single name lookup /// /// LLDB needs to create Decls for entities it finds. This class communicates /// what name is being searched for and provides helper functions to construct /// Decls given appropriate type information. -//---------------------------------------------------------------------- struct NameSearchContext { ClangASTSource &m_ast_source; ///< The AST source making the request llvm::SmallVectorImpl<clang::NamedDecl *> @@ -504,24 +455,22 @@ bool type : 1; } m_found; - //------------------------------------------------------------------ /// Constructor /// /// Initializes class variables. /// - /// @param[in] astSource + /// \param[in] astSource /// A reference to the AST source making a request. /// - /// @param[in] decls + /// \param[in] decls /// A reference to a list into which new Decls will be placed. This /// list is typically empty when the function is called. /// - /// @param[in] name + /// \param[in] name /// The name being searched for (always an Identifier). /// - /// @param[in] dc + /// \param[in] dc /// The DeclContext to register Decls in. - //------------------------------------------------------------------ NameSearchContext(ClangASTSource &astSource, llvm::SmallVectorImpl<clang::NamedDecl *> &decls, clang::DeclarationName &name, const clang::DeclContext *dc) @@ -530,59 +479,47 @@ memset(&m_found, 0, sizeof(m_found)); } - //------------------------------------------------------------------ /// Create a VarDecl with the name being searched for and the provided type /// and register it in the right places. /// - /// @param[in] type + /// \param[in] type /// The opaque QualType for the VarDecl being registered. - //------------------------------------------------------------------ clang::NamedDecl *AddVarDecl(const CompilerType &type); - //------------------------------------------------------------------ /// Create a FunDecl with the name being searched for and the provided type /// and register it in the right places. /// - /// @param[in] type + /// \param[in] type /// The opaque QualType for the FunDecl being registered. /// - /// @param[in] extern_c + /// \param[in] extern_c /// If true, build an extern "C" linkage specification for this. - //------------------------------------------------------------------ clang::NamedDecl *AddFunDecl(const CompilerType &type, bool extern_c = false); - //------------------------------------------------------------------ /// Create a FunDecl with the name being searched for and generic type (i.e. /// intptr_t NAME_GOES_HERE(...)) and register it in the right places. - //------------------------------------------------------------------ clang::NamedDecl *AddGenericFunDecl(); - //------------------------------------------------------------------ /// Create a TypeDecl with the name being searched for and the provided type /// and register it in the right places. /// - /// @param[in] compiler_type + /// \param[in] compiler_type /// The opaque QualType for the TypeDecl being registered. - //------------------------------------------------------------------ clang::NamedDecl *AddTypeDecl(const CompilerType &compiler_type); - //------------------------------------------------------------------ /// Add Decls from the provided DeclContextLookupResult to the list of /// results. /// - /// @param[in] result + /// \param[in] result /// The DeclContextLookupResult, usually returned as the result /// of querying a DeclContext. - //------------------------------------------------------------------ void AddLookupResult(clang::DeclContextLookupResult result); - //------------------------------------------------------------------ /// Add a NamedDecl to the list of results. /// - /// @param[in] decl + /// \param[in] decl /// The NamedDecl, usually returned as the result /// of querying a DeclContext. - //------------------------------------------------------------------ void AddNamedDecl(clang::NamedDecl *decl); };
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangDiagnostic.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangDiagnostic.h index 9ea4e3a..db50c2a 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangDiagnostic.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangDiagnostic.h
@@ -1,9 +1,8 @@ //===-- ClangDiagnostic.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -34,7 +33,7 @@ uint32_t compiler_id) : Diagnostic(message, severity, eDiagnosticOriginClang, compiler_id) {} - virtual ~ClangDiagnostic() = default; + ~ClangDiagnostic() override = default; bool HasFixIts() const override { return !m_fixit_vec.empty(); }
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp index 9c2f8c4..a49a702 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp
@@ -1,9 +1,8 @@ //===-- ClangExpressionDeclMap.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,9 +32,7 @@ #include "lldb/Symbol/TypeList.h" #include "lldb/Symbol/Variable.h" #include "lldb/Symbol/VariableList.h" -#include "lldb/Target/CPPLanguageRuntime.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" @@ -54,6 +51,8 @@ #include "clang/AST/RecursiveASTVisitor.h" #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" +#include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" using namespace lldb; using namespace lldb_private; @@ -66,10 +65,11 @@ ClangExpressionDeclMap::ClangExpressionDeclMap( bool keep_result_in_memory, Materializer::PersistentVariableDelegate *result_delegate, - ExecutionContext &exe_ctx) + ExecutionContext &exe_ctx, ValueObject *ctx_obj) : ClangASTSource(exe_ctx.GetTargetSP()), m_found_entities(), m_struct_members(), m_keep_result_in_memory(keep_result_in_memory), - m_result_delegate(result_delegate), m_parser_vars(), m_struct_vars() { + m_result_delegate(result_delegate), m_ctx_obj(ctx_obj), m_parser_vars(), + m_struct_vars() { EnableStructVars(); } @@ -132,7 +132,7 @@ if (log) ClangASTMetrics::DumpCounters(log); - if (m_parser_vars.get()) { + if (m_parser_vars) { for (size_t entity_index = 0, num_entities = m_found_entities.GetSize(); entity_index < num_entities; ++entity_index) { ExpressionVariableSP var_sp( @@ -272,9 +272,15 @@ merger.AddSources(importer_source); clang::ASTImporter &exporter = merger.ImporterForOrigin(source); CompleteAllDeclContexts(exporter, file, root); - clang::QualType ret = exporter.Import(root); + llvm::Expected<clang::QualType> ret_or_error = exporter.Import(root); merger.RemoveSources(importer_source); - return ret; + if (ret_or_error) { + return *ret_or_error; + } else { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + LLDB_LOG_ERROR(log, ret_or_error.takeError(), "Couldn't import type: {0}"); + return clang::QualType(); + } } TypeFromUser ClangExpressionDeclMap::DeportType(ClangASTContext &target, @@ -309,7 +315,7 @@ } bool ClangExpressionDeclMap::AddPersistentVariable(const NamedDecl *decl, - const ConstString &name, + ConstString name, TypeFromParser parser_type, bool is_result, bool is_lvalue) { @@ -361,7 +367,7 @@ Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx; Target *target = exe_ctx.GetTargetPtr(); - if (target == NULL) + if (target == nullptr) return false; ClangASTContext *context(target->GetScratchClangASTContext()); @@ -424,7 +430,7 @@ } bool ClangExpressionDeclMap::AddValueToStruct(const NamedDecl *decl, - const ConstString &name, + ConstString name, llvm::Value *value, size_t size, lldb::offset_t alignment) { assert(m_struct_vars.get()); @@ -604,7 +610,7 @@ addr_t ClangExpressionDeclMap::GetSymbolAddress(Target &target, Process *process, - const ConstString &name, + ConstString name, lldb::SymbolType symbol_type, lldb_private::Module *module) { SymbolContextList sc_list; @@ -692,7 +698,7 @@ } if (symbol_load_addr == LLDB_INVALID_ADDRESS && process) { - ObjCLanguageRuntime *runtime = process->GetObjCLanguageRuntime(); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process); if (runtime) { symbol_load_addr = runtime->LookupRuntimeSymbol(name); @@ -702,7 +708,7 @@ return symbol_load_addr; } -addr_t ClangExpressionDeclMap::GetSymbolAddress(const ConstString &name, +addr_t ClangExpressionDeclMap::GetSymbolAddress(ConstString name, lldb::SymbolType symbol_type) { assert(m_parser_vars.get()); @@ -715,7 +721,7 @@ } lldb::VariableSP ClangExpressionDeclMap::FindGlobalVariable( - Target &target, ModuleSP &module, const ConstString &name, + Target &target, ModuleSP &module, ConstString name, CompilerDeclContext *namespace_decl, TypeFromUser *type) { VariableList vars; @@ -921,16 +927,31 @@ name.GetCString()); context.AddNamedDecl(parser_named_decl); - } while (0); + } while (false); } if (name.GetCString()[0] == '$' && !namespace_decl) { static ConstString g_lldb_class_name("$__lldb_class"); if (name == g_lldb_class_name) { + if (m_ctx_obj) { + Status status; + lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status); + if (!ctx_obj_ptr || status.Fail()) + return; + + AddThisType(context, TypeFromUser(m_ctx_obj->GetCompilerType()), + current_id); + + m_struct_vars->m_object_pointer_type = + TypeFromUser(ctx_obj_ptr->GetCompilerType()); + + return; + } + // Clang is looking for the type of "this" - if (frame == NULL) + if (frame == nullptr) return; // Find the block that defines the function represented by "sym_ctx" @@ -1020,6 +1041,21 @@ static ConstString g_lldb_objc_class_name("$__lldb_objc_class"); if (name == g_lldb_objc_class_name) { + if (m_ctx_obj) { + Status status; + lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status); + if (!ctx_obj_ptr || status.Fail()) + return; + + AddOneType(context, TypeFromUser(m_ctx_obj->GetCompilerType()), + current_id); + + m_struct_vars->m_object_pointer_type = + TypeFromUser(ctx_obj_ptr->GetCompilerType()); + + return; + } + // Clang is looking for the type of "*self" if (!frame) @@ -1241,7 +1277,8 @@ } } if (target) { - var = FindGlobalVariable(*target, module_sp, name, &namespace_decl, NULL); + var = FindGlobalVariable(*target, module_sp, name, &namespace_decl, + nullptr); if (var) { valobj = ValueObjectVariable::Create(target, var); @@ -1398,8 +1435,8 @@ } if (sc_list.GetSize()) { - Symbol *extern_symbol = NULL; - Symbol *non_extern_symbol = NULL; + Symbol *extern_symbol = nullptr; + Symbol *non_extern_symbol = nullptr; for (uint32_t index = 0, num_indices = sc_list.GetSize(); index < num_indices; ++index) { @@ -1416,13 +1453,13 @@ if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr)) continue; - AddOneFunction(context, sym_ctx.function, NULL, current_id); + AddOneFunction(context, sym_ctx.function, nullptr, current_id); context.m_found.function_with_type_info = true; context.m_found.function = true; } else if (sym_ctx.symbol) { if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target) { sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target); - if (sym_ctx.symbol == NULL) + if (sym_ctx.symbol == nullptr) continue; } @@ -1448,10 +1485,10 @@ if (!context.m_found.function_with_type_info) { if (extern_symbol) { - AddOneFunction(context, NULL, extern_symbol, current_id); + AddOneFunction(context, nullptr, extern_symbol, current_id); context.m_found.function = true; } else if (non_extern_symbol) { - AddOneFunction(context, NULL, non_extern_symbol, current_id); + AddOneFunction(context, nullptr, non_extern_symbol, current_id); context.m_found.function = true; } } @@ -1525,7 +1562,7 @@ context.m_found.variable = true; } } - } while (0); + } while (false); } if (target && !context.m_found.variable && !namespace_decl) { @@ -1687,7 +1724,7 @@ bool is_reference = pt.IsReferenceType(); - NamedDecl *var_decl = NULL; + NamedDecl *var_decl = nullptr; if (is_reference) var_decl = context.AddVarDecl(pt); else @@ -1704,7 +1741,7 @@ entity->GetParserVars(GetParserID()); parser_vars->m_parser_type = pt; parser_vars->m_named_decl = var_decl; - parser_vars->m_llvm_value = NULL; + parser_vars->m_llvm_value = nullptr; parser_vars->m_lldb_value = var_location; parser_vars->m_lldb_var = var; @@ -1747,7 +1784,7 @@ ->GetParserVars(GetParserID()); parser_vars->m_parser_type = parser_type; parser_vars->m_named_decl = var_decl; - parser_vars->m_llvm_value = NULL; + parser_vars->m_llvm_value = nullptr; parser_vars->m_lldb_value.Clear(); if (log) { @@ -1766,7 +1803,7 @@ Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr(); - if (target == NULL) + if (target == nullptr) return; ASTContext *scratch_ast_context = @@ -1805,7 +1842,7 @@ parser_vars->m_parser_type = parser_type; parser_vars->m_named_decl = var_decl; - parser_vars->m_llvm_value = NULL; + parser_vars->m_llvm_value = nullptr; parser_vars->m_lldb_sym = &symbol; if (log) { @@ -1853,7 +1890,7 @@ var_type.getAsOpaquePtr(), ClangASTContext::GetASTContext(&var_decl->getASTContext())); - lldb::opaque_compiler_type_t copied_type = 0; + lldb::opaque_compiler_type_t copied_type = nullptr; if (m_ast_importer_sp) { copied_type = m_ast_importer_sp->CopyType( scratch_ast_context->getASTContext(), &var_decl->getASTContext(), @@ -1926,7 +1963,7 @@ entity->GetParserVars(GetParserID()); parser_vars->m_parser_type = parser_clang_type; parser_vars->m_named_decl = var_decl; - parser_vars->m_llvm_value = NULL; + parser_vars->m_llvm_value = nullptr; parser_vars->m_lldb_value.Clear(); entity->m_flags |= ClangExpressionVariable::EVBareRegister; @@ -1945,7 +1982,7 @@ Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); - NamedDecl *function_decl = NULL; + NamedDecl *function_decl = nullptr; Address fun_address; CompilerType function_clang_type; @@ -2105,7 +2142,7 @@ } parser_vars->m_named_decl = function_decl; - parser_vars->m_llvm_value = NULL; + parser_vars->m_llvm_value = nullptr; if (log) { std::string function_str = @@ -2125,7 +2162,7 @@ } void ClangExpressionDeclMap::AddThisType(NameSearchContext &context, - TypeFromUser &ut, + const TypeFromUser &ut, unsigned int current_id) { CompilerType copied_clang_type = GuardedCopyType(ut); @@ -2158,7 +2195,7 @@ CXXMethodDecl *method_decl = ClangASTContext::GetASTContext(m_ast_context) ->AddMethodToCXXRecordType( - copied_clang_type.GetOpaqueQualType(), "$__lldb_expr", NULL, + copied_clang_type.GetOpaqueQualType(), "$__lldb_expr", nullptr, method_type, lldb::eAccessPublic, is_virtual, is_static, is_inline, is_explicit, is_attr_used, is_artificial); @@ -2199,7 +2236,7 @@ } void ClangExpressionDeclMap::AddOneType(NameSearchContext &context, - TypeFromUser &ut, + const TypeFromUser &ut, unsigned int current_id) { CompilerType copied_clang_type = GuardedCopyType(ut);
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.h index 93fa578..03b73e6 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.h
@@ -1,9 +1,8 @@ //===-- ClangExpressionDeclMap.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,8 +29,7 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class ClangExpressionDeclMap ClangExpressionDeclMap.h +/// \class ClangExpressionDeclMap ClangExpressionDeclMap.h /// "lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are /// defined in LLDB's debug information. /// @@ -54,236 +52,213 @@ /// /// Fourth and finally, it "dematerializes" the struct after the JITted code /// has has executed, placing the new values back where it found the old ones. -//---------------------------------------------------------------------- class ClangExpressionDeclMap : public ClangASTSource { public: - //------------------------------------------------------------------ /// Constructor /// /// Initializes class variables. /// - /// @param[in] keep_result_in_memory + /// \param[in] keep_result_in_memory /// If true, inhibits the normal deallocation of the memory for /// the result persistent variable, and instead marks the variable /// as persisting. /// - /// @param[in] delegate + /// \param[in] delegate /// If non-NULL, use this delegate to report result values. This /// allows the client ClangUserExpression to report a result. /// - /// @param[in] exe_ctx + /// \param[in] exe_ctx /// The execution context to use when parsing. - //------------------------------------------------------------------ + /// + /// \param[in] ctx_obj + /// If not empty, then expression is evaluated in context of this object. + /// See the comment to `UserExpression::Evaluate` for details. ClangExpressionDeclMap( bool keep_result_in_memory, Materializer::PersistentVariableDelegate *result_delegate, - ExecutionContext &exe_ctx); + ExecutionContext &exe_ctx, + ValueObject *ctx_obj); - //------------------------------------------------------------------ /// Destructor - //------------------------------------------------------------------ ~ClangExpressionDeclMap() override; - //------------------------------------------------------------------ /// Enable the state needed for parsing and IR transformation. /// - /// @param[in] exe_ctx + /// \param[in] exe_ctx /// The execution context to use when finding types for variables. /// Also used to find a "scratch" AST context to store result types. /// - /// @param[in] materializer + /// \param[in] materializer /// If non-NULL, the materializer to populate with information about /// the variables to use /// - /// @return + /// \return /// True if parsing is possible; false if it is unsafe to continue. - //------------------------------------------------------------------ bool WillParse(ExecutionContext &exe_ctx, Materializer *materializer); void InstallCodeGenerator(clang::ASTConsumer *code_gen); - //------------------------------------------------------------------ /// [Used by ClangExpressionParser] For each variable that had an unknown /// type at the beginning of parsing, determine its final type now. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ bool ResolveUnknownTypes(); - //------------------------------------------------------------------ /// Disable the state needed for parsing and IR transformation. - //------------------------------------------------------------------ void DidParse(); - //------------------------------------------------------------------ /// [Used by IRForTarget] Add a variable to the list of persistent /// variables for the process. /// - /// @param[in] decl + /// \param[in] decl /// The Clang declaration for the persistent variable, used for /// lookup during parsing. /// - /// @param[in] name + /// \param[in] name /// The name of the persistent variable, usually $something. /// - /// @param[in] type + /// \param[in] type /// The type of the variable, in the Clang parser's context. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ bool AddPersistentVariable(const clang::NamedDecl *decl, - const ConstString &name, TypeFromParser type, + ConstString name, TypeFromParser type, bool is_result, bool is_lvalue); - //------------------------------------------------------------------ /// [Used by IRForTarget] Add a variable to the struct that needs to /// be materialized each time the expression runs. /// - /// @param[in] decl + /// \param[in] decl /// The Clang declaration for the variable. /// - /// @param[in] name + /// \param[in] name /// The name of the variable. /// - /// @param[in] value + /// \param[in] value /// The LLVM IR value for this variable. /// - /// @param[in] size + /// \param[in] size /// The size of the variable in bytes. /// - /// @param[in] alignment + /// \param[in] alignment /// The required alignment of the variable in bytes. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ - bool AddValueToStruct(const clang::NamedDecl *decl, const ConstString &name, + bool AddValueToStruct(const clang::NamedDecl *decl, ConstString name, llvm::Value *value, size_t size, lldb::offset_t alignment); - //------------------------------------------------------------------ /// [Used by IRForTarget] Finalize the struct, laying out the position of /// each object in it. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ bool DoStructLayout(); - //------------------------------------------------------------------ /// [Used by IRForTarget] Get general information about the laid-out struct /// after DoStructLayout() has been called. /// - /// @param[out] num_elements + /// \param[out] num_elements /// The number of elements in the struct. /// - /// @param[out] size + /// \param[out] size /// The size of the struct, in bytes. /// - /// @param[out] alignment + /// \param[out] alignment /// The alignment of the struct, in bytes. /// - /// @return + /// \return /// True if the information could be retrieved; false otherwise. - //------------------------------------------------------------------ bool GetStructInfo(uint32_t &num_elements, size_t &size, lldb::offset_t &alignment); - //------------------------------------------------------------------ /// [Used by IRForTarget] Get specific information about one field of the /// laid-out struct after DoStructLayout() has been called. /// - /// @param[out] decl + /// \param[out] decl /// The parsed Decl for the field, as generated by ClangASTSource /// on ClangExpressionDeclMap's behalf. In the case of the result /// value, this will have the name $__lldb_result even if the /// result value ends up having the name $1. This is an /// implementation detail of IRForTarget. /// - /// @param[out] value + /// \param[out] value /// The IR value for the field (usually a GlobalVariable). In /// the case of the result value, this will have the correct /// name ($1, for instance). This is an implementation detail /// of IRForTarget. /// - /// @param[out] offset + /// \param[out] offset /// The offset of the field from the beginning of the struct. /// As long as the struct is aligned according to its required /// alignment, this offset will align the field correctly. /// - /// @param[out] name + /// \param[out] name /// The name of the field as used in materialization. /// - /// @param[in] index + /// \param[in] index /// The index of the field about which information is requested. /// - /// @return + /// \return /// True if the information could be retrieved; false otherwise. - //------------------------------------------------------------------ bool GetStructElement(const clang::NamedDecl *&decl, llvm::Value *&value, lldb::offset_t &offset, ConstString &name, uint32_t index); - //------------------------------------------------------------------ /// [Used by IRForTarget] Get information about a function given its Decl. /// - /// @param[in] decl + /// \param[in] decl /// The parsed Decl for the Function, as generated by ClangASTSource /// on ClangExpressionDeclMap's behalf. /// - /// @param[out] ptr + /// \param[out] ptr /// The absolute address of the function in the target. /// - /// @return + /// \return /// True if the information could be retrieved; false otherwise. - //------------------------------------------------------------------ bool GetFunctionInfo(const clang::NamedDecl *decl, uint64_t &ptr); - //------------------------------------------------------------------ /// [Used by IRForTarget] Get the address of a symbol given nothing but its /// name. /// - /// @param[in] target + /// \param[in] target /// The target to find the symbol in. If not provided, /// then the current parsing context's Target. /// - /// @param[in] process + /// \param[in] process /// The process to use. For Objective-C symbols, the process's /// Objective-C language runtime may be queried if the process /// is non-NULL. /// - /// @param[in] name + /// \param[in] name /// The name of the symbol. /// - /// @param[in] module + /// \param[in] module /// The module to limit the search to. This can be NULL /// - /// @return + /// \return /// Valid load address for the symbol - //------------------------------------------------------------------ lldb::addr_t GetSymbolAddress(Target &target, Process *process, - const ConstString &name, - lldb::SymbolType symbol_type, - Module *module = NULL); + ConstString name, lldb::SymbolType symbol_type, + Module *module = nullptr); - lldb::addr_t GetSymbolAddress(const ConstString &name, + lldb::addr_t GetSymbolAddress(ConstString name, lldb::SymbolType symbol_type); - //------------------------------------------------------------------ /// [Used by IRInterpreter] Get basic target information. /// - /// @param[out] byte_order + /// \param[out] byte_order /// The byte order of the target. /// - /// @param[out] address_byte_size + /// \param[out] address_byte_size /// The size of a pointer in bytes. /// - /// @return + /// \return /// True if the information could be determined; false /// otherwise. - //------------------------------------------------------------------ struct TargetInfo { lldb::ByteOrder byte_order; size_t address_byte_size; @@ -296,38 +271,34 @@ }; TargetInfo GetTargetInfo(); - //------------------------------------------------------------------ /// [Used by ClangASTSource] Find all entities matching a given name, using /// a NameSearchContext to make Decls for them. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext that can construct Decls for this name. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ void FindExternalVisibleDecls(NameSearchContext &context) override; - //------------------------------------------------------------------ /// Find all entities matching a given name in a given module/namespace, /// using a NameSearchContext to make Decls for them. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext that can construct Decls for this name. /// - /// @param[in] module + /// \param[in] module /// If non-NULL, the module to query. /// - /// @param[in] namespace_decl + /// \param[in] namespace_decl /// If valid and module is non-NULL, the parent namespace. /// - /// @param[in] current_id + /// \param[in] current_id /// The ID for the current FindExternalVisibleDecls invocation, /// for logging purposes. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ void FindExternalVisibleDecls(NameSearchContext &context, lldb::ModuleSP module, CompilerDeclContext &namespace_decl, @@ -344,10 +315,12 @@ Materializer::PersistentVariableDelegate *m_result_delegate; ///< If non-NULL, used to report expression results to ///ClangUserExpression. + ValueObject *m_ctx_obj; ///< If not empty, then expression is + ///evaluated in context of this object. + ///For details see the comment to + ///`UserExpression::Evaluate`. - //---------------------------------------------------------------------- /// The following values should not live beyond parsing - //---------------------------------------------------------------------- class ParserVars { public: ParserVars() {} @@ -357,7 +330,7 @@ return m_exe_ctx.GetTargetPtr(); else if (m_sym_ctx.target_sp) m_sym_ctx.target_sp.get(); - return NULL; + return nullptr; } ExecutionContext m_exe_ctx; ///< The execution context to use when parsing. @@ -380,27 +353,21 @@ std::unique_ptr<ParserVars> m_parser_vars; - //---------------------------------------------------------------------- /// Activate parser-specific variables - //---------------------------------------------------------------------- void EnableParserVars() { if (!m_parser_vars.get()) m_parser_vars = llvm::make_unique<ParserVars>(); } - //---------------------------------------------------------------------- /// Deallocate parser-specific variables - //---------------------------------------------------------------------- void DisableParserVars() { m_parser_vars.reset(); } - //---------------------------------------------------------------------- /// The following values contain layout information for the materialized /// struct, but are not specific to a single materialization - //---------------------------------------------------------------------- struct StructVars { StructVars() : m_struct_alignment(0), m_struct_size(0), m_struct_laid_out(false), - m_result_name(), m_object_pointer_type(NULL, NULL) {} + m_result_name(), m_object_pointer_type(nullptr, nullptr) {} lldb::offset_t m_struct_alignment; ///< The alignment of the struct in bytes. @@ -416,202 +383,176 @@ std::unique_ptr<StructVars> m_struct_vars; - //---------------------------------------------------------------------- /// Activate struct variables - //---------------------------------------------------------------------- void EnableStructVars() { if (!m_struct_vars.get()) m_struct_vars.reset(new struct StructVars); } - //---------------------------------------------------------------------- /// Deallocate struct variables - //---------------------------------------------------------------------- void DisableStructVars() { m_struct_vars.reset(); } - //---------------------------------------------------------------------- /// Get this parser's ID for use in extracting parser- and JIT-specific data /// from persistent variables. - //---------------------------------------------------------------------- uint64_t GetParserID() { return (uint64_t) this; } - //------------------------------------------------------------------ /// Given a target, find a variable that matches the given name and type. /// - /// @param[in] target + /// \param[in] target /// The target to use as a basis for finding the variable. /// - /// @param[in] module + /// \param[in] module /// If non-NULL, the module to search. /// - /// @param[in] name + /// \param[in] name /// The name as a plain C string. /// - /// @param[in] namespace_decl + /// \param[in] namespace_decl /// If non-NULL and module is non-NULL, the parent namespace. /// - /// @param[in] type + /// \param[in] type /// The required type for the variable. This function may be called /// during parsing, in which case we don't know its type; hence the /// default. /// - /// @return + /// \return /// The LLDB Variable found, or NULL if none was found. - //------------------------------------------------------------------ lldb::VariableSP FindGlobalVariable(Target &target, lldb::ModuleSP &module, - const ConstString &name, + ConstString name, CompilerDeclContext *namespace_decl, - TypeFromUser *type = NULL); + TypeFromUser *type = nullptr); - //------------------------------------------------------------------ /// Get the value of a variable in a given execution context and return the /// associated Types if needed. /// - /// @param[in] var + /// \param[in] var /// The variable to evaluate. /// - /// @param[out] var_location + /// \param[out] var_location /// The variable location value to fill in /// - /// @param[out] found_type + /// \param[out] found_type /// The type of the found value, as it was found in the user process. /// This is only useful when the variable is being inspected on behalf /// of the parser, hence the default. /// - /// @param[out] parser_type + /// \param[out] parser_type /// The type of the found value, as it was copied into the parser's /// AST context. This is only useful when the variable is being /// inspected on behalf of the parser, hence the default. /// - /// @param[in] decl + /// \param[in] decl /// The Decl to be looked up. /// - /// @return + /// \return /// Return true if the value was successfully filled in. - //------------------------------------------------------------------ bool GetVariableValue(lldb::VariableSP &var, lldb_private::Value &var_location, - TypeFromUser *found_type = NULL, - TypeFromParser *parser_type = NULL); + TypeFromUser *found_type = nullptr, + TypeFromParser *parser_type = nullptr); - //------------------------------------------------------------------ /// Use the NameSearchContext to generate a Decl for the given LLDB /// Variable, and put it in the Tuple list. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when constructing the Decl. /// - /// @param[in] var + /// \param[in] var /// The LLDB Variable that needs a Decl. /// - /// @param[in] valobj + /// \param[in] valobj /// The LLDB ValueObject for that variable. - //------------------------------------------------------------------ void AddOneVariable(NameSearchContext &context, lldb::VariableSP var, lldb::ValueObjectSP valobj, unsigned int current_id); - //------------------------------------------------------------------ /// Use the NameSearchContext to generate a Decl for the given persistent /// variable, and put it in the list of found entities. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when constructing the Decl. /// - /// @param[in] pvar + /// \param[in] pvar /// The persistent variable that needs a Decl. /// - /// @param[in] current_id + /// \param[in] current_id /// The ID of the current invocation of FindExternalVisibleDecls /// for logging purposes. - //------------------------------------------------------------------ void AddOneVariable(NameSearchContext &context, lldb::ExpressionVariableSP &pvar_sp, unsigned int current_id); - //------------------------------------------------------------------ /// Use the NameSearchContext to generate a Decl for the given LLDB symbol /// (treated as a variable), and put it in the list of found entities. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when constructing the Decl. /// - /// @param[in] var + /// \param[in] var /// The LLDB Variable that needs a Decl. - //------------------------------------------------------------------ void AddOneGenericVariable(NameSearchContext &context, const Symbol &symbol, unsigned int current_id); - //------------------------------------------------------------------ /// Use the NameSearchContext to generate a Decl for the given function. /// (Functions are not placed in the Tuple list.) Can handle both fully /// typed functions and generic functions. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when constructing the Decl. /// - /// @param[in] fun + /// \param[in] fun /// The Function that needs to be created. If non-NULL, this is /// a fully-typed function. /// - /// @param[in] sym + /// \param[in] sym /// The Symbol that corresponds to a function that needs to be /// created with generic type (unitptr_t foo(...)). - //------------------------------------------------------------------ void AddOneFunction(NameSearchContext &context, Function *fun, Symbol *sym, unsigned int current_id); - //------------------------------------------------------------------ /// Use the NameSearchContext to generate a Decl for the given register. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when constructing the Decl. /// - /// @param[in] reg_info + /// \param[in] reg_info /// The information corresponding to that register. - //------------------------------------------------------------------ void AddOneRegister(NameSearchContext &context, const RegisterInfo *reg_info, unsigned int current_id); - //------------------------------------------------------------------ /// Use the NameSearchContext to generate a Decl for the given type. (Types /// are not placed in the Tuple list.) /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when constructing the Decl. /// - /// @param[in] type + /// \param[in] type /// The type that needs to be created. - //------------------------------------------------------------------ - void AddOneType(NameSearchContext &context, TypeFromUser &type, + void AddOneType(NameSearchContext &context, const TypeFromUser &type, unsigned int current_id); - //------------------------------------------------------------------ /// Generate a Decl for "*this" and add a member function declaration to it /// for the expression, then report it. /// - /// @param[in] context + /// \param[in] context /// The NameSearchContext to use when constructing the Decl. /// - /// @param[in] type + /// \param[in] type /// The type for *this. - //------------------------------------------------------------------ - void AddThisType(NameSearchContext &context, TypeFromUser &type, + void AddThisType(NameSearchContext &context, const TypeFromUser &type, unsigned int current_id); - //------------------------------------------------------------------ /// Move a type out of the current ASTContext into another, but make sure to /// export all components of the type also. /// - /// @param[in] target + /// \param[in] target /// The ClangASTContext to move to. - /// @param[in] source + /// \param[in] source /// The ClangASTContext to move from. This is assumed to be going away. - /// @param[in] parser_type + /// \param[in] parser_type /// The type as it appears in the source context. /// - /// @return + /// \return /// Returns the moved type, or an empty type if there was a problem. - //------------------------------------------------------------------ TypeFromUser DeportType(ClangASTContext &target, ClangASTContext &source, TypeFromParser parser_type);
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionHelper.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionHelper.h index b5b640c..48da5ab 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionHelper.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionHelper.h
@@ -1,9 +1,8 @@ //===-- ClangExpressionHelper.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ class RecordingMemoryManager; -//---------------------------------------------------------------------- // ClangExpressionHelper -//---------------------------------------------------------------------- class ClangExpressionHelper : public ExpressionTypeSystemHelper { public: static bool classof(const ExpressionTypeSystemHelper *ts) { @@ -37,25 +34,19 @@ : ExpressionTypeSystemHelper( ExpressionTypeSystemHelper::LLVMCastKind::eKindClangHelper) {} - //------------------------------------------------------------------ /// Destructor - //------------------------------------------------------------------ virtual ~ClangExpressionHelper() {} - //------------------------------------------------------------------ /// Return the object that the parser should use when resolving external /// values. May be NULL if everything should be self-contained. - //------------------------------------------------------------------ virtual ClangExpressionDeclMap *DeclMap() = 0; - //------------------------------------------------------------------ /// Return the object that the parser should allow to access ASTs. /// May be NULL if the ASTs do not need to be transformed. /// - /// @param[in] passthrough + /// \param[in] passthrough /// The ASTConsumer that the returned transformer should send /// the ASTs to after transformation. - //------------------------------------------------------------------ virtual clang::ASTConsumer * ASTTransformer(clang::ASTConsumer *passthrough) = 0;
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp index 6650c0d..7d13891 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
@@ -1,19 +1,16 @@ //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <cctype> #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/PrettyPrinter.h" #include "clang/Basic/DiagnosticIDs.h" -#include "clang/Basic/FileManager.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Version.h" @@ -39,15 +36,11 @@ #include "llvm/ADT/StringRef.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" +#include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.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 "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/DynamicLibrary.h" @@ -58,19 +51,25 @@ #include "ClangDiagnostic.h" #include "ClangExpressionParser.h" +#include "ClangUserExpression.h" +#include "ASTUtils.h" #include "ClangASTSource.h" +#include "ClangDiagnostic.h" #include "ClangExpressionDeclMap.h" #include "ClangExpressionHelper.h" +#include "ClangExpressionParser.h" +#include "ClangHost.h" #include "ClangModulesDeclVendor.h" #include "ClangPersistentVariables.h" +#include "IRDynamicChecks.h" #include "IRForTarget.h" +#include "ModuleDependencyCollector.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Disassembler.h" #include "lldb/Core/Module.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Expression/IRDynamicChecks.h" #include "lldb/Expression/IRExecutionUnit.h" #include "lldb/Expression/IRInterpreter.h" #include "lldb/Host/File.h" @@ -79,17 +78,22 @@ #include "lldb/Symbol/SymbolVendor.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Language.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadPlanCallFunction.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Reproducer.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StringList.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + +#include <cctype> +#include <memory> + using namespace clang; using namespace llvm; using namespace lldb_private; @@ -111,24 +115,19 @@ void moduleImport(SourceLocation import_location, clang::ModuleIdPath path, const clang::Module * /*null*/) override { - std::vector<ConstString> string_path; + SourceModule module; - for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) { - string_path.push_back(ConstString(component.first->getName())); - } + for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) + module.path.push_back(ConstString(component.first->getName())); StreamString error_stream; ClangModulesDeclVendor::ModuleVector exported_modules; - - if (!m_decl_vendor.AddModule(string_path, &exported_modules, - m_error_stream)) { + if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream)) m_has_errors = true; - } - for (ClangModulesDeclVendor::ModuleID module : exported_modules) { + for (ClangModulesDeclVendor::ModuleID module : exported_modules) m_persistent_vars.AddHandLoadedClangModule(module); - } } bool hasErrors() { return m_has_errors; } @@ -150,7 +149,7 @@ } void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, - const clang::Diagnostic &Info) { + const clang::Diagnostic &Info) override { if (m_manager) { llvm::SmallVector<char, 32> diag_str; Info.FormatDiagnostic(diag_str); @@ -214,15 +213,58 @@ std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough; }; +static void +SetupModuleHeaderPaths(CompilerInstance *compiler, + std::vector<ConstString> include_directories, + lldb::TargetSP target_sp) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + + HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts(); + + for (ConstString dir : include_directories) { + search_opts.AddPath(dir.AsCString(), frontend::System, false, true); + LLDB_LOG(log, "Added user include dir: {0}", dir); + } + + llvm::SmallString<128> module_cache; + auto props = ModuleList::GetGlobalModuleListProperties(); + props.GetClangModulesCachePath().GetPath(module_cache); + search_opts.ModuleCachePath = module_cache.str(); + LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str()); + + FileSpec clang_resource_dir = GetClangResourceDir(); + std::string resource_dir = clang_resource_dir.GetPath(); + if (FileSystem::Instance().IsDirectory(resource_dir)) { + search_opts.ResourceDir = resource_dir; + std::string resource_include = resource_dir + "/include"; + search_opts.AddPath(resource_include, frontend::System, false, true); + + LLDB_LOG(log, "Added resource include dir: {0}", resource_include); + } + + search_opts.ImplicitModuleMaps = true; + + std::vector<std::string> system_include_directories = + target_sp->GetPlatform()->GetSystemIncludeDirectories( + lldb::eLanguageTypeC_plus_plus); + + for (const std::string &include_dir : system_include_directories) { + search_opts.AddPath(include_dir, frontend::System, false, true); + + LLDB_LOG(log, "Added system include dir: {0}", include_dir); + } +} + //===----------------------------------------------------------------------===// // Implementation of ClangExpressionParser //===----------------------------------------------------------------------===// -ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope, - Expression &expr, - bool generate_debug_info) +ClangExpressionParser::ClangExpressionParser( + ExecutionContextScope *exe_scope, Expression &expr, + bool generate_debug_info, std::vector<ConstString> include_directories) : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(), - m_pp_callbacks(nullptr) { + m_pp_callbacks(nullptr), + m_include_directories(std::move(include_directories)) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); // We can't compile expressions without a target. So if the exe_scope is @@ -249,6 +291,22 @@ // 1. Create a new compiler instance. m_compiler.reset(new CompilerInstance()); + + // When capturing a reproducer, hook up the file collector with clang to + // collector modules and headers. + if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { + repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>(); + m_compiler->setModuleDepCollector( + std::make_shared<ModuleDependencyCollectorAdaptor>( + fp.GetFileCollector())); + DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts(); + opts.IncludeSystemHeaders = true; + opts.IncludeModuleFiles = true; + } + + // Make sure clang uses the same VFS as LLDB. + m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); + lldb::LanguageType frame_lang = expr.Language(); // defaults to lldb::eLanguageTypeUnknown bool overridden_target_opts = false; @@ -363,6 +421,7 @@ // 5. Set language options. lldb::LanguageType language = expr.Language(); + LangOptions &lang_opts = m_compiler->getLangOpts(); switch (language) { case lldb::eLanguageTypeC: @@ -374,13 +433,13 @@ // For now, the expression parser must use C++ anytime the language is a C // family language, because the expression parser uses features of C++ to // capture values. - m_compiler->getLangOpts().CPlusPlus = true; + lang_opts.CPlusPlus = true; break; case lldb::eLanguageTypeObjC: - m_compiler->getLangOpts().ObjC = true; + lang_opts.ObjC = true; // FIXME: the following language option is a temporary workaround, // to "ask for ObjC, get ObjC++" (see comment above). - m_compiler->getLangOpts().CPlusPlus = true; + lang_opts.CPlusPlus = true; // Clang now sets as default C++14 as the default standard (with // GNU extensions), so we do the same here to avoid mismatches that @@ -388,71 +447,92 @@ // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see // two lines below) so we decide to be consistent with that, but this could // be re-evaluated in the future. - m_compiler->getLangOpts().CPlusPlus11 = true; + lang_opts.CPlusPlus11 = true; break; case lldb::eLanguageTypeC_plus_plus: case lldb::eLanguageTypeC_plus_plus_11: case lldb::eLanguageTypeC_plus_plus_14: - m_compiler->getLangOpts().CPlusPlus11 = true; + lang_opts.CPlusPlus11 = true; m_compiler->getHeaderSearchOpts().UseLibcxx = true; LLVM_FALLTHROUGH; case lldb::eLanguageTypeC_plus_plus_03: - m_compiler->getLangOpts().CPlusPlus = true; + lang_opts.CPlusPlus = true; if (process_sp) - m_compiler->getLangOpts().ObjC = + lang_opts.ObjC = process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr; break; case lldb::eLanguageTypeObjC_plus_plus: case lldb::eLanguageTypeUnknown: default: - m_compiler->getLangOpts().ObjC = true; - m_compiler->getLangOpts().CPlusPlus = true; - m_compiler->getLangOpts().CPlusPlus11 = true; + lang_opts.ObjC = true; + lang_opts.CPlusPlus = true; + lang_opts.CPlusPlus11 = true; m_compiler->getHeaderSearchOpts().UseLibcxx = true; break; } - m_compiler->getLangOpts().Bool = true; - m_compiler->getLangOpts().WChar = true; - m_compiler->getLangOpts().Blocks = true; - m_compiler->getLangOpts().DebuggerSupport = + lang_opts.Bool = true; + lang_opts.WChar = true; + lang_opts.Blocks = true; + lang_opts.DebuggerSupport = true; // Features specifically for debugger clients if (expr.DesiredResultType() == Expression::eResultTypeId) - m_compiler->getLangOpts().DebuggerCastResultToId = true; + lang_opts.DebuggerCastResultToId = true; - m_compiler->getLangOpts().CharIsSigned = - ArchSpec(m_compiler->getTargetOpts().Triple.c_str()) - .CharIsSignedByDefault(); + lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str()) + .CharIsSignedByDefault(); // Spell checking is a nice feature, but it ends up completing a lot of types // that we didn't strictly speaking need to complete. As a result, we spend a // long time parsing and importing debug information. - m_compiler->getLangOpts().SpellChecking = false; + lang_opts.SpellChecking = false; - if (process_sp && m_compiler->getLangOpts().ObjC) { - if (process_sp->GetObjCLanguageRuntime()) { - if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == + auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr); + if (clang_expr && clang_expr->DidImportCxxModules()) { + LLDB_LOG(log, "Adding lang options for importing C++ modules"); + + lang_opts.Modules = true; + // We want to implicitly build modules. + lang_opts.ImplicitModules = true; + // To automatically import all submodules when we import 'std'. + lang_opts.ModulesLocalVisibility = false; + + // We use the @import statements, so we need this: + // FIXME: We could use the modules-ts, but that currently doesn't work. + lang_opts.ObjC = true; + + // Options we need to parse libc++ code successfully. + // FIXME: We should ask the driver for the appropriate default flags. + lang_opts.GNUMode = true; + lang_opts.GNUKeywords = true; + lang_opts.DoubleSquareBracketAttributes = true; + lang_opts.CPlusPlus11 = true; + + SetupModuleHeaderPaths(m_compiler.get(), m_include_directories, + target_sp); + } + + if (process_sp && lang_opts.ObjC) { + if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) { + if (runtime->GetRuntimeVersion() == ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2) - m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, - VersionTuple(10, 7)); + lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7)); else - m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, - VersionTuple(10, 7)); + lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX, + VersionTuple(10, 7)); - if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing()) - m_compiler->getLangOpts().DebuggerObjCLiteral = true; + if (runtime->HasNewLiteralsAndIndexing()) + lang_opts.DebuggerObjCLiteral = true; } } - m_compiler->getLangOpts().ThreadsafeStatics = false; - m_compiler->getLangOpts().AccessControl = - false; // Debuggers get universal access - m_compiler->getLangOpts().DollarIdents = - true; // $ indicates a persistent variable name + lang_opts.ThreadsafeStatics = false; + lang_opts.AccessControl = false; // Debuggers get universal access + lang_opts.DollarIdents = true; // $ indicates a persistent variable name // We enable all builtin functions beside the builtins from libc/libm (e.g. // 'fopen'). Those libc functions are already correctly handled by LLDB, and // additionally enabling them as expandable builtins is breaking Clang. - m_compiler->getLangOpts().NoBuiltin = true; + lang_opts.NoBuiltin = true; // Set CodeGen options m_compiler->getCodeGenOpts().EmitDeclMetadata = true; @@ -483,14 +563,9 @@ m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter); // 7. Set up the source management objects inside the compiler - - clang::FileSystemOptions file_system_options; - m_file_manager.reset(new clang::FileManager(file_system_options)); - - if (!m_compiler->hasSourceManager()) - m_compiler->createSourceManager(*m_file_manager.get()); - m_compiler->createFileManager(); + if (!m_compiler->hasSourceManager()) + m_compiler->createSourceManager(m_compiler->getFileManager()); m_compiler->createPreprocessor(TU_Complete); if (ClangModulesDeclVendor *decl_vendor = @@ -517,17 +592,6 @@ m_compiler->createASTContext(); clang::ASTContext &ast_context = m_compiler->getASTContext(); - ClangExpressionHelper *type_system_helper = - dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); - ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); - - if (decl_map) { - llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source( - decl_map->CreateProxy()); - decl_map->InstallASTContext(ast_context, m_compiler->getFileManager()); - ast_context.setExternalSource(ast_source); - } - m_ast_context.reset( new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str())); m_ast_context->setASTContext(&ast_context); @@ -545,13 +609,11 @@ namespace { -//---------------------------------------------------------------------- -/// @class CodeComplete +/// \class CodeComplete /// /// A code completion consumer for the clang Sema that is responsible for /// creating the completion suggestions when a user requests completion /// of an incomplete `expr` invocation. -//---------------------------------------------------------------------- class CodeComplete : public CodeCompleteConsumer { CodeCompletionTUInfo m_info; @@ -624,20 +686,20 @@ public: /// Constructs a CodeComplete consumer that can be attached to a Sema. - /// @param[out] matches + /// \param[out] matches /// The list of matches that the lldb completion API expects as a result. /// This may already contain matches, so it's only allowed to append /// to this variable. - /// @param[out] expr + /// \param[out] expr /// The whole expression string that we are currently parsing. This /// string needs to be equal to the input the user typed, and NOT the /// final code that Clang is parsing. - /// @param[out] position + /// \param[out] position /// The character position of the user cursor in the `expr` parameter. /// CodeComplete(CompletionRequest &request, clang::LangOptions ops, std::string expr, unsigned position) - : CodeCompleteConsumer(CodeCompleteOptions(), false), + : CodeCompleteConsumer(CodeCompleteOptions()), m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr), m_position(position), m_request(request), m_desc_policy(ops) { @@ -653,7 +715,7 @@ } /// Deregisters and destroys this code-completion consumer. - virtual ~CodeComplete() {} + ~CodeComplete() override {} /// \name Code-completion filtering /// Check if the result should be filtered out. @@ -788,8 +850,8 @@ // To actually get the raw user input here, we have to cast our expression to // the LLVMUserExpression which exposes the right API. This should never fail // as we always have a ClangUserExpression whenever we call this. - LLVMUserExpression &llvm_expr = *static_cast<LLVMUserExpression *>(&m_expr); - CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr.GetUserText(), + ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr); + CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr->GetUserText(), typed_pos); // We don't need a code generator for parsing. m_code_generator.reset(); @@ -848,9 +910,9 @@ if (file.Write(expr_text, bytes_written).Success()) { if (bytes_written == expr_text_len) { file.Close(); - source_mgr.setMainFileID( - source_mgr.createFileID(m_file_manager->getFile(result_path), - SourceLocation(), SrcMgr::C_User)); + source_mgr.setMainFileID(source_mgr.createFileID( + m_compiler->getFileManager().getFile(result_path), + SourceLocation(), SrcMgr::C_User)); created_main_file = true; } } @@ -859,7 +921,7 @@ if (!created_main_file) { std::unique_ptr<MemoryBuffer> memory_buffer = - MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__); + MemoryBuffer::getMemBufferCopy(expr_text, "<lldb-expr>"); source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer))); } @@ -869,12 +931,6 @@ ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); - ASTConsumer *ast_transformer = - type_system_helper->ASTTransformer(m_code_generator.get()); - - if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap()) - decl_map->InstallCodeGenerator(m_code_generator.get()); - // If we want to parse for code completion, we need to attach our code // completion consumer to the Sema and specify a completion position. // While parsing the Sema will call this consumer with the provided @@ -889,18 +945,72 @@ PP.SetCodeCompletionPoint(main_file, completion_line, completion_column); } + ASTConsumer *ast_transformer = + type_system_helper->ASTTransformer(m_code_generator.get()); + + std::unique_ptr<clang::ASTConsumer> Consumer; if (ast_transformer) { - ast_transformer->Initialize(m_compiler->getASTContext()); - ParseAST(m_compiler->getPreprocessor(), ast_transformer, - m_compiler->getASTContext(), false, TU_Complete, - completion_consumer); + Consumer.reset(new ASTConsumerForwarder(ast_transformer)); + } else if (m_code_generator) { + Consumer.reset(new ASTConsumerForwarder(m_code_generator.get())); } else { - m_code_generator->Initialize(m_compiler->getASTContext()); - ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), - m_compiler->getASTContext(), false, TU_Complete, - completion_consumer); + Consumer.reset(new ASTConsumer()); } + clang::ASTContext &ast_context = m_compiler->getASTContext(); + + m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context, + *Consumer, TU_Complete, completion_consumer)); + m_compiler->setASTConsumer(std::move(Consumer)); + + if (ast_context.getLangOpts().Modules) { + m_compiler->createModuleManager(); + m_ast_context->setSema(&m_compiler->getSema()); + } + + ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); + if (decl_map) { + decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer()); + + clang::ExternalASTSource *ast_source = decl_map->CreateProxy(); + + if (ast_context.getExternalSource()) { + auto module_wrapper = + new ExternalASTSourceWrapper(ast_context.getExternalSource()); + + auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source); + + auto multiplexer = + new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper); + IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer); + ast_context.setExternalSource(Source); + } else { + ast_context.setExternalSource(ast_source); + } + decl_map->InstallASTContext(ast_context, m_compiler->getFileManager()); + } + + // Check that the ASTReader is properly attached to ASTContext and Sema. + if (ast_context.getLangOpts().Modules) { + assert(m_compiler->getASTContext().getExternalSource() && + "ASTContext doesn't know about the ASTReader?"); + assert(m_compiler->getSema().getExternalSource() && + "Sema doesn't know about the ASTReader?"); + } + + { + llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema( + &m_compiler->getSema()); + ParseAST(m_compiler->getSema(), false, false); + } + + // Make sure we have no pointer to the Sema we are about to destroy. + if (ast_context.getLangOpts().Modules) + m_ast_context->setSema(nullptr); + // Destroy the Sema. This is necessary because we want to emulate the + // original behavior of ParseAST (which also destroys the Sema after parsing). + m_compiler->setSema(nullptr); + diag_buf->EndSourceFile(); unsigned num_errors = diag_buf->getNumErrors(); @@ -1050,10 +1160,10 @@ lldb_private::Status err; - std::unique_ptr<llvm::Module> llvm_module_ap( + std::unique_ptr<llvm::Module> llvm_module_up( m_code_generator->ReleaseModule()); - if (!llvm_module_ap.get()) { + if (!llvm_module_up) { err.SetErrorToGenericError(); err.SetErrorString("IR doesn't contain a module"); return err; @@ -1064,7 +1174,7 @@ if (execution_policy != eExecutionPolicyTopLevel) { // Find the actual name of the function (it's often mangled somehow) - if (!FindFunctionInModule(function_name, llvm_module_ap.get(), + if (!FindFunctionInModule(function_name, llvm_module_up.get(), m_expr.FunctionName())) { err.SetErrorToGenericError(); err.SetErrorStringWithFormat("Couldn't find %s() in the module", @@ -1105,14 +1215,14 @@ "expression module '%s'", __FUNCTION__, m_expr.FunctionName()); - custom_passes.EarlyPasses->run(*llvm_module_ap); + custom_passes.EarlyPasses->run(*llvm_module_up); } - execution_unit_sp.reset( - new IRExecutionUnit(m_llvm_context, // handed off here - llvm_module_ap, // handed off here - function_name, exe_ctx.GetTargetSP(), sc, - m_compiler->getTargetOpts().Features)); + execution_unit_sp = std::make_shared<IRExecutionUnit>( + m_llvm_context, // handed off here + llvm_module_up, // handed off here + function_name, exe_ctx.GetTargetSP(), sc, + m_compiler->getTargetOpts().Features); ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); @@ -1120,7 +1230,7 @@ type_system_helper->DeclMap(); // result can be NULL if (decl_map) { - Stream *error_stream = NULL; + Stream *error_stream = nullptr; Target *target = exe_ctx.GetTargetPtr(); error_stream = target->GetDebugger().GetErrorFile().get(); @@ -1172,8 +1282,8 @@ (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) { if (m_expr.NeedsValidation() && process) { if (!process->GetDynamicCheckers()) { - DynamicCheckerFunctions *dynamic_checkers = - new DynamicCheckerFunctions(); + ClangDynamicCheckerFunctions *dynamic_checkers = + new ClangDynamicCheckerFunctions(); DiagnosticManager install_diagnostics; @@ -1189,27 +1299,30 @@ process->SetDynamicCheckers(dynamic_checkers); if (log) - log->Printf("== [ClangUserExpression::Evaluate] Finished " - "installing dynamic checkers =="); + log->Printf("== [ClangExpressionParser::PrepareForExecution] " + "Finished installing dynamic checkers =="); } - IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), - function_name.AsCString()); + if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>( + process->GetDynamicCheckers())) { + IRDynamicChecks ir_dynamic_checks(*checker_funcs, + function_name.AsCString()); - llvm::Module *module = execution_unit_sp->GetModule(); - if (!module || !ir_dynamic_checks.runOnModule(*module)) { - err.SetErrorToGenericError(); - err.SetErrorString("Couldn't add dynamic checks to the expression"); - return err; - } + llvm::Module *module = execution_unit_sp->GetModule(); + if (!module || !ir_dynamic_checks.runOnModule(*module)) { + err.SetErrorToGenericError(); + err.SetErrorString("Couldn't add dynamic checks to the expression"); + return err; + } - if (custom_passes.LatePasses) { - if (log) - log->Printf("%s - Running Late IR Passes from LanguageRuntime on " - "expression module '%s'", - __FUNCTION__, m_expr.FunctionName()); + if (custom_passes.LatePasses) { + if (log) + log->Printf("%s - Running Late IR Passes from LanguageRuntime on " + "expression module '%s'", + __FUNCTION__, m_expr.FunctionName()); - custom_passes.LatePasses->run(*module); + custom_passes.LatePasses->run(*module); + } } } }
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h index 03ff55f..a42c219 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h
@@ -1,9 +1,8 @@ //===-- ClangExpressionParser.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,8 +27,7 @@ class IRExecutionUnit; -//---------------------------------------------------------------------- -/// @class ClangExpressionParser ClangExpressionParser.h +/// \class ClangExpressionParser ClangExpressionParser.h /// "lldb/Expression/ClangExpressionParser.h" Encapsulates an instance of /// Clang that can parse expressions. /// @@ -38,140 +36,130 @@ /// as a glorified parameter list, performing the required parsing and /// conversion to formats (DWARF bytecode, or JIT compiled machine code) that /// can be executed. -//---------------------------------------------------------------------- class ClangExpressionParser : public ExpressionParser { public: - //------------------------------------------------------------------ /// Constructor /// /// Initializes class variables. /// - /// @param[in] exe_scope, + /// \param[in] exe_scope, /// If non-NULL, an execution context scope that can help to /// correctly create an expression with a valid process for /// optional tuning Objective-C runtime support. Can be NULL. /// - /// @param[in] expr + /// \param[in] expr /// The expression to be parsed. - //------------------------------------------------------------------ + /// + /// @param[in] include_directories + /// List of include directories that should be used when parsing the + /// expression. ClangExpressionParser(ExecutionContextScope *exe_scope, Expression &expr, - bool generate_debug_info); + bool generate_debug_info, + std::vector<ConstString> include_directories = {}); - //------------------------------------------------------------------ /// Destructor - //------------------------------------------------------------------ ~ClangExpressionParser() override; bool Complete(CompletionRequest &request, unsigned line, unsigned pos, unsigned typed_pos) override; - //------------------------------------------------------------------ /// Parse a single expression and convert it to IR using Clang. Don't wrap /// the expression in anything at all. /// - /// @param[in] diagnostic_manager + /// \param[in] diagnostic_manager /// The diagnostic manager to report errors to. /// - /// @return + /// \return /// The number of errors encountered during parsing. 0 means /// success. - //------------------------------------------------------------------ unsigned Parse(DiagnosticManager &diagnostic_manager) override; bool RewriteExpression(DiagnosticManager &diagnostic_manager) override; - //------------------------------------------------------------------ /// Ready an already-parsed expression for execution, possibly evaluating it /// statically. /// - /// @param[out] func_addr + /// \param[out] func_addr /// The address to which the function has been written. /// - /// @param[out] func_end + /// \param[out] func_end /// The end of the function's allocated memory region. (func_addr /// and func_end do not delimit an allocated region; the allocated /// region may begin before func_addr.) /// - /// @param[in] execution_unit_sp + /// \param[in] execution_unit_sp /// After parsing, ownership of the execution unit for /// for the expression is handed to this shared pointer. /// - /// @param[in] exe_ctx + /// \param[in] exe_ctx /// The execution context to write the function into. /// - /// @param[out] evaluated_statically + /// \param[out] evaluated_statically /// Set to true if the expression could be interpreted statically; /// untouched otherwise. /// - /// @param[out] const_result + /// \param[out] const_result /// If the result of the expression is constant, and the /// expression has no side effects, this is set to the result of the /// expression. /// - /// @param[in] execution_policy + /// \param[in] execution_policy /// Determines whether the expression must be JIT-compiled, must be /// evaluated statically, or whether this decision may be made /// opportunistically. /// - /// @return + /// \return /// An error code indicating the success or failure of the operation. /// Test with Success(). - //------------------------------------------------------------------ Status PrepareForExecution(lldb::addr_t &func_addr, lldb::addr_t &func_end, lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, bool &can_interpret, lldb_private::ExecutionPolicy execution_policy) override; - //------------------------------------------------------------------ /// Run all static initializers for an execution unit. /// - /// @param[in] execution_unit_sp + /// \param[in] execution_unit_sp /// The execution unit. /// - /// @param[in] exe_ctx + /// \param[in] exe_ctx /// The execution context to use when running them. Thread can't be null. /// - /// @return + /// \return /// The error code indicating the - //------------------------------------------------------------------ Status RunStaticInitializers(lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx); - //------------------------------------------------------------------ /// Returns a string representing current ABI. /// - /// @param[in] target_arch + /// \param[in] target_arch /// The target architecture. /// - /// @return + /// \return /// A string representing target ABI for the current architecture. - //------------------------------------------------------------------- std::string GetClangTargetABI(const ArchSpec &target_arch); private: - //------------------------------------------------------------------ /// Parses the expression. /// - /// @param[in] diagnostic_manager + /// \param[in] diagnostic_manager /// The diagnostic manager that should receive the diagnostics /// from the parsing process. /// - /// @param[in] completion + /// \param[in] completion /// The completion consumer that should be used during parsing /// (or a nullptr if no consumer should be attached). /// - /// @param[in] completion_line + /// \param[in] completion_line /// The line in which the completion marker should be placed. /// The first line is represented by the value 0. /// - /// @param[in] completion_column + /// \param[in] completion_column /// The column in which the completion marker should be placed. /// The first column is represented by the value 0. /// - /// @return + /// \return /// The number of parsing errors. - //------------------------------------------------------------------- unsigned ParseInternal(DiagnosticManager &diagnostic_manager, clang::CodeCompleteConsumer *completion = nullptr, unsigned completion_line = 0, @@ -179,8 +167,6 @@ std::unique_ptr<llvm::LLVMContext> m_llvm_context; ///< The LLVM context to generate IR into - std::unique_ptr<clang::FileManager> - m_file_manager; ///< The Clang file manager object used by the compiler std::unique_ptr<clang::CompilerInstance> m_compiler; ///< The Clang compiler used to parse expressions into IR std::unique_ptr<clang::CodeGenerator> @@ -190,6 +176,8 @@ LLDBPreprocessorCallbacks *m_pp_callbacks; ///< Called when the preprocessor ///encounters module imports std::unique_ptr<ClangASTContext> m_ast_context; + + std::vector<ConstString> m_include_directories; }; }
diff --git a/src/llvm-project/lldb/source/Expression/ExpressionSourceCode.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp similarity index 65% rename from src/llvm-project/lldb/source/Expression/ExpressionSourceCode.cpp rename to src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp index 03b2d26..f513b1e 100644 --- a/src/llvm-project/lldb/source/Expression/ExpressionSourceCode.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp
@@ -1,13 +1,17 @@ -//===-- ExpressionSourceCode.cpp --------------------------------*- C++ -*-===// +//===-- ClangExpressionSourceCode.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Expression/ExpressionSourceCode.h" +#include "ClangExpressionSourceCode.h" + +#include "clang/Basic/CharInfo.h" +#include "clang/Basic/SourceManager.h" +#include "clang/Lex/Lexer.h" +#include "llvm/ADT/StringRef.h" #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h" #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" @@ -25,7 +29,7 @@ using namespace lldb_private; -const char *ExpressionSourceCode::g_expression_prefix = R"( +const char *ClangExpressionSourceCode::g_expression_prefix = R"( #ifndef NULL #define NULL (__null) #endif @@ -162,24 +166,121 @@ } } +namespace { +/// Allows checking if a token is contained in a given expression. +class TokenVerifier { + /// The tokens we found in the expression. + llvm::StringSet<> m_tokens; + +public: + TokenVerifier(std::string body); + /// Returns true iff the given expression body contained a token with the + /// given content. + bool hasToken(llvm::StringRef token) const { + return m_tokens.find(token) != m_tokens.end(); + } +}; +} // namespace + +TokenVerifier::TokenVerifier(std::string body) { + using namespace clang; + + // We only care about tokens and not their original source locations. If we + // move the whole expression to only be in one line we can simplify the + // following code that extracts the token contents. + std::replace(body.begin(), body.end(), '\n', ' '); + std::replace(body.begin(), body.end(), '\r', ' '); + + FileSystemOptions file_opts; + FileManager file_mgr(file_opts, + FileSystem::Instance().GetVirtualFileSystem()); + + // Let's build the actual source code Clang needs and setup some utility + // objects. + llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_ids(new DiagnosticIDs()); + llvm::IntrusiveRefCntPtr<DiagnosticOptions> diags_opts( + new DiagnosticOptions()); + DiagnosticsEngine diags(diag_ids, diags_opts); + clang::SourceManager SM(diags, file_mgr); + auto buf = llvm::MemoryBuffer::getMemBuffer(body); + + FileID FID = SM.createFileID(clang::SourceManager::Unowned, buf.get()); + + // Let's just enable the latest ObjC and C++ which should get most tokens + // right. + LangOptions Opts; + Opts.ObjC = true; + Opts.DollarIdents = true; + Opts.CPlusPlus17 = true; + Opts.LineComment = true; + + Lexer lex(FID, buf.get(), SM, Opts); + + Token token; + bool exit = false; + while (!exit) { + // Returns true if this is the last token we get from the lexer. + exit = lex.LexFromRawLexer(token); + + // Extract the column number which we need to extract the token content. + // Our expression is just one line, so we don't need to handle any line + // numbers here. + bool invalid = false; + unsigned start = SM.getSpellingColumnNumber(token.getLocation(), &invalid); + if (invalid) + continue; + // Column numbers start at 1, but indexes in our string start at 0. + --start; + + // Annotations don't have a length, so let's skip them. + if (token.isAnnotation()) + continue; + + // Extract the token string from our source code and store it. + std::string token_str = body.substr(start, token.getLength()); + if (token_str.empty()) + continue; + m_tokens.insert(token_str); + } +} + static void AddLocalVariableDecls(const lldb::VariableListSP &var_list_sp, - StreamString &stream) { + StreamString &stream, + const std::string &expr, + lldb::LanguageType wrapping_language) { + TokenVerifier tokens(expr); + for (size_t i = 0; i < var_list_sp->GetSize(); i++) { lldb::VariableSP var_sp = var_list_sp->GetVariableAtIndex(i); ConstString var_name = var_sp->GetName(); - if (!var_name || var_name == ConstString("this") || - var_name == ConstString(".block_descriptor")) + + + // We can check for .block_descriptor w/o checking for langauge since this + // is not a valid identifier in either C or C++. + if (!var_name || var_name == ".block_descriptor") + continue; + + if (!expr.empty() && !tokens.hasToken(var_name.GetStringRef())) + continue; + + if ((var_name == "self" || var_name == "_cmd") && + (wrapping_language == lldb::eLanguageTypeObjC || + wrapping_language == lldb::eLanguageTypeObjC_plus_plus)) + continue; + + if (var_name == "this" && + wrapping_language == lldb::eLanguageTypeC_plus_plus) continue; stream.Printf("using $__lldb_local_vars::%s;\n", var_name.AsCString()); } } -bool ExpressionSourceCode::GetText(std::string &text, - lldb::LanguageType wrapping_language, - bool static_method, - ExecutionContext &exe_ctx) const { +bool ClangExpressionSourceCode::GetText( + std::string &text, lldb::LanguageType wrapping_language, bool static_method, + ExecutionContext &exe_ctx, bool add_locals, bool force_add_all_locals, + llvm::ArrayRef<std::string> modules) const { const char *target_specific_defines = "typedef signed char BOOL;\n"; std::string module_macros; @@ -252,14 +353,14 @@ } } - ConstString object_name; - if (Language::LanguageIsCPlusPlus(frame->GetLanguage())) { + if (add_locals) if (target->GetInjectLocalVariables(&exe_ctx)) { lldb::VariableListSP var_list_sp = frame->GetInScopeVariableList(false, true); - AddLocalVariableDecls(var_list_sp, lldb_local_var_decls); + AddLocalVariableDecls(var_list_sp, lldb_local_var_decls, + force_add_all_locals ? "" : m_body, + wrapping_language); } - } } if (m_wrap) { @@ -272,6 +373,15 @@ break; } + // Generate a list of @import statements that will import the specified + // module into our expression. + std::string module_imports; + for (const std::string &module : modules) { + module_imports.append("@import "); + module_imports.append(module); + module_imports.append(";\n"); + } + StreamString wrap_stream; wrap_stream.Printf("%s\n%s\n%s\n%s\n%s\n", module_macros.c_str(), @@ -297,50 +407,58 @@ default: break; case lldb::eLanguageTypeC: - wrap_stream.Printf("void \n" + wrap_stream.Printf("%s" + "void \n" "%s(void *$__lldb_arg) \n" "{ \n" " %s; \n" "%s" "} \n", - m_name.c_str(), lldb_local_var_decls.GetData(), - tagged_body.c_str()); + module_imports.c_str(), m_name.c_str(), + lldb_local_var_decls.GetData(), tagged_body.c_str()); break; case lldb::eLanguageTypeC_plus_plus: - wrap_stream.Printf("void \n" + wrap_stream.Printf("%s" + "void \n" "$__lldb_class::%s(void *$__lldb_arg) \n" "{ \n" " %s; \n" "%s" "} \n", - m_name.c_str(), lldb_local_var_decls.GetData(), - tagged_body.c_str()); + module_imports.c_str(), m_name.c_str(), + lldb_local_var_decls.GetData(), tagged_body.c_str()); break; case lldb::eLanguageTypeObjC: if (static_method) { wrap_stream.Printf( + "%s" "@interface $__lldb_objc_class ($__lldb_category) \n" "+(void)%s:(void *)$__lldb_arg; \n" "@end \n" "@implementation $__lldb_objc_class ($__lldb_category) \n" "+(void)%s:(void *)$__lldb_arg \n" "{ \n" + " %s; \n" "%s" "} \n" "@end \n", - m_name.c_str(), m_name.c_str(), tagged_body.c_str()); + module_imports.c_str(), m_name.c_str(), m_name.c_str(), + lldb_local_var_decls.GetData(), tagged_body.c_str()); } else { wrap_stream.Printf( + "%s" "@interface $__lldb_objc_class ($__lldb_category) \n" "-(void)%s:(void *)$__lldb_arg; \n" "@end \n" "@implementation $__lldb_objc_class ($__lldb_category) \n" "-(void)%s:(void *)$__lldb_arg \n" "{ \n" + " %s; \n" "%s" "} \n" "@end \n", - m_name.c_str(), m_name.c_str(), tagged_body.c_str()); + module_imports.c_str(), m_name.c_str(), m_name.c_str(), + lldb_local_var_decls.GetData(), tagged_body.c_str()); } break; } @@ -353,7 +471,7 @@ return true; } -bool ExpressionSourceCode::GetOriginalBodyBounds( +bool ClangExpressionSourceCode::GetOriginalBodyBounds( std::string transformed_text, lldb::LanguageType wrapping_language, size_t &start_loc, size_t &end_loc) { const char *start_marker;
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.h new file mode 100644 index 0000000..8942902 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.h
@@ -0,0 +1,71 @@ +//===-- ClangExpressionSourceCode.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 liblldb_ClangExpressionSourceCode_h +#define liblldb_ClangExpressionSourceCode_h + +#include "lldb/Expression/Expression.h" +#include "lldb/Expression/ExpressionSourceCode.h" +#include "lldb/lldb-enumerations.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" + +#include <string> + +namespace lldb_private { + +class ExecutionContext; + +class ClangExpressionSourceCode : public ExpressionSourceCode { +public: + static const char *g_expression_prefix; + + static ClangExpressionSourceCode *CreateWrapped(const char *prefix, + const char *body) { + return new ClangExpressionSourceCode("$__lldb_expr", prefix, body, true); + } + + uint32_t GetNumBodyLines(); + + /// Generates the source code that will evaluate the expression. + /// + /// \param text output parameter containing the source code string. + /// \param wrapping_language If the expression is supossed to be wrapped, + /// then this is the language that should be used for that. + /// \param static_method True iff the expression is valuated inside a static + /// Objective-C method. + /// \param exe_ctx The execution context in which the expression will be + /// evaluated. + /// \param add_locals True iff local variables should be injected into the + /// expression source code. + /// \param force_add_all_locals True iff all local variables should be + /// injected even if they are not used in the expression. + /// \param modules A list of (C++) modules that the expression should import. + /// + /// \return true iff the source code was successfully generated. + bool GetText(std::string &text, lldb::LanguageType wrapping_language, + bool static_method, ExecutionContext &exe_ctx, bool add_locals, + bool force_add_all_locals, + llvm::ArrayRef<std::string> modules) const; + + // Given a string returned by GetText, find the beginning and end of the body + // passed to CreateWrapped. Return true if the bounds could be found. This + // will also work on text with FixItHints applied. + static bool GetOriginalBodyBounds(std::string transformed_text, + lldb::LanguageType wrapping_language, + size_t &start_loc, size_t &end_loc); + +protected: + ClangExpressionSourceCode(const char *name, const char *prefix, const char *body, + bool wrap) : + ExpressionSourceCode(name, prefix, body, wrap) {} +}; + +} // namespace lldb_private + +#endif
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.cpp index 624cbf2..b5a2c80 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.cpp
@@ -1,9 +1,8 @@ //===-- ClangExpressionVariable.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,7 +31,7 @@ } ClangExpressionVariable::ClangExpressionVariable( - ExecutionContextScope *exe_scope, Value &value, const ConstString &name, + ExecutionContextScope *exe_scope, Value &value, ConstString name, uint16_t flags) : ExpressionVariable(LLVMCastKind::eKindClang), m_parser_vars(), m_jit_vars() { @@ -49,7 +48,7 @@ } ClangExpressionVariable::ClangExpressionVariable( - ExecutionContextScope *exe_scope, const ConstString &name, + ExecutionContextScope *exe_scope, ConstString name, const TypeFromUser &user_type, lldb::ByteOrder byte_order, uint32_t addr_byte_size) : ExpressionVariable(LLVMCastKind::eKindClang), m_parser_vars(),
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.h index 6886f09..eb7f74f 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.h
@@ -1,9 +1,8 @@ //===-- ClangExpressionVariable.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,8 +34,7 @@ class ValueObjectConstResult; -//---------------------------------------------------------------------- -/// @class ClangExpressionVariable ClangExpressionVariable.h +/// \class ClangExpressionVariable ClangExpressionVariable.h /// "lldb/Expression/ClangExpressionVariable.h" Encapsulates one variable for /// the expression parser. /// @@ -56,36 +54,31 @@ /// /// This class supports all of these use cases using simple type polymorphism, /// and provides necessary support methods. Its interface is RTTI-neutral. -//---------------------------------------------------------------------- class ClangExpressionVariable : public ExpressionVariable { public: ClangExpressionVariable(ExecutionContextScope *exe_scope, lldb::ByteOrder byte_order, uint32_t addr_byte_size); ClangExpressionVariable(ExecutionContextScope *exe_scope, Value &value, - const ConstString &name, uint16_t flags = EVNone); + ConstString name, uint16_t flags = EVNone); ClangExpressionVariable(const lldb::ValueObjectSP &valobj_sp); ClangExpressionVariable(ExecutionContextScope *exe_scope, - const ConstString &name, + ConstString name, const TypeFromUser &user_type, lldb::ByteOrder byte_order, uint32_t addr_byte_size); - //---------------------------------------------------------------------- /// Utility functions for dealing with ExpressionVariableLists in Clang- /// specific ways - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- /// Finds a variable by NamedDecl in the list. /// - /// @param[in] name + /// \param[in] name /// The name of the requested variable. /// - /// @return + /// \return /// The variable requested, or NULL if that variable is not in the list. - //---------------------------------------------------------------------- static ClangExpressionVariable * FindVariableInList(ExpressionVariableList &list, const clang::NamedDecl *decl, uint64_t parser_id) { @@ -105,31 +98,27 @@ return nullptr; } - //---------------------------------------------------------------------- /// If the variable contains its own data, make a Value point at it. If \a /// exe_ctx in not NULL, the value will be resolved in with that execution /// context. /// - /// @param[in] value + /// \param[in] value /// The value to point at the data. /// - /// @param[in] exe_ctx + /// \param[in] exe_ctx /// The execution context to use to resolve \a value. /// - /// @return + /// \return /// True on success; false otherwise (in particular, if this variable /// does not contain its own data). - //---------------------------------------------------------------------- bool PointValueAtData(Value &value, ExecutionContext *exe_ctx); - //---------------------------------------------------------------------- /// The following values should not live beyond parsing - //---------------------------------------------------------------------- class ParserVars { public: ParserVars() - : m_parser_type(), m_named_decl(NULL), m_llvm_value(NULL), - m_lldb_value(), m_lldb_var(), m_lldb_sym(NULL) {} + : m_parser_type(), m_named_decl(nullptr), m_llvm_value(nullptr), + m_lldb_value(), m_lldb_var(), m_lldb_sym(nullptr) {} TypeFromParser m_parser_type; ///< The type of the variable according to the parser @@ -149,34 +138,26 @@ ParserVarMap m_parser_vars; public: - //---------------------------------------------------------------------- /// Make this variable usable by the parser by allocating space for parser- /// specific variables - //---------------------------------------------------------------------- void EnableParserVars(uint64_t parser_id) { m_parser_vars.insert(std::make_pair(parser_id, ParserVars())); } - //---------------------------------------------------------------------- /// Deallocate parser-specific variables - //---------------------------------------------------------------------- void DisableParserVars(uint64_t parser_id) { m_parser_vars.erase(parser_id); } - //---------------------------------------------------------------------- /// Access parser-specific variables - //---------------------------------------------------------------------- ParserVars *GetParserVars(uint64_t parser_id) { ParserVarMap::iterator i = m_parser_vars.find(parser_id); if (i == m_parser_vars.end()) - return NULL; + return nullptr; else return &i->second; } - //---------------------------------------------------------------------- /// The following values are valid if the variable is used by JIT code - //---------------------------------------------------------------------- struct JITVars { JITVars() : m_alignment(0), m_size(0), m_offset(0) {} @@ -192,40 +173,32 @@ JITVarMap m_jit_vars; public: - //---------------------------------------------------------------------- /// Make this variable usable for materializing for the JIT by allocating /// space for JIT-specific variables - //---------------------------------------------------------------------- void EnableJITVars(uint64_t parser_id) { m_jit_vars.insert(std::make_pair(parser_id, JITVars())); } - //---------------------------------------------------------------------- /// Deallocate JIT-specific variables - //---------------------------------------------------------------------- void DisableJITVars(uint64_t parser_id) { m_jit_vars.erase(parser_id); } JITVars *GetJITVars(uint64_t parser_id) { JITVarMap::iterator i = m_jit_vars.find(parser_id); if (i == m_jit_vars.end()) - return NULL; + return nullptr; else return &i->second; } TypeFromUser GetTypeFromUser(); - //------------------------------------------------------------------ // llvm casting support - //------------------------------------------------------------------ static bool classof(const ExpressionVariable *ev) { return ev->getKind() == ExpressionVariable::eKindClang; } - //---------------------------------------------------------------------- /// Members - //---------------------------------------------------------------------- DISALLOW_COPY_AND_ASSIGN(ClangExpressionVariable); };
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.cpp index 8ec9ff2..eabc96a 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.cpp
@@ -1,9 +1,8 @@ //===-- ClangFunctionCaller.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -43,9 +42,7 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // ClangFunctionCaller constructor -//---------------------------------------------------------------------- ClangFunctionCaller::ClangFunctionCaller(ExecutionContextScope &exe_scope, const CompilerType &return_type, const Address &functionAddress, @@ -59,9 +56,7 @@ assert(m_jit_process_wp.lock()); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ClangFunctionCaller::~ClangFunctionCaller() {} unsigned
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.h index 9d933bf..24f6f2e 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangFunctionCaller.h
@@ -1,9 +1,8 @@ //===-- ClangFunctionCaller.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,8 +24,7 @@ class ASTStructExtractor; class ClangExpressionParser; -//---------------------------------------------------------------------- -/// @class ClangFunctionCaller ClangFunctionCaller.h +/// \class ClangFunctionCaller ClangFunctionCaller.h /// "lldb/Expression/ClangFunctionCaller.h" Encapsulates a function that can /// be called. /// @@ -58,30 +56,30 @@ /// /// Any of the methods that take arg_addr_ptr can be passed NULL, and the /// argument space will be managed for you. -//---------------------------------------------------------------------- class ClangFunctionCaller : public FunctionCaller { friend class ASTStructExtractor; + /// LLVM-style RTTI support. + static bool classof(const Expression *E) { + return E->getKind() == eKindClangFunctionCaller; + } + class ClangFunctionCallerHelper : public ClangExpressionHelper { public: ClangFunctionCallerHelper(ClangFunctionCaller &owner) : m_owner(owner) {} ~ClangFunctionCallerHelper() override = default; - //------------------------------------------------------------------ /// Return the object that the parser should use when resolving external /// values. May be NULL if everything should be self-contained. - //------------------------------------------------------------------ - ClangExpressionDeclMap *DeclMap() override { return NULL; } + ClangExpressionDeclMap *DeclMap() override { return nullptr; } - //------------------------------------------------------------------ /// Return the object that the parser should allow to access ASTs. May be /// NULL if the ASTs do not need to be transformed. /// - /// @param[in] passthrough + /// \param[in] passthrough /// The ASTConsumer that the returned transformer should send /// the ASTs to after transformation. - //------------------------------------------------------------------ clang::ASTConsumer * ASTTransformer(clang::ASTConsumer *passthrough) override; @@ -94,27 +92,25 @@ }; public: - //------------------------------------------------------------------ /// Constructor /// - /// @param[in] exe_scope + /// \param[in] exe_scope /// An execution context scope that gets us at least a target and /// process. /// - /// @param[in] ast_context + /// \param[in] ast_context /// The AST context to evaluate argument types in. /// - /// @param[in] return_qualtype + /// \param[in] return_qualtype /// An opaque Clang QualType for the function result. Should be /// defined in ast_context. /// - /// @param[in] function_address + /// \param[in] function_address /// The address of the function to call. /// - /// @param[in] arg_value_list + /// \param[in] arg_value_list /// The default values to use when calling this function. Can /// be overridden using WriteFunctionArguments(). - //------------------------------------------------------------------ ClangFunctionCaller(ExecutionContextScope &exe_scope, const CompilerType &return_type, const Address &function_address, @@ -122,20 +118,18 @@ ~ClangFunctionCaller() override; - //------------------------------------------------------------------ /// Compile the wrapper function /// - /// @param[in] thread_to_use_sp + /// \param[in] thread_to_use_sp /// Compilation might end up calling functions. Pass in the thread you /// want the compilation to use. If you pass in an empty ThreadSP it will /// use the currently selected thread. /// - /// @param[in] diagnostic_manager + /// \param[in] diagnostic_manager /// The diagnostic manager to report parser errors to. /// - /// @return + /// \return /// The number of errors. - //------------------------------------------------------------------ unsigned CompileFunction(lldb::ThreadSP thread_to_use_sp, DiagnosticManager &diagnostic_manager) override; @@ -147,9 +141,7 @@ const char *GetWrapperStructName() { return m_wrapper_struct_name.c_str(); } private: - //------------------------------------------------------------------ // For ClangFunctionCaller only - //------------------------------------------------------------------ // Note: the parser needs to be destructed before the execution unit, so // declare the execution unit first.
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp index 44a1335..65c5473 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
@@ -1,9 +1,8 @@ //===-- ClangHost.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,11 +16,9 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Threading.h" +#include "lldb/Host/Config.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/HostInfo.h" -#if !defined(_WIN32) -#include "lldb/Host/posix/HostInfoPosix.h" -#endif #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" @@ -29,18 +26,6 @@ using namespace lldb_private; -#if defined(_WIN32) -static bool ComputeClangDirectory(FileSpec &file_spec) { return false; } -#else -static bool DefaultComputeClangDirectory(FileSpec &file_spec) { - return HostInfoPosix::ComputePathRelativeToLibrary( - file_spec, (llvm::Twine("/lib") + CLANG_LIBDIR_SUFFIX + "/clang/" + - CLANG_VERSION_STRING) - .str()); -} - -#if defined(__APPLE__) - static bool VerifyClangPath(const llvm::Twine &clang_path) { if (FileSystem::Instance().IsDirectory(clang_path)) return true; @@ -52,8 +37,55 @@ return false; } -bool lldb_private::ComputeClangDirectory(FileSpec &lldb_shlib_spec, +/// +/// This will compute the clang resource directory assuming that clang was +/// installed with the same prefix as lldb. +/// +/// If verify is true, the first candidate resource directory will be returned. +/// This mode is only used for testing. +/// +static bool DefaultComputeClangResourceDirectory(FileSpec &lldb_shlib_spec, + FileSpec &file_spec, + bool verify) { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); + std::string raw_path = lldb_shlib_spec.GetPath(); + llvm::StringRef parent_dir = llvm::sys::path::parent_path(raw_path); + + static const llvm::StringRef kResourceDirSuffixes[] = { + // LLVM.org's build of LLDB uses the clang resource directory placed + // in $install_dir/lib{,64}/clang/$clang_version. + "lib" CLANG_LIBDIR_SUFFIX "/clang/" CLANG_VERSION_STRING, + // swift-lldb uses the clang resource directory copied from swift, which + // by default is placed in $install_dir/lib{,64}/lldb/clang. LLDB places + // it there, so we use LLDB_LIBDIR_SUFFIX. + "lib" LLDB_LIBDIR_SUFFIX "/lldb/clang", + }; + + for (const auto &Suffix : kResourceDirSuffixes) { + llvm::SmallString<256> clang_dir(parent_dir); + llvm::SmallString<32> relative_path(Suffix); + llvm::sys::path::native(relative_path); + llvm::sys::path::append(clang_dir, relative_path); + if (!verify || VerifyClangPath(clang_dir)) { + if (log) + log->Printf("DefaultComputeClangResourceDir: Setting ClangResourceDir " + "to \"%s\", verify = %s", + clang_dir.str().str().c_str(), verify ? "true" : "false"); + file_spec.GetDirectory().SetString(clang_dir); + FileSystem::Instance().Resolve(file_spec); + return true; + } + } + + return false; +} + +bool lldb_private::ComputeClangResourceDirectory(FileSpec &lldb_shlib_spec, FileSpec &file_spec, bool verify) { +#if !defined(__APPLE__) + return DefaultComputeClangResourceDirectory(lldb_shlib_spec, file_spec, + verify); +#else std::string raw_path = lldb_shlib_spec.GetPath(); auto rev_it = llvm::sys::path::rbegin(raw_path); @@ -66,8 +98,10 @@ ++rev_it; } + // We found a non-framework build of LLDB if (rev_it == r_end) - return DefaultComputeClangDirectory(file_spec); + return DefaultComputeClangResourceDirectory(lldb_shlib_spec, file_spec, + verify); // Inside Xcode and in Xcode toolchains LLDB is always in lockstep // with the Swift compiler, so it can reuse its Clang resource @@ -84,7 +118,7 @@ "Developer/Toolchains/XcodeDefault.xctoolchain", swift_clang_resource_dir); if (!verify || VerifyClangPath(clang_path)) { - file_spec.SetFile(clang_path.c_str(), FileSpec::Style::native); + file_spec.GetDirectory().SetString(clang_path.c_str()); FileSystem::Instance().Resolve(file_spec); return true; } @@ -99,7 +133,7 @@ raw_path.resize(parent - r_end); llvm::sys::path::append(clang_path, raw_path, swift_clang_resource_dir); if (!verify || VerifyClangPath(clang_path)) { - file_spec.SetFile(clang_path.c_str(), FileSpec::Style::native); + file_spec.GetDirectory().SetString(clang_path.c_str()); FileSystem::Instance().Resolve(file_spec); return true; } @@ -112,30 +146,19 @@ // Fall back to the Clang resource directory inside the framework. raw_path.append("LLDB.framework/Resources/Clang"); - file_spec.SetFile(raw_path.c_str(), FileSpec::Style::native); + file_spec.GetDirectory().SetString(raw_path.c_str()); FileSystem::Instance().Resolve(file_spec); return true; -} - -static bool ComputeClangDirectory(FileSpec &file_spec) { - if (FileSpec lldb_file_spec = HostInfo::GetShlibDir()) - return ComputeClangDirectory(lldb_file_spec, file_spec, true); - return false; -} -#else // __APPLE__ - -// All non-Apple posix systems. -static bool ComputeClangDirectory(FileSpec &file_spec) { - return DefaultComputeClangDirectory(file_spec); -} #endif // __APPLE__ -#endif // _WIN32 +} FileSpec lldb_private::GetClangResourceDir() { static FileSpec g_cached_resource_dir; static llvm::once_flag g_once_flag; llvm::call_once(g_once_flag, []() { - ::ComputeClangDirectory(g_cached_resource_dir); + if (FileSpec lldb_file_spec = HostInfo::GetShlibDir()) + ComputeClangResourceDirectory(lldb_file_spec, g_cached_resource_dir, + true); Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); if (log) log->Printf("GetClangResourceDir() => '%s'",
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.h index 4fe423a..9d49188 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangHost.h
@@ -1,9 +1,8 @@ //===-- ClangHost.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,10 +13,8 @@ class FileSpec; -#if defined(__APPLE__) -bool ComputeClangDirectory(FileSpec &lldb_shlib_spec, FileSpec &file_spec, - bool verify); -#endif +bool ComputeClangResourceDirectory(FileSpec &lldb_shlib_spec, + FileSpec &file_spec, bool verify); FileSpec GetClangResourceDir();
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp index ced21df..4a22079 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
@@ -1,9 +1,8 @@ //===-- ClangModulesDeclVendor.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,15 +22,18 @@ #include "ClangHost.h" #include "ClangModulesDeclVendor.h" +#include "ModuleDependencyCollector.h" #include "lldb/Core/ModuleList.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/SourceModule.h" #include "lldb/Target/Target.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Reproducer.h" #include "lldb/Utility/StreamString.h" using namespace lldb_private; @@ -70,13 +72,13 @@ ~ClangModulesDeclVendorImpl() override = default; - bool AddModule(ModulePath &path, ModuleVector *exported_modules, + bool AddModule(const SourceModule &module, ModuleVector *exported_modules, Stream &error_stream) override; bool AddModulesForCompileUnit(CompileUnit &cu, ModuleVector &exported_modules, Stream &error_stream) override; - uint32_t FindDecls(const ConstString &name, bool append, uint32_t max_matches, + uint32_t FindDecls(ConstString name, bool append, uint32_t max_matches, std::vector<clang::NamedDecl *> &decls) override; void ForEachMacro(const ModuleVector &modules, @@ -183,7 +185,7 @@ } } -bool ClangModulesDeclVendorImpl::AddModule(ModulePath &path, +bool ClangModulesDeclVendorImpl::AddModule(const SourceModule &module, ModuleVector *exported_modules, Stream &error_stream) { // Fail early. @@ -198,7 +200,7 @@ std::vector<ConstString> imported_module; - for (ConstString path_component : path) { + for (ConstString path_component : module.path) { imported_module.push_back(path_component); } @@ -213,11 +215,42 @@ } } - if (!m_compiler_instance->getPreprocessor() - .getHeaderSearchInfo() - .lookupModule(path[0].GetStringRef())) { + clang::HeaderSearch &HS = + m_compiler_instance->getPreprocessor().getHeaderSearchInfo(); + + if (module.search_path) { + auto path_begin = llvm::sys::path::begin(module.search_path.GetStringRef()); + auto path_end = llvm::sys::path::end(module.search_path.GetStringRef()); + auto sysroot_begin = llvm::sys::path::begin(module.sysroot.GetStringRef()); + auto sysroot_end = llvm::sys::path::end(module.sysroot.GetStringRef()); + // FIXME: Use C++14 std::equal(it, it, it, it) variant once it's available. + bool is_system_module = (std::distance(path_begin, path_end) >= + std::distance(sysroot_begin, sysroot_end)) && + std::equal(sysroot_begin, sysroot_end, path_begin); + // No need to inject search paths to modules in the sysroot. + if (!is_system_module) { + auto error = [&]() { + error_stream.Printf("error: No module map file in %s\n", + module.search_path.AsCString()); + return false; + }; + + bool is_system = true; + bool is_framework = false; + auto *dir = + HS.getFileMgr().getDirectory(module.search_path.GetStringRef()); + if (!dir) + return error(); + auto *file = HS.lookupModuleMapFile(dir, is_framework); + if (!file) + return error(); + if (!HS.loadModuleMapFile(file, is_system)) + return error(); + } + } + if (!HS.lookupModule(module.path.front().GetStringRef())) { error_stream.Printf("error: Header search couldn't locate module %s\n", - path[0].AsCString()); + module.path.front().AsCString()); return false; } @@ -229,7 +262,7 @@ clang::SourceManager &source_manager = m_compiler_instance->getASTContext().getSourceManager(); - for (ConstString path_component : path) { + for (ConstString path_component : module.path) { clang_path.push_back(std::make_pair( &m_compiler_instance->getASTContext().Idents.get( path_component.GetStringRef()), @@ -249,19 +282,18 @@ if (!top_level_module) { diagnostic_consumer->DumpDiagnostics(error_stream); error_stream.Printf("error: Couldn't load top-level module %s\n", - path[0].AsCString()); + module.path.front().AsCString()); return false; } clang::Module *submodule = top_level_module; - for (size_t ci = 1; ci < path.size(); ++ci) { - llvm::StringRef component = path[ci].GetStringRef(); - submodule = submodule->findSubmodule(component.str()); + for (auto &component : llvm::ArrayRef<ConstString>(module.path).drop_front()) { + submodule = submodule->findSubmodule(component.GetStringRef()); if (!submodule) { diagnostic_consumer->DumpDiagnostics(error_stream); error_stream.Printf("error: Couldn't load submodule %s\n", - component.str().c_str()); + component.GetCString()); return false; } } @@ -288,12 +320,16 @@ switch (language) { default: return false; - // C++ and friends to be added case lldb::LanguageType::eLanguageTypeC: case lldb::LanguageType::eLanguageTypeC11: case lldb::LanguageType::eLanguageTypeC89: case lldb::LanguageType::eLanguageTypeC99: + case lldb::LanguageType::eLanguageTypeC_plus_plus: + case lldb::LanguageType::eLanguageTypeC_plus_plus_03: + case lldb::LanguageType::eLanguageTypeC_plus_plus_11: + case lldb::LanguageType::eLanguageTypeC_plus_plus_14: case lldb::LanguageType::eLanguageTypeObjC: + case lldb::LanguageType::eLanguageTypeObjC_plus_plus: return true; } } @@ -302,28 +338,17 @@ CompileUnit &cu, ClangModulesDeclVendor::ModuleVector &exported_modules, Stream &error_stream) { if (LanguageSupportsClangModules(cu.GetLanguage())) { - std::vector<ConstString> imported_modules = cu.GetImportedModules(); - - for (ConstString imported_module : imported_modules) { - std::vector<ConstString> path; - - path.push_back(imported_module); - - if (!AddModule(path, &exported_modules, error_stream)) { + for (auto &imported_module : cu.GetImportedModules()) + if (!AddModule(imported_module, &exported_modules, error_stream)) return false; - } - } - - return true; } - return true; } // ClangImporter::lookupValue uint32_t -ClangModulesDeclVendorImpl::FindDecls(const ConstString &name, bool append, +ClangModulesDeclVendorImpl::FindDecls(ConstString name, bool append, uint32_t max_matches, std::vector<clang::NamedDecl *> &decls) { if (!m_enabled) { @@ -583,7 +608,7 @@ compiler_invocation_arguments.push_back(module_cache_argument); } - FileSpecList &module_search_paths = target.GetClangModuleSearchPaths(); + FileSpecList module_search_paths = target.GetClangModuleSearchPaths(); for (size_t spi = 0, spe = module_search_paths.GetSize(); spi < spe; ++spi) { const FileSpec &search_path = module_search_paths.GetFileSpecAtIndex(spi); @@ -610,9 +635,13 @@ std::vector<const char *> compiler_invocation_argument_cstrs; compiler_invocation_argument_cstrs.reserve( compiler_invocation_arguments.size()); - for (const std::string &arg : compiler_invocation_arguments) { + for (const std::string &arg : compiler_invocation_arguments) compiler_invocation_argument_cstrs.push_back(arg.c_str()); - } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + LLDB_LOG(log, "ClangModulesDeclVendor's compiler flags {0:$[ ]}", + llvm::make_range(compiler_invocation_arguments.begin(), + compiler_invocation_arguments.end())); std::shared_ptr<clang::CompilerInvocation> invocation = clang::createInvocationFromCommandLine(compiler_invocation_argument_cstrs, @@ -632,6 +661,20 @@ std::unique_ptr<clang::CompilerInstance> instance( new clang::CompilerInstance); + // When capturing a reproducer, hook up the file collector with clang to + // collector modules and headers. + if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { + repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>(); + instance->setModuleDepCollector( + std::make_shared<ModuleDependencyCollectorAdaptor>( + fp.GetFileCollector())); + clang::DependencyOutputOptions &opts = instance->getDependencyOutputOpts(); + opts.IncludeSystemHeaders = true; + opts.IncludeModuleFiles = true; + } + + // Make sure clang uses the same VFS as LLDB. + instance->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); instance->setDiagnostics(diagnostics_engine.get()); instance->setInvocation(invocation);
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h index 23769cc..d5c8757 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h
@@ -1,9 +1,8 @@ //===-- ClangModulesDeclVendor.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,6 +11,7 @@ #include "lldb/Core/ClangForward.h" #include "lldb/Symbol/DeclVendor.h" +#include "lldb/Symbol/SourceModule.h" #include "lldb/Target/Platform.h" #include <set> @@ -21,9 +21,7 @@ class ClangModulesDeclVendor : public DeclVendor { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ ClangModulesDeclVendor(); ~ClangModulesDeclVendor() override; @@ -34,84 +32,77 @@ typedef uintptr_t ModuleID; typedef std::vector<ModuleID> ModuleVector; - //------------------------------------------------------------------ /// Add a module to the list of modules to search. /// - /// @param[in] path + /// \param[in] module /// The path to the exact module to be loaded. E.g., if the desired /// module is std.io, then this should be { "std", "io" }. /// - /// @param[in] exported_modules + /// \param[in] exported_modules /// If non-NULL, a pointer to a vector to populate with the ID of every /// module that is re-exported by the specified module. /// - /// @param[in] error_stream + /// \param[in] error_stream /// A stream to populate with the output of the Clang parser when /// it tries to load the module. /// - /// @return + /// \return /// True if the module could be loaded; false if not. If the /// compiler encountered a fatal error during a previous module /// load, then this will always return false for this ModuleImporter. - //------------------------------------------------------------------ - virtual bool AddModule(ModulePath &path, ModuleVector *exported_modules, + virtual bool AddModule(const SourceModule &module, + ModuleVector *exported_modules, Stream &error_stream) = 0; - //------------------------------------------------------------------ /// Add all modules referred to in a given compilation unit to the list /// of modules to search. /// - /// @param[in] cu + /// \param[in] cu /// The compilation unit to scan for imported modules. /// - /// @param[in] exported_modules + /// \param[in] exported_modules /// A vector to populate with the ID of each module loaded (directly /// and via re-exports) in this way. /// - /// @param[in] error_stream + /// \param[in] error_stream /// A stream to populate with the output of the Clang parser when /// it tries to load the modules. /// - /// @return + /// \return /// True if all modules referred to by the compilation unit could be /// loaded; false if one could not be loaded. If the compiler /// encountered a fatal error during a previous module /// load, then this will always return false for this ModuleImporter. - //------------------------------------------------------------------ virtual bool AddModulesForCompileUnit(CompileUnit &cu, ModuleVector &exported_modules, Stream &error_stream) = 0; - //------------------------------------------------------------------ /// Enumerate all the macros that are defined by a given set of modules /// that are already imported. /// - /// @param[in] modules + /// \param[in] modules /// The unique IDs for all modules to query. Later modules have higher /// priority, just as if you @imported them in that order. This matters /// if module A #defines a macro and module B #undefs it. /// - /// @param[in] handler + /// \param[in] handler /// A function to call with the text of each #define (including the /// #define directive). #undef directives are not included; we simply /// elide any corresponding #define. If this function returns true, /// we stop the iteration immediately. - //------------------------------------------------------------------ virtual void ForEachMacro(const ModuleVector &modules, std::function<bool(const std::string &)> handler) = 0; - //------------------------------------------------------------------ /// Query whether Clang supports modules for a particular language. /// LLDB uses this to decide whether to try to find the modules loaded - /// by a gaiven compile unit. + /// by a given compile unit. /// - /// @param[in] language + /// \param[in] language /// The language to query for. /// - /// @return + /// \return /// True if Clang has modules for the given language. - //------------------------------------------------------------------ static bool LanguageSupportsClangModules(lldb::LanguageType language); };
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.cpp index bb73d55..742a149 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.cpp
@@ -1,15 +1,15 @@ //===-- ClangPersistentVariables.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "ClangPersistentVariables.h" #include "lldb/Core/Value.h" +#include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Log.h" @@ -32,7 +32,7 @@ } ExpressionVariableSP ClangPersistentVariables::CreatePersistentVariable( - ExecutionContextScope *exe_scope, const ConstString &name, + ExecutionContextScope *exe_scope, ConstString name, const CompilerType &compiler_type, lldb::ByteOrder byte_order, uint32_t addr_byte_size) { return AddNewlyConstructedVariable(new ClangExpressionVariable( @@ -49,11 +49,26 @@ return; name++; - if (strtoul(name, NULL, 0) == m_next_persistent_variable_id - 1) + if (strtoul(name, nullptr, 0) == m_next_persistent_variable_id - 1) m_next_persistent_variable_id--; } -void ClangPersistentVariables::RegisterPersistentDecl(const ConstString &name, +llvm::Optional<CompilerType> +ClangPersistentVariables::GetCompilerTypeFromPersistentDecl( + ConstString type_name) { + CompilerType compiler_type; + if (clang::TypeDecl *tdecl = llvm::dyn_cast_or_null<clang::TypeDecl>( + GetPersistentDecl(type_name))) { + compiler_type.SetCompilerType( + ClangASTContext::GetASTContext(&tdecl->getASTContext()), + reinterpret_cast<lldb::opaque_compiler_type_t>( + const_cast<clang::Type *>(tdecl->getTypeForDecl()))); + return compiler_type; + } + return llvm::None; +} + +void ClangPersistentVariables::RegisterPersistentDecl(ConstString name, clang::NamedDecl *decl) { m_persistent_decls.insert( std::pair<const char *, clang::NamedDecl *>(name.GetCString(), decl)); @@ -68,12 +83,12 @@ } clang::NamedDecl * -ClangPersistentVariables::GetPersistentDecl(const ConstString &name) { +ClangPersistentVariables::GetPersistentDecl(ConstString name) { PersistentDeclMap::const_iterator i = m_persistent_decls.find(name.GetCString()); if (i == m_persistent_decls.end()) - return NULL; + return nullptr; else return i->second; }
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.h index c4438c7..b39f89a 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangPersistentVariables.h
@@ -1,9 +1,8 @@ //===-- ClangPersistentVariables.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,24 +18,20 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class ClangPersistentVariables ClangPersistentVariables.h +/// \class ClangPersistentVariables ClangPersistentVariables.h /// "lldb/Expression/ClangPersistentVariables.h" Manages persistent values /// that need to be preserved between expression invocations. /// /// A list of variables that can be accessed and updated by any expression. See /// ClangPersistentVariable for more discussion. Also provides an increasing, /// 0-based counter for naming result variables. -//---------------------------------------------------------------------- class ClangPersistentVariables : public PersistentExpressionState { public: ClangPersistentVariables(); ~ClangPersistentVariables() override = default; - //------------------------------------------------------------------ // llvm casting support - //------------------------------------------------------------------ static bool classof(const PersistentExpressionState *pv) { return pv->getKind() == PersistentExpressionState::eKindClang; } @@ -45,7 +40,7 @@ CreatePersistentVariable(const lldb::ValueObjectSP &valobj_sp) override; lldb::ExpressionVariableSP CreatePersistentVariable( - ExecutionContextScope *exe_scope, const ConstString &name, + ExecutionContextScope *exe_scope, ConstString name, const CompilerType &compiler_type, lldb::ByteOrder byte_order, uint32_t addr_byte_size) override; @@ -55,9 +50,12 @@ return "$"; } - void RegisterPersistentDecl(const ConstString &name, clang::NamedDecl *decl); + llvm::Optional<CompilerType> + GetCompilerTypeFromPersistentDecl(ConstString type_name) override; - clang::NamedDecl *GetPersistentDecl(const ConstString &name); + void RegisterPersistentDecl(ConstString name, clang::NamedDecl *decl); + + clang::NamedDecl *GetPersistentDecl(ConstString name); void AddHandLoadedClangModule(ClangModulesDeclVendor::ModuleID module) { m_hand_loaded_clang_modules.push_back(module);
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp index f42955d..2dae5b7 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp
@@ -1,9 +1,8 @@ //===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,6 +21,7 @@ #include "ClangDiagnostic.h" #include "ClangExpressionDeclMap.h" #include "ClangExpressionParser.h" +#include "ClangExpressionSourceCode.h" #include "ClangModulesDeclVendor.h" #include "ClangPersistentVariables.h" @@ -37,6 +37,7 @@ #include "lldb/Symbol/Block.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/ClangExternalASTSourceCommon.h" +#include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolVendor.h" @@ -55,18 +56,20 @@ #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" +#include "llvm/ADT/ScopeExit.h" + using namespace lldb_private; ClangUserExpression::ClangUserExpression( ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, - ResultType desired_type, const EvaluateExpressionOptions &options) + ResultType desired_type, const EvaluateExpressionOptions &options, + ValueObject *ctx_obj) : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type, - options), - m_type_system_helper(*m_target_wp.lock().get(), - options.GetExecutionPolicy() == - eExecutionPolicyTopLevel), - m_result_delegate(exe_scope.CalculateTarget()) { + options, eKindClangUserExpression), + m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() == + eExecutionPolicyTopLevel), + m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) { switch (m_language) { case lldb::eLanguageTypeC_plus_plus: m_allow_cxx = true; @@ -99,7 +102,7 @@ } StackFrame *frame = exe_ctx.GetFramePtr(); - if (frame == NULL) { + if (frame == nullptr) { if (log) log->Printf(" [CUE::SC] Null stack frame"); return; @@ -131,7 +134,27 @@ return; } - if (clang::CXXMethodDecl *method_decl = + if (m_ctx_obj) { + switch (m_ctx_obj->GetObjectRuntimeLanguage()) { + case lldb::eLanguageTypeC: + case lldb::eLanguageTypeC89: + case lldb::eLanguageTypeC99: + case lldb::eLanguageTypeC11: + case lldb::eLanguageTypeC_plus_plus: + case lldb::eLanguageTypeC_plus_plus_03: + case lldb::eLanguageTypeC_plus_plus_11: + case lldb::eLanguageTypeC_plus_plus_14: + m_in_cplusplus_method = true; + break; + case lldb::eLanguageTypeObjC: + case lldb::eLanguageTypeObjC_plus_plus: + m_in_objectivec_method = true; + break; + default: + break; + } + m_needs_object_ptr = true; + } else if (clang::CXXMethodDecl *method_decl = ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) { if (m_allow_cxx && method_decl->isInstance()) { if (m_enforce_valid_object) { @@ -307,21 +330,6 @@ #undef OBJC_CAST_HACK_FROM } -namespace { -// Utility guard that calls a callback when going out of scope. -class OnExit { -public: - typedef std::function<void(void)> Callback; - - OnExit(Callback const &callback) : m_callback(callback) {} - - ~OnExit() { m_callback(); } - -private: - Callback m_callback; -}; -} // namespace - bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) { if (Target *target = exe_ctx.GetTargetPtr()) { @@ -377,7 +385,8 @@ } void ClangUserExpression::UpdateLanguageForExpr( - DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) { + DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, + std::vector<std::string> modules_to_import, bool for_completion) { m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown; std::string prefix = m_expr_prefix; @@ -385,8 +394,8 @@ if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { m_transformed_text = m_expr_text; } else { - std::unique_ptr<ExpressionSourceCode> source_code( - ExpressionSourceCode::CreateWrapped(prefix.c_str(), + std::unique_ptr<ClangExpressionSourceCode> source_code( + ClangExpressionSourceCode::CreateWrapped(prefix.c_str(), m_expr_text.c_str())); if (m_in_cplusplus_method) @@ -397,7 +406,8 @@ m_expr_lang = lldb::eLanguageTypeC; if (!source_code->GetText(m_transformed_text, m_expr_lang, - m_in_static_method, exe_ctx)) { + m_in_static_method, exe_ctx, !m_ctx_obj, + for_completion, modules_to_import)) { diagnostic_manager.PutString(eDiagnosticSeverityError, "couldn't construct expression body"); return; @@ -409,14 +419,73 @@ std::size_t original_end; bool found_bounds = source_code->GetOriginalBodyBounds( m_transformed_text, m_expr_lang, original_start, original_end); - if (found_bounds) { + if (found_bounds) m_user_expression_start_pos = original_start; - } } } +static bool SupportsCxxModuleImport(lldb::LanguageType language) { + switch (language) { + case lldb::eLanguageTypeC_plus_plus: + case lldb::eLanguageTypeC_plus_plus_03: + case lldb::eLanguageTypeC_plus_plus_11: + case lldb::eLanguageTypeC_plus_plus_14: + case lldb::eLanguageTypeObjC_plus_plus: + return true; + default: + return false; + } +} + +std::vector<std::string> +ClangUserExpression::GetModulesToImport(ExecutionContext &exe_ctx) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + + if (!SupportsCxxModuleImport(Language())) + return {}; + + Target *target = exe_ctx.GetTargetPtr(); + if (!target || !target->GetEnableImportStdModule()) + return {}; + + StackFrame *frame = exe_ctx.GetFramePtr(); + if (!frame) + return {}; + + Block *block = frame->GetFrameBlock(); + if (!block) + return {}; + + SymbolContext sc; + block->CalculateSymbolContext(&sc); + if (!sc.comp_unit) + return {}; + + if (log) { + for (const SourceModule &m : sc.comp_unit->GetImportedModules()) { + LLDB_LOG(log, "Found module in compile unit: {0:$[.]} - include dir: {1}", + llvm::make_range(m.path.begin(), m.path.end()), m.search_path); + } + } + + for (const SourceModule &m : sc.comp_unit->GetImportedModules()) + m_include_directories.push_back(m.search_path); + + // Check if we imported 'std' or any of its submodules. + // We currently don't support importing any other modules in the expression + // parser. + for (const SourceModule &m : sc.comp_unit->GetImportedModules()) + if (!m.path.empty() && m.path.front() == "std") + return {"std"}; + + return {}; +} + bool ClangUserExpression::PrepareForParsing( - DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) { + DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, + bool for_completion) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + InstallContext(exe_ctx); if (!SetupPersistentState(diagnostic_manager, exe_ctx)) @@ -437,7 +506,14 @@ SetupDeclVendor(exe_ctx, m_target); - UpdateLanguageForExpr(diagnostic_manager, exe_ctx); + std::vector<std::string> used_modules = GetModulesToImport(exe_ctx); + m_imported_cpp_modules = !used_modules.empty(); + + LLDB_LOG(log, "List of imported modules in expression: {0}", + llvm::make_range(used_modules.begin(), used_modules.end())); + + UpdateLanguageForExpr(diagnostic_manager, exe_ctx, used_modules, + for_completion); return true; } @@ -448,7 +524,7 @@ bool generate_debug_info) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); - if (!PrepareForParsing(diagnostic_manager, exe_ctx)) + if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false)) return false; if (log) @@ -469,13 +545,13 @@ // Parse the expression // - m_materializer_ap.reset(new Materializer()); + m_materializer_up.reset(new Materializer()); ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory); - OnExit on_exit([this]() { ResetDeclMap(); }); + auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); }); - if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get())) { + if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) { diagnostic_manager.PutString( eDiagnosticSeverityError, "current process state is unsuitable for expression parsing"); @@ -496,7 +572,8 @@ // succeeds or the rewrite parser we might make if it fails. But the // parser_sp will never be empty. - ClangExpressionParser parser(exe_scope, *this, generate_debug_info); + ClangExpressionParser parser(exe_scope, *this, generate_debug_info, + m_include_directories); unsigned num_errors = parser.Parse(diagnostic_manager); @@ -509,7 +586,7 @@ size_t fixed_end; const std::string &fixed_expression = diagnostic_manager.GetFixedExpression(); - if (ExpressionSourceCode::GetOriginalBodyBounds( + if (ClangExpressionSourceCode::GetOriginalBodyBounds( fixed_expression, m_expr_lang, fixed_start, fixed_end)) m_fixed_text = fixed_expression.substr(fixed_start, fixed_end - fixed_start); @@ -518,7 +595,7 @@ return false; } - ////////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// // Prepare the output of the parser for execution, evaluating it statically // if possible // @@ -597,25 +674,23 @@ return true; } -//------------------------------------------------------------------ /// Converts an absolute position inside a given code string into /// a column/line pair. /// -/// @param[in] abs_pos +/// \param[in] abs_pos /// A absolute position in the code string that we want to convert /// to a column/line pair. /// -/// @param[in] code +/// \param[in] code /// A multi-line string usually representing source code. /// -/// @param[out] line +/// \param[out] line /// The line in the code that contains the given absolute position. /// The first line in the string is indexed as 1. /// -/// @param[out] column +/// \param[out] column /// The column in the line that contains the absolute position. /// The first character in a line is indexed as 0. -//------------------------------------------------------------------ static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code, unsigned &line, unsigned &column) { // Reset to code position to beginning of the file. @@ -648,7 +723,7 @@ // correct. DiagnosticManager diagnostic_manager; - if (!PrepareForParsing(diagnostic_manager, exe_ctx)) + if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true)) return false; if (log) @@ -658,13 +733,13 @@ // Parse the expression // - m_materializer_ap.reset(new Materializer()); + m_materializer_up.reset(new Materializer()); ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true); - OnExit on_exit([this]() { ResetDeclMap(); }); + auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); }); - if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get())) { + if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) { diagnostic_manager.PutString( eDiagnosticSeverityError, "current process state is unsuitable for expression parsing"); @@ -734,7 +809,15 @@ Status object_ptr_error; - object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error); + if (m_ctx_obj) { + AddressType address_type; + object_ptr = m_ctx_obj->GetAddressOf(false, &address_type); + if (object_ptr == LLDB_INVALID_ADDRESS || + address_type != eAddressTypeLoad) + object_ptr_error.SetErrorString("Can't get context object's " + "debuggee address"); + } else + object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error); if (!object_ptr_error.Success()) { exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf( @@ -777,9 +860,11 @@ void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap( ExecutionContext &exe_ctx, Materializer::PersistentVariableDelegate &delegate, - bool keep_result_in_memory) { + bool keep_result_in_memory, + ValueObject *ctx_obj) { m_expr_decl_map_up.reset( - new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx)); + new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx, + ctx_obj)); } clang::ASTConsumer * @@ -792,7 +877,7 @@ } void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() { - if (m_result_synthesizer_up.get()) { + if (m_result_synthesizer_up) { m_result_synthesizer_up->CommitPersistentDecls(); } }
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h index 7e4cba6..24c152b 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h
@@ -1,9 +1,8 @@ //===-- ClangUserExpression.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,8 +28,7 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class ClangUserExpression ClangUserExpression.h +/// \class ClangUserExpression ClangUserExpression.h /// "lldb/Expression/ClangUserExpression.h" Encapsulates a single expression /// for use with Clang /// @@ -38,9 +36,13 @@ /// and as a backend for the expr command. ClangUserExpression encapsulates /// the objects needed to parse and interpret or JIT an expression. It uses /// the Clang parser to produce LLVM IR from the expression. -//---------------------------------------------------------------------- class ClangUserExpression : public LLVMUserExpression { public: + /// LLVM-style RTTI support. + static bool classof(const Expression *E) { + return E->getKind() == eKindClangUserExpression; + } + enum { kDefaultTimeout = 500000u }; class ClangUserExpressionHelper : public ClangExpressionHelper { @@ -50,10 +52,8 @@ ~ClangUserExpressionHelper() override = default; - //------------------------------------------------------------------ /// Return the object that the parser should use when resolving external /// values. May be NULL if everything should be self-contained. - //------------------------------------------------------------------ ClangExpressionDeclMap *DeclMap() override { return m_expr_decl_map_up.get(); } @@ -62,16 +62,15 @@ void ResetDeclMap(ExecutionContext &exe_ctx, Materializer::PersistentVariableDelegate &result_delegate, - bool keep_result_in_memory); + bool keep_result_in_memory, + ValueObject *ctx_obj); - //------------------------------------------------------------------ /// Return the object that the parser should allow to access ASTs. May be /// NULL if the ASTs do not need to be transformed. /// - /// @param[in] passthrough + /// \param[in] passthrough /// The ASTConsumer that the returned transformer should send /// the ASTs to after transformation. - //------------------------------------------------------------------ clang::ASTConsumer * ASTTransformer(clang::ASTConsumer *passthrough) override; @@ -88,53 +87,55 @@ bool m_top_level; }; - //------------------------------------------------------------------ /// Constructor /// - /// @param[in] expr + /// \param[in] expr /// The expression to parse. /// - /// @param[in] expr_prefix + /// \param[in] expr_prefix /// If non-NULL, a C string containing translation-unit level /// definitions to be included when the expression is parsed. /// - /// @param[in] language + /// \param[in] language /// If not eLanguageTypeUnknown, a language to use when parsing /// the expression. Currently restricted to those languages /// supported by Clang. /// - /// @param[in] desired_type + /// \param[in] desired_type /// If not eResultTypeAny, the type to use for the expression /// result. - //------------------------------------------------------------------ + /// + /// \param[in] ctx_obj + /// The object (if any) in which context the expression + /// must be evaluated. For details see the comment to + /// `UserExpression::Evaluate`. ClangUserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, ResultType desired_type, - const EvaluateExpressionOptions &options); + const EvaluateExpressionOptions &options, + ValueObject *ctx_obj); ~ClangUserExpression() override; - //------------------------------------------------------------------ /// Parse the expression /// - /// @param[in] diagnostic_manager + /// \param[in] diagnostic_manager /// A diagnostic manager to report parse errors and warnings to. /// - /// @param[in] exe_ctx + /// \param[in] exe_ctx /// The execution context to use when looking up entities that /// are needed for parsing (locations of functions, types of /// variables, persistent variables, etc.) /// - /// @param[in] execution_policy + /// \param[in] execution_policy /// Determines whether interpretation is possible or mandatory. /// - /// @param[in] keep_result_in_memory + /// \param[in] keep_result_in_memory /// True if the resulting persistent variable should reside in /// target memory, if applicable. /// - /// @return + /// \return /// True on success (no errors); false otherwise. - //------------------------------------------------------------------ bool Parse(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, lldb_private::ExecutionPolicy execution_policy, bool keep_result_in_memory, bool generate_debug_info) override; @@ -154,17 +155,18 @@ Materializer::PersistentVariableDelegate &result_delegate, bool keep_result_in_memory) { m_type_system_helper.ResetDeclMap(exe_ctx, result_delegate, - keep_result_in_memory); + keep_result_in_memory, + m_ctx_obj); } lldb::ExpressionVariableSP GetResultAfterDematerialization(ExecutionContextScope *exe_scope) override; + bool DidImportCxxModules() const { return m_imported_cpp_modules; } + private: - //------------------------------------------------------------------ /// Populate m_in_cplusplus_method and m_in_objectivec_method based on the /// environment. - //------------------------------------------------------------------ void ScanContext(ExecutionContext &exe_ctx, lldb_private::Status &err) override; @@ -173,12 +175,15 @@ lldb::addr_t struct_address, DiagnosticManager &diagnostic_manager) override; + std::vector<std::string> GetModulesToImport(ExecutionContext &exe_ctx); void UpdateLanguageForExpr(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx); + ExecutionContext &exe_ctx, + std::vector<std::string> modules_to_import, + bool for_completion); bool SetupPersistentState(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx); bool PrepareForParsing(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx); + ExecutionContext &exe_ctx, bool for_completion); ClangUserExpressionHelper m_type_system_helper; @@ -199,12 +204,21 @@ /// The language type of the current expression. lldb::LanguageType m_expr_lang = lldb::eLanguageTypeUnknown; + /// The include directories that should be used when parsing the expression. + std::vector<ConstString> m_include_directories; /// The absolute character position in the transformed source code where the /// user code (as typed by the user) starts. If the variable is empty, then we /// were not able to calculate this position. llvm::Optional<size_t> m_user_expression_start_pos; ResultDelegate m_result_delegate; + + /// The object (if any) in which context the expression is evaluated. + /// See the comment to `UserExpression::Evaluate` for details. + ValueObject *m_ctx_obj; + + /// True iff this expression explicitly imported C++ modules. + bool m_imported_cpp_modules = false; }; } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp index fe6ca45..5eec224 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp
@@ -1,15 +1,15 @@ //===-- ClangUtilityFunction.cpp ---------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "ClangUtilityFunction.h" #include "ClangExpressionDeclMap.h" #include "ClangExpressionParser.h" +#include "ClangExpressionSourceCode.h" #include <stdio.h> #if HAVE_SYS_TYPES_H @@ -19,7 +19,6 @@ #include "lldb/Core/Module.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Expression/ExpressionSourceCode.h" #include "lldb/Expression/IRExecutionUnit.h" #include "lldb/Host/Host.h" #include "lldb/Target/ExecutionContext.h" @@ -30,33 +29,33 @@ using namespace lldb_private; -//------------------------------------------------------------------ /// Constructor /// -/// @param[in] text +/// \param[in] text /// The text of the function. Must be a full translation unit. /// -/// @param[in] name +/// \param[in] name /// The name of the function, as used in the text. -//------------------------------------------------------------------ ClangUtilityFunction::ClangUtilityFunction(ExecutionContextScope &exe_scope, const char *text, const char *name) - : UtilityFunction(exe_scope, text, name) {} + : UtilityFunction(exe_scope, text, name, eKindClangUtilityFunction) { + m_function_text.assign(ClangExpressionSourceCode::g_expression_prefix); + if (text && text[0]) + m_function_text.append(text); +} ClangUtilityFunction::~ClangUtilityFunction() {} -//------------------------------------------------------------------ /// Install the utility function into a process /// -/// @param[in] diagnostic_manager +/// \param[in] diagnostic_manager /// A diagnostic manager to report errors and warnings to. /// -/// @param[in] exe_ctx +/// \param[in] exe_ctx /// The execution context to install the utility function to. /// -/// @return +/// \return /// True on success (no errors); false otherwise. -//------------------------------------------------------------------ bool ClangUtilityFunction::Install(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) { if (m_jit_start_addr != LLDB_INVALID_ADDRESS) { @@ -91,7 +90,7 @@ ResetDeclMap(exe_ctx, keep_result_in_memory); - if (!DeclMap()->WillParse(exe_ctx, NULL)) { + if (!DeclMap()->WillParse(exe_ctx, nullptr)) { diagnostic_manager.PutString( eDiagnosticSeverityError, "current process state is unsuitable for expression parsing"); @@ -157,5 +156,6 @@ void ClangUtilityFunction::ClangUtilityFunctionHelper::ResetDeclMap( ExecutionContext &exe_ctx, bool keep_result_in_memory) { m_expr_decl_map_up.reset( - new ClangExpressionDeclMap(keep_result_in_memory, nullptr, exe_ctx)); + new ClangExpressionDeclMap(keep_result_in_memory, nullptr, exe_ctx, + nullptr)); }
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.h index b0650f0..70ebb2f 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.h
@@ -1,9 +1,8 @@ //===-- ClangUtilityFunction.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,8 +22,7 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class ClangUtilityFunction ClangUtilityFunction.h +/// \class ClangUtilityFunction ClangUtilityFunction.h /// "lldb/Expression/ClangUtilityFunction.h" Encapsulates a single expression /// for use with Clang /// @@ -34,19 +32,21 @@ /// functions can perform error-checking for ClangUserExpressions, or can /// simply provide a way to push a function into the target for the debugger /// to call later on. -//---------------------------------------------------------------------- class ClangUtilityFunction : public UtilityFunction { public: + /// LLVM-style RTTI support. + static bool classof(const Expression *E) { + return E->getKind() == eKindClangUtilityFunction; + } + class ClangUtilityFunctionHelper : public ClangExpressionHelper { public: ClangUtilityFunctionHelper() {} ~ClangUtilityFunctionHelper() override {} - //------------------------------------------------------------------ /// Return the object that the parser should use when resolving external /// values. May be NULL if everything should be self-contained. - //------------------------------------------------------------------ ClangExpressionDeclMap *DeclMap() override { return m_expr_decl_map_up.get(); } @@ -55,14 +55,12 @@ void ResetDeclMap(ExecutionContext &exe_ctx, bool keep_result_in_memory); - //------------------------------------------------------------------ /// Return the object that the parser should allow to access ASTs. May be /// NULL if the ASTs do not need to be transformed. /// - /// @param[in] passthrough + /// \param[in] passthrough /// The ASTConsumer that the returned transformer should send /// the ASTs to after transformation. - //------------------------------------------------------------------ clang::ASTConsumer * ASTTransformer(clang::ASTConsumer *passthrough) override { return nullptr; @@ -71,15 +69,13 @@ private: std::unique_ptr<ClangExpressionDeclMap> m_expr_decl_map_up; }; - //------------------------------------------------------------------ /// Constructor /// - /// @param[in] text + /// \param[in] text /// The text of the function. Must be a full translation unit. /// - /// @param[in] name + /// \param[in] name /// The name of the function, as used in the text. - //------------------------------------------------------------------ ClangUtilityFunction(ExecutionContextScope &exe_scope, const char *text, const char *name);
diff --git a/src/llvm-project/lldb/source/Expression/IRDynamicChecks.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.cpp similarity index 78% rename from src/llvm-project/lldb/source/Expression/IRDynamicChecks.cpp rename to src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.cpp index 20431d5..f8e004f 100644 --- a/src/llvm-project/lldb/source/Expression/IRDynamicChecks.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.cpp
@@ -1,9 +1,8 @@ //===-- IRDynamicChecks.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,17 +14,18 @@ #include "llvm/IR/Value.h" #include "llvm/Support/raw_ostream.h" -#include "lldb/Expression/IRDynamicChecks.h" +#include "IRDynamicChecks.h" #include "lldb/Expression/UtilityFunction.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Log.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + using namespace llvm; using namespace lldb_private; @@ -41,12 +41,13 @@ " unsigned char $__lldb_local_val = *$__lldb_arg_ptr;\n" "}"; -DynamicCheckerFunctions::DynamicCheckerFunctions() = default; +ClangDynamicCheckerFunctions::ClangDynamicCheckerFunctions() + : DynamicCheckerFunctions(DCF_Clang) {} -DynamicCheckerFunctions::~DynamicCheckerFunctions() = default; +ClangDynamicCheckerFunctions::~ClangDynamicCheckerFunctions() = default; -bool DynamicCheckerFunctions::Install(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx) { +bool ClangDynamicCheckerFunctions::Install( + DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) { Status error; m_valid_pointer_check.reset( exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( @@ -62,7 +63,7 @@ if (process) { ObjCLanguageRuntime *objc_language_runtime = - process->GetObjCLanguageRuntime(); + ObjCLanguageRuntime::Get(*process); if (objc_language_runtime) { m_objc_object_check.reset(objc_language_runtime->CreateObjectChecker( @@ -76,8 +77,8 @@ return true; } -bool DynamicCheckerFunctions::DoCheckersExplainStop(lldb::addr_t addr, - Stream &message) { +bool ClangDynamicCheckerFunctions::DoCheckersExplainStop(lldb::addr_t addr, + Stream &message) { // FIXME: We have to get the checkers to know why they scotched the call in // more detail, // so we can print a better message here. @@ -103,8 +104,7 @@ return s; } -//---------------------------------------------------------------------- -/// @class Instrumenter IRDynamicChecks.cpp +/// \class Instrumenter IRDynamicChecks.cpp /// Finds and instruments individual LLVM IR instructions /// /// When instrumenting LLVM IR, it is frequently desirable to first search for @@ -130,38 +130,32 @@ /// /// - InspectFunction [default: iterates through the basic blocks in a /// function calling InspectBasicBlock] -//---------------------------------------------------------------------- class Instrumenter { public: - //------------------------------------------------------------------ /// Constructor /// - /// @param[in] module + /// \param[in] module /// The module being instrumented. - //------------------------------------------------------------------ - Instrumenter(llvm::Module &module, DynamicCheckerFunctions &checker_functions) - : m_module(module), m_checker_functions(checker_functions), + Instrumenter(llvm::Module &module, + std::shared_ptr<UtilityFunction> checker_function) + : m_module(module), m_checker_function(checker_function), m_i8ptr_ty(nullptr), m_intptr_ty(nullptr) {} virtual ~Instrumenter() = default; - //------------------------------------------------------------------ /// Inspect a function to find instructions to instrument /// - /// @param[in] function + /// \param[in] function /// The function to inspect. /// - /// @return + /// \return /// True on success; false on error. - //------------------------------------------------------------------ bool Inspect(llvm::Function &function) { return InspectFunction(function); } - //------------------------------------------------------------------ /// Instrument all the instructions found by Inspect() /// - /// @return + /// \return /// True on success; false on error. - //------------------------------------------------------------------ bool Instrument() { for (InstIterator ii = m_to_instrument.begin(), last_ii = m_to_instrument.end(); @@ -174,48 +168,40 @@ } protected: - //------------------------------------------------------------------ /// Add instrumentation to a single instruction /// - /// @param[in] inst + /// \param[in] inst /// The instruction to be instrumented. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ virtual bool InstrumentInstruction(llvm::Instruction *inst) = 0; - //------------------------------------------------------------------ /// Register a single instruction to be instrumented /// - /// @param[in] inst + /// \param[in] inst /// The instruction to be instrumented. - //------------------------------------------------------------------ void RegisterInstruction(llvm::Instruction &i) { m_to_instrument.push_back(&i); } - //------------------------------------------------------------------ /// Determine whether a single instruction is interesting to instrument, /// and, if so, call RegisterInstruction /// - /// @param[in] i + /// \param[in] i /// The instruction to be inspected. /// - /// @return + /// \return /// False if there was an error scanning; true otherwise. - //------------------------------------------------------------------ virtual bool InspectInstruction(llvm::Instruction &i) { return true; } - //------------------------------------------------------------------ /// Scan a basic block to see if any instructions are interesting /// - /// @param[in] bb + /// \param[in] bb /// The basic block to be inspected. /// - /// @return + /// \return /// False if there was an error scanning; true otherwise. - //------------------------------------------------------------------ virtual bool InspectBasicBlock(llvm::BasicBlock &bb) { for (llvm::BasicBlock::iterator ii = bb.begin(), last_ii = bb.end(); ii != last_ii; ++ii) { @@ -226,15 +212,13 @@ return true; } - //------------------------------------------------------------------ /// Scan a function to see if any instructions are interesting /// - /// @param[in] f + /// \param[in] f /// The function to be inspected. /// - /// @return + /// \return /// False if there was an error scanning; true otherwise. - //------------------------------------------------------------------ virtual bool InspectFunction(llvm::Function &f) { for (llvm::Function::iterator bbi = f.begin(), last_bbi = f.end(); bbi != last_bbi; ++bbi) { @@ -245,17 +229,15 @@ return true; } - //------------------------------------------------------------------ /// Build a function pointer for a function with signature void /// (*)(uint8_t*) with a given address /// - /// @param[in] start_address + /// \param[in] start_address /// The address of the function. /// - /// @return + /// \return /// The function pointer, for use in a CallInst. - //------------------------------------------------------------------ - llvm::Value *BuildPointerValidatorFunc(lldb::addr_t start_address) { + llvm::FunctionCallee BuildPointerValidatorFunc(lldb::addr_t start_address) { llvm::Type *param_array[1]; param_array[0] = const_cast<llvm::PointerType *>(GetI8PtrTy()); @@ -267,20 +249,18 @@ PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty); Constant *fun_addr_int = ConstantInt::get(GetIntptrTy(), start_address, false); - return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty); + return {fun_ty, ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty)}; } - //------------------------------------------------------------------ /// Build a function pointer for a function with signature void /// (*)(uint8_t*, uint8_t*) with a given address /// - /// @param[in] start_address + /// \param[in] start_address /// The address of the function. /// - /// @return + /// \return /// The function pointer, for use in a CallInst. - //------------------------------------------------------------------ - llvm::Value *BuildObjectCheckerFunc(lldb::addr_t start_address) { + llvm::FunctionCallee BuildObjectCheckerFunc(lldb::addr_t start_address) { llvm::Type *param_array[2]; param_array[0] = const_cast<llvm::PointerType *>(GetI8PtrTy()); @@ -293,7 +273,7 @@ PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty); Constant *fun_addr_int = ConstantInt::get(GetIntptrTy(), start_address, false); - return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty); + return {fun_ty, ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty)}; } PointerType *GetI8PtrTy() { @@ -319,8 +299,8 @@ InstVector m_to_instrument; ///< List of instructions the inspector found llvm::Module &m_module; ///< The module which is being instrumented - DynamicCheckerFunctions - &m_checker_functions; ///< The dynamic checker functions for the process + std::shared_ptr<UtilityFunction> + m_checker_function; ///< The dynamic checker function for the process private: PointerType *m_i8ptr_ty; @@ -330,8 +310,8 @@ class ValidPointerChecker : public Instrumenter { public: ValidPointerChecker(llvm::Module &module, - DynamicCheckerFunctions &checker_functions) - : Instrumenter(module, checker_functions), + std::shared_ptr<UtilityFunction> checker_function) + : Instrumenter(module, checker_function), m_valid_pointer_check_func(nullptr) {} ~ValidPointerChecker() override = default; @@ -345,8 +325,8 @@ PrintValue(inst).c_str()); if (!m_valid_pointer_check_func) - m_valid_pointer_check_func = BuildPointerValidatorFunc( - m_checker_functions.m_valid_pointer_check->StartAddress()); + m_valid_pointer_check_func = + BuildPointerValidatorFunc(m_checker_function->StartAddress()); llvm::Value *dereferenced_ptr = nullptr; @@ -383,14 +363,14 @@ } private: - llvm::Value *m_valid_pointer_check_func; + llvm::FunctionCallee m_valid_pointer_check_func; }; class ObjcObjectChecker : public Instrumenter { public: ObjcObjectChecker(llvm::Module &module, - DynamicCheckerFunctions &checker_functions) - : Instrumenter(module, checker_functions), + std::shared_ptr<UtilityFunction> checker_function) + : Instrumenter(module, checker_function), m_objc_object_check_func(nullptr) {} ~ObjcObjectChecker() override = default; @@ -414,8 +394,8 @@ // InspectInstruction wouldn't have registered it if (!m_objc_object_check_func) - m_objc_object_check_func = BuildObjectCheckerFunc( - m_checker_functions.m_objc_object_check->StartAddress()); + m_objc_object_check_func = + BuildObjectCheckerFunc(m_checker_function->StartAddress()); // id objc_msgSend(id theReceiver, SEL theSelector, ...) @@ -425,8 +405,15 @@ switch (msgSend_types[inst]) { case eMsgSend: case eMsgSend_fpret: - target_object = call_inst->getArgOperand(0); - selector = call_inst->getArgOperand(1); + // On arm64, clang uses objc_msgSend for scalar and struct return + // calls. The call instruction will record which was used. + if (call_inst->hasStructRetAttr()) { + target_object = call_inst->getArgOperand(1); + selector = call_inst->getArgOperand(2); + } else { + target_object = call_inst->getArgOperand(0); + selector = call_inst->getArgOperand(1); + } break; case eMsgSend_stret: target_object = call_inst->getArgOperand(1); @@ -545,11 +532,11 @@ } private: - llvm::Value *m_objc_object_check_func; + llvm::FunctionCallee m_objc_object_check_func; }; -IRDynamicChecks::IRDynamicChecks(DynamicCheckerFunctions &checker_functions, - const char *func_name) +IRDynamicChecks::IRDynamicChecks( + ClangDynamicCheckerFunctions &checker_functions, const char *func_name) : ModulePass(ID), m_func_name(func_name), m_checker_functions(checker_functions) {} @@ -568,7 +555,7 @@ } if (m_checker_functions.m_valid_pointer_check) { - ValidPointerChecker vpc(M, m_checker_functions); + ValidPointerChecker vpc(M, m_checker_functions.m_valid_pointer_check); if (!vpc.Inspect(*function)) return false; @@ -578,7 +565,7 @@ } if (m_checker_functions.m_objc_object_check) { - ObjcObjectChecker ooc(M, m_checker_functions); + ObjcObjectChecker ooc(M, m_checker_functions.m_objc_object_check); if (!ooc.Inspect(*function)) return false;
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.h new file mode 100644 index 0000000..60c0691 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.h
@@ -0,0 +1,131 @@ +//===-- IRDynamicChecks.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 liblldb_IRDynamicChecks_h_ +#define liblldb_IRDynamicChecks_h_ + +#include "lldb/Expression/DynamicCheckerFunctions.h" +#include "lldb/lldb-types.h" +#include "llvm/Pass.h" + +namespace llvm { +class BasicBlock; +class Module; +} + +namespace lldb_private { + +class ExecutionContext; +class Stream; + +class ClangDynamicCheckerFunctions + : public lldb_private::DynamicCheckerFunctions { +public: + /// Constructor + ClangDynamicCheckerFunctions(); + + /// Destructor + virtual ~ClangDynamicCheckerFunctions(); + + static bool classof(const DynamicCheckerFunctions *checker_funcs) { + return checker_funcs->GetKind() == DCF_Clang; + } + + /// Install the utility functions into a process. This binds the instance + /// of DynamicCheckerFunctions to that process. + /// + /// \param[in] diagnostic_manager + /// A diagnostic manager to report errors to. + /// + /// \param[in] exe_ctx + /// The execution context to install the functions into. + /// + /// \return + /// True on success; false on failure, or if the functions have + /// already been installed. + bool Install(DiagnosticManager &diagnostic_manager, + ExecutionContext &exe_ctx) override; + + bool DoCheckersExplainStop(lldb::addr_t addr, Stream &message) override; + + std::shared_ptr<UtilityFunction> m_valid_pointer_check; + std::shared_ptr<UtilityFunction> m_objc_object_check; +}; + +/// \class IRDynamicChecks IRDynamicChecks.h +/// "lldb/Expression/IRDynamicChecks.h" Adds dynamic checks to a user-entered +/// expression to reduce its likelihood of crashing +/// +/// When an IR function is executed in the target process, it may cause +/// crashes or hangs by dereferencing NULL pointers, trying to call +/// Objective-C methods on objects that do not respond to them, and so forth. +/// +/// IRDynamicChecks adds calls to the functions in DynamicCheckerFunctions to +/// appropriate locations in an expression's IR. +class IRDynamicChecks : public llvm::ModulePass { +public: + /// Constructor + /// + /// \param[in] checker_functions + /// The checker functions for the target process. + /// + /// \param[in] func_name + /// The name of the function to prepare for execution in the target. + /// + /// \param[in] decl_map + /// The mapping used to look up entities in the target process. In + /// this case, used to find objc_msgSend + IRDynamicChecks(ClangDynamicCheckerFunctions &checker_functions, + const char *func_name = "$__lldb_expr"); + + /// Destructor + ~IRDynamicChecks() override; + + /// Run this IR transformer on a single module + /// + /// \param[in] M + /// The module to run on. This module is searched for the function + /// $__lldb_expr, and that function is passed to the passes one by + /// one. + /// + /// \return + /// True on success; false otherwise + bool runOnModule(llvm::Module &M) override; + + /// Interface stub + void assignPassManager( + llvm::PMStack &PMS, + llvm::PassManagerType T = llvm::PMT_ModulePassManager) override; + + /// Returns PMT_ModulePassManager + llvm::PassManagerType getPotentialPassManagerType() const override; + +private: + /// A basic block-level pass to find all pointer dereferences and + /// validate them before use. + + /// The top-level pass implementation + /// + /// \param[in] M + /// The module currently being processed. + /// + /// \param[in] BB + /// The basic block currently being processed. + /// + /// \return + /// True on success; false otherwise + bool FindDataLoads(llvm::Module &M, llvm::BasicBlock &BB); + + std::string m_func_name; ///< The name of the function to add checks to + ClangDynamicCheckerFunctions + &m_checker_functions; ///< The checker functions for the process +}; + +} // namespace lldb_private + +#endif // liblldb_IRDynamicChecks_h_
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp index 3a7cd58..07acb2e 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp
@@ -1,9 +1,8 @@ //===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -61,7 +60,7 @@ static llvm::Value *FindEntryInstruction(llvm::Function *function) { if (function->empty()) - return NULL; + return nullptr; return function->getEntryBlock().getFirstNonPHIOrDbg(); } @@ -72,11 +71,12 @@ lldb_private::Stream &error_stream, const char *func_name) : ModulePass(ID), m_resolve_vars(resolve_vars), m_func_name(func_name), - m_module(NULL), m_decl_map(decl_map), m_CFStringCreateWithBytes(NULL), - m_sel_registerName(NULL), m_objc_getClass(NULL), m_intptr_ty(NULL), - m_error_stream(error_stream), - m_execution_unit(execution_unit), m_result_store(NULL), - m_result_is_pointer(false), m_reloc_placeholder(NULL), + m_module(nullptr), m_decl_map(decl_map), + m_CFStringCreateWithBytes(nullptr), m_sel_registerName(nullptr), + m_objc_getClass(nullptr), m_intptr_ty(nullptr), + m_error_stream(error_stream), m_execution_unit(execution_unit), + m_result_store(nullptr), m_result_is_pointer(false), + m_reloc_placeholder(nullptr), m_entry_instruction_finder(FindEntryInstruction) {} /* Handy utility functions used at several places in the code */ @@ -117,7 +117,7 @@ module->getNamedMetadata("clang.global.decl.ptrs"); if (!named_metadata) - return NULL; + return nullptr; unsigned num_nodes = named_metadata->getNumOperands(); unsigned node_index; @@ -126,7 +126,7 @@ llvm::MDNode *metadata_node = dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index)); if (!metadata_node) - return NULL; + return nullptr; if (metadata_node->getNumOperands() != 2) continue; @@ -139,14 +139,14 @@ mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1)); if (!constant_int) - return NULL; + return nullptr; uintptr_t ptr = constant_int->getZExtValue(); return reinterpret_cast<clang::NamedDecl *>(ptr); } - return NULL; + return nullptr; } clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) { @@ -165,7 +165,7 @@ ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable(); std::string result_name_str; - const char *result_name = NULL; + const char *result_name = nullptr; for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); @@ -343,8 +343,8 @@ GlobalVariable *new_result_global = new GlobalVariable( (*m_module), result_global->getType()->getElementType(), - false, /* not constant */ - GlobalValue::ExternalLinkage, NULL, /* no initializer */ + false, /* not constant */ + GlobalValue::ExternalLinkage, nullptr, /* no initializer */ m_result_name.GetCString()); // It's too late in compilation to create a new VarDecl for this, but we @@ -433,9 +433,11 @@ static lldb_private::ConstString g_CFStringCreateWithBytes_str( "CFStringCreateWithBytes"); + bool missing_weak = false; CFStringCreateWithBytes_addr = - m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str); - if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS) { + m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str, + missing_weak); + if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS || missing_weak) { if (log) log->PutCString("Couldn't find CFStringCreateWithBytes in the target"); @@ -478,18 +480,18 @@ ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5); - llvm::Type *CFSCWB_ty = + llvm::FunctionType *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false); // Build the constant containing the pointer to the function PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty); Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false); - m_CFStringCreateWithBytes = - ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty); + m_CFStringCreateWithBytes = { + CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)}; } - ConstantDataSequential *string_array = NULL; + ConstantDataSequential *string_array = nullptr; if (cstr) string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer()); @@ -734,7 +736,7 @@ } if (!cstr_array) - cstr_global = NULL; + cstr_global = nullptr; if (!RewriteObjCConstString(nsstring_global, cstr_global)) { if (log) @@ -857,9 +859,11 @@ if (!m_sel_registerName) { lldb::addr_t sel_registerName_addr; + bool missing_weak = false; static lldb_private::ConstString g_sel_registerName_str("sel_registerName"); - sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str); - if (sel_registerName_addr == LLDB_INVALID_ADDRESS) + sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str, + missing_weak); + if (sel_registerName_addr == LLDB_INVALID_ADDRESS || missing_weak) return false; if (log) @@ -881,14 +885,15 @@ ArrayRef<Type *> srN_arg_types(type_array, 1); - llvm::Type *srN_type = + llvm::FunctionType *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false); // Build the constant containing the pointer to the function PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type); Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false); - m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty); + m_sel_registerName = {srN_type, + ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)}; } Value *argument_array[1]; @@ -1026,9 +1031,11 @@ if (!m_objc_getClass) { lldb::addr_t objc_getClass_addr; + bool missing_weak = false; static lldb_private::ConstString g_objc_getClass_str("objc_getClass"); - objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str); - if (objc_getClass_addr == LLDB_INVALID_ADDRESS) + objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str, + missing_weak); + if (objc_getClass_addr == LLDB_INVALID_ADDRESS || missing_weak) return false; if (log) @@ -1043,14 +1050,15 @@ ArrayRef<Type *> ogC_arg_types(type_array, 1); - llvm::Type *ogC_type = + llvm::FunctionType *ogC_type = FunctionType::get(class_type, ogC_arg_types, false); // Build the constant containing the pointer to the function PointerType *ogC_ptr_ty = PointerType::getUnqual(ogC_type); Constant *ogC_addr_int = ConstantInt::get(m_intptr_ty, objc_getClass_addr, false); - m_objc_getClass = ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty); + m_objc_getClass = {ogC_type, + ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty)}; } Value *argument_array[1]; @@ -1148,8 +1156,8 @@ return false; GlobalVariable *persistent_global = new GlobalVariable( - (*m_module), alloc->getType(), false, /* not constant */ - GlobalValue::ExternalLinkage, NULL, /* no initializer */ + (*m_module), alloc->getType(), false, /* not constant */ + GlobalValue::ExternalLinkage, nullptr, /* no initializer */ alloc->getName().str()); // What we're going to do here is make believe this was a regular old @@ -1345,13 +1353,13 @@ std::string name(named_decl->getName().str()); clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl); - if (value_decl == NULL) + if (value_decl == nullptr) return false; lldb_private::CompilerType compiler_type(&value_decl->getASTContext(), value_decl->getType()); - const Type *value_type = NULL; + const Type *value_type = nullptr; if (name[0] == '$') { // The $__lldb_expr_result name indicates the return value has allocated @@ -1629,12 +1637,12 @@ } static bool isGuardVariableRef(Value *V) { - Constant *Old = NULL; + Constant *Old = nullptr; if (!(Old = dyn_cast<Constant>(V))) return false; - ConstantExpr *CE = NULL; + ConstantExpr *CE = nullptr; if ((CE = dyn_cast<ConstantExpr>(V))) { if (CE->getOpcode() != Instruction::BitCast) @@ -1929,8 +1937,8 @@ } for (element_index = 0; element_index < num_elements; ++element_index) { - const clang::NamedDecl *decl = NULL; - Value *value = NULL; + const clang::NamedDecl *decl = nullptr; + Value *value = nullptr; lldb::offset_t offset; lldb_private::ConstString name; @@ -2050,7 +2058,7 @@ std::string s; raw_string_ostream oss(s); - m_module->print(oss, NULL); + m_module->print(oss, nullptr); oss.flush(); @@ -2087,7 +2095,7 @@ m_reloc_placeholder = new llvm::GlobalVariable( (*m_module), int8_ty, false /* IsConstant */, GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty), - "reloc_placeholder", NULL /* InsertBefore */, + "reloc_placeholder", nullptr /* InsertBefore */, GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */); //////////////////////////////////////////////////////////// @@ -2109,7 +2117,7 @@ std::string s; raw_string_ostream oss(s); - m_module->print(oss, NULL); + m_module->print(oss, nullptr); oss.flush(); @@ -2244,7 +2252,7 @@ std::string s; raw_string_ostream oss(s); - m_module->print(oss, NULL); + m_module->print(oss, nullptr); oss.flush();
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h index c6c44b4..f87fd8a 100644 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h
@@ -1,10 +1,9 @@ //===-- IRForTarget.h ---------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,6 +16,7 @@ #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" #include "lldb/lldb-public.h" +#include "llvm/IR/DerivedTypes.h" #include "llvm/Pass.h" #include <functional> @@ -31,11 +31,9 @@ class GlobalValue; class GlobalVariable; class Instruction; -class IntegerType; class Module; class StoreInst; class DataLayout; -class Type; class Value; } @@ -45,8 +43,7 @@ class IRMemoryMap; } -//---------------------------------------------------------------------- -/// @class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h" +/// \class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h" /// Transforms the IR for a function to run in the target /// /// Once an expression has been parsed and converted to IR, it can run in two @@ -57,168 +54,143 @@ /// transformations to the IR which make it relocatable. These /// transformations are discussed in more detail next to their relevant /// functions. -//---------------------------------------------------------------------- class IRForTarget : public llvm::ModulePass { public: enum class LookupResult { Success, Fail, Ignore }; - //------------------------------------------------------------------ /// Constructor /// - /// @param[in] decl_map + /// \param[in] decl_map /// The list of externally-referenced variables for the expression, /// for use in looking up globals and allocating the argument /// struct. See the documentation for ClangExpressionDeclMap. /// - /// @param[in] resolve_vars + /// \param[in] resolve_vars /// True if the external variable references (including persistent /// variables) should be resolved. If not, only external functions /// are resolved. /// - /// @param[in] execution_policy + /// \param[in] execution_policy /// Determines whether an IR interpreter can be used to statically /// evaluate the expression. /// - /// @param[in] const_result + /// \param[in] const_result /// This variable is populated with the statically-computed result /// of the function, if it has no side-effects and the result can /// be computed statically. /// - /// @param[in] execution_unit + /// \param[in] execution_unit /// The holder for raw data associated with the expression. /// - /// @param[in] error_stream + /// \param[in] error_stream /// If non-NULL, a stream on which errors can be printed. /// - /// @param[in] func_name + /// \param[in] func_name /// The name of the function to prepare for execution in the target. - //------------------------------------------------------------------ IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Stream &error_stream, const char *func_name = "$__lldb_expr"); - //------------------------------------------------------------------ /// Destructor - //------------------------------------------------------------------ ~IRForTarget() override; - //------------------------------------------------------------------ /// Run this IR transformer on a single module /// /// Implementation of the llvm::ModulePass::runOnModule() function. /// - /// @param[in] llvm_module + /// \param[in] llvm_module /// The module to run on. This module is searched for the function /// $__lldb_expr, and that function is passed to the passes one by /// one. /// - /// @param[in] interpreter_error + /// \param[in] interpreter_error /// An error. If the expression fails to be interpreted, this error /// is set to a reason why. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool runOnModule(llvm::Module &llvm_module) override; - //------------------------------------------------------------------ /// Interface stub /// /// Implementation of the llvm::ModulePass::assignPassManager() function. - //------------------------------------------------------------------ void assignPassManager(llvm::PMStack &pass_mgr_stack, llvm::PassManagerType pass_mgr_type = llvm::PMT_ModulePassManager) override; - //------------------------------------------------------------------ /// Returns PMT_ModulePassManager /// /// Implementation of the llvm::ModulePass::getPotentialPassManagerType() /// function. - //------------------------------------------------------------------ llvm::PassManagerType getPotentialPassManagerType() const override; private: - //------------------------------------------------------------------ /// Ensures that the current function's linkage is set to external. /// Otherwise the JIT may not return an address for it. /// - /// @param[in] llvm_function + /// \param[in] llvm_function /// The function whose linkage is to be fixed. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ bool FixFunctionLinkage(llvm::Function &llvm_function); - //------------------------------------------------------------------ /// A module-level pass to replace all function pointers with their /// integer equivalents. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] llvm_module + /// \param[in] llvm_module /// The module currently being processed. /// - /// @param[in] llvm_function + /// \param[in] llvm_function /// The function currently being processed. /// - /// @return + /// \return /// True on success; false otherwise. - //------------------------------------------------------------------ bool HasSideEffects(llvm::Function &llvm_function); - //------------------------------------------------------------------ /// A function-level pass to check whether the function has side /// effects. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Get the address of a function, and a location to put the complete Value /// of the function if one is available. /// - /// @param[in] function + /// \param[in] function /// The function to find the location of. /// - /// @param[out] ptr + /// \param[out] ptr /// The location of the function in the target. /// - /// @param[out] name + /// \param[out] name /// The resolved name of the function (matters for intrinsics). /// - /// @param[out] value_ptr + /// \param[out] value_ptr /// A variable to put the function's completed Value* in, or NULL /// if the Value* shouldn't be stored anywhere. /// - /// @return + /// \return /// The pointer. - //------------------------------------------------------------------ LookupResult GetFunctionAddress(llvm::Function *function, uint64_t &ptr, lldb_private::ConstString &name, llvm::Constant **&value_ptr); - //------------------------------------------------------------------ /// A function-level pass to take the generated global value /// $__lldb_expr_result and make it into a persistent variable. Also see /// ASTResultSynthesizer. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Find the NamedDecl corresponding to a Value. This interface is exposed /// for the IR interpreter. /// - /// @param[in] module + /// \param[in] module /// The module containing metadata to search /// - /// @param[in] global + /// \param[in] global /// The global entity to search for /// - /// @return + /// \return /// The corresponding variable declaration - //------------------------------------------------------------------ public: static clang::NamedDecl *DeclForGlobal(const llvm::GlobalValue *global_val, llvm::Module *module); @@ -226,75 +198,62 @@ private: clang::NamedDecl *DeclForGlobal(llvm::GlobalValue *global); - //------------------------------------------------------------------ /// Set the constant result variable m_const_result to the provided /// constant, assuming it can be evaluated. The result variable will be /// reset to NULL later if the expression has side effects. /// - /// @param[in] initializer + /// \param[in] initializer /// The constant initializer for the variable. /// - /// @param[in] name + /// \param[in] name /// The name of the result variable. /// - /// @param[in] type + /// \param[in] type /// The Clang type of the result variable. - //------------------------------------------------------------------ void MaybeSetConstantResult(llvm::Constant *initializer, - const lldb_private::ConstString &name, + lldb_private::ConstString name, lldb_private::TypeFromParser type); - //------------------------------------------------------------------ /// If the IR represents a cast of a variable, set m_const_result to the /// result of the cast. The result variable will be reset to /// NULL latger if the expression has side effects. /// - /// @param[in] type + /// \param[in] type /// The Clang type of the result variable. - //------------------------------------------------------------------ void MaybeSetCastResult(lldb_private::TypeFromParser type); - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] llvm_function + /// \param[in] llvm_function /// The function currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool CreateResultVariable(llvm::Function &llvm_function); - //------------------------------------------------------------------ /// A module-level pass to find Objective-C constant strings and /// transform them to calls to CFStringCreateWithBytes. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Rewrite a single Objective-C constant string. /// - /// @param[in] NSStr + /// \param[in] NSStr /// The constant NSString to be transformed /// - /// @param[in] CStr + /// \param[in] CStr /// The constant C string inside the NSString. This will be /// passed as the bytes argument to CFStringCreateWithBytes. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RewriteObjCConstString(llvm::GlobalVariable *NSStr, llvm::GlobalVariable *CStr); - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RewriteObjCConstStrings(); - //------------------------------------------------------------------ /// A basic block-level pass to find all Objective-C method calls and /// rewrite them to use sel_registerName instead of statically allocated /// selectors. The reason is that the selectors are created on the @@ -302,59 +261,47 @@ /// section and prepare them. This doesn't happen when code is copied into /// the target, though, and there's no easy way to induce the runtime to /// scan them. So instead we get our selectors from sel_registerName. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Replace a single selector reference /// - /// @param[in] selector_load + /// \param[in] selector_load /// The load of the statically-allocated selector. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RewriteObjCSelector(llvm::Instruction *selector_load); - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] basic_block + /// \param[in] basic_block /// The basic block currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RewriteObjCSelectors(llvm::BasicBlock &basic_block); - //------------------------------------------------------------------ /// A basic block-level pass to find all Objective-C class references that /// use the old-style Objective-C runtime and rewrite them to use /// class_getClass instead of statically allocated class references. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Replace a single old-style class reference /// - /// @param[in] selector_load + /// \param[in] selector_load /// The load of the statically-allocated selector. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RewriteObjCClassReference(llvm::Instruction *class_load); - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] basic_block + /// \param[in] basic_block /// The basic block currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RewriteObjCClassReferences(llvm::BasicBlock &basic_block); - //------------------------------------------------------------------ /// A basic block-level pass to find all newly-declared persistent /// variables and register them with the ClangExprDeclMap. This allows them /// to be materialized and dematerialized like normal external variables. @@ -362,182 +309,147 @@ /// locals, so they have an allocation. This pass excises these allocations /// and makes references look like external references where they will be /// resolved -- like all other external references -- by ResolveExternals(). - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Handle a single allocation of a persistent variable /// - /// @param[in] persistent_alloc + /// \param[in] persistent_alloc /// The allocation of the persistent variable. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc); - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] basic_block + /// \param[in] basic_block /// The basic block currently being processed. - //------------------------------------------------------------------ bool RewritePersistentAllocs(llvm::BasicBlock &basic_block); - //------------------------------------------------------------------ /// A function-level pass to find all external variables and functions /// used in the IR. Each found external variable is added to the struct, /// and each external function is resolved in place, its call replaced with /// a call to a function pointer whose value is the address of the function /// in the target process. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Write an initializer to a memory array of assumed sufficient size. /// - /// @param[in] data + /// \param[in] data /// A pointer to the data to write to. /// - /// @param[in] initializer + /// \param[in] initializer /// The initializer itself. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool MaterializeInitializer(uint8_t *data, llvm::Constant *initializer); - //------------------------------------------------------------------ /// Move an internal variable into the static allocation section. /// - /// @param[in] global_variable + /// \param[in] global_variable /// The variable. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool MaterializeInternalVariable(llvm::GlobalVariable *global_variable); - //------------------------------------------------------------------ /// Handle a single externally-defined variable /// - /// @param[in] value + /// \param[in] value /// The variable. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool MaybeHandleVariable(llvm::Value *value); - //------------------------------------------------------------------ /// Handle a single externally-defined symbol /// - /// @param[in] symbol + /// \param[in] symbol /// The symbol. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool HandleSymbol(llvm::Value *symbol); - //------------------------------------------------------------------ /// Handle a single externally-defined Objective-C class /// - /// @param[in] classlist_reference + /// \param[in] classlist_reference /// The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n" /// where n (if present) is an index. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool HandleObjCClass(llvm::Value *classlist_reference); - //------------------------------------------------------------------ /// Handle all the arguments to a function call /// - /// @param[in] C + /// \param[in] C /// The call instruction. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool MaybeHandleCallArguments(llvm::CallInst *call_inst); - //------------------------------------------------------------------ /// Resolve variable references in calls to external functions /// - /// @param[in] basic_block + /// \param[in] basic_block /// The basic block currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool ResolveCalls(llvm::BasicBlock &basic_block); - //------------------------------------------------------------------ /// Remove calls to __cxa_atexit, which should never be generated by /// expressions. /// - /// @param[in] call_inst + /// \param[in] call_inst /// The call instruction. /// - /// @return + /// \return /// True if the scan was successful; false if some operation /// failed - //------------------------------------------------------------------ bool RemoveCXAAtExit(llvm::BasicBlock &basic_block); - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] basic_block + /// \param[in] basic_block /// The function currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool ResolveExternals(llvm::Function &llvm_function); - //------------------------------------------------------------------ /// A basic block-level pass to excise guard variables from the code. /// The result for the function is passed through Clang as a static /// variable. Static variables normally have guard variables to ensure that /// they are only initialized once. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// Rewrite a load to a guard variable to return constant 0. /// - /// @param[in] guard_load + /// \param[in] guard_load /// The load instruction to zero out. - //------------------------------------------------------------------ void TurnGuardLoadIntoZero(llvm::Instruction *guard_load); - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] basic_block + /// \param[in] basic_block /// The basic block currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool RemoveGuards(llvm::BasicBlock &basic_block); - //------------------------------------------------------------------ /// A function-level pass to make all external variable references /// point at the correct offsets from the void* passed into the function. /// ClangExpressionDeclMap::DoStructLayout() must be called beforehand, so /// that the offsets are valid. - //------------------------------------------------------------------ - //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] llvm_function + /// \param[in] llvm_function /// The function currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool ReplaceVariables(llvm::Function &llvm_function); /// Flags @@ -557,18 +469,16 @@ ///module. lldb_private::ClangExpressionDeclMap *m_decl_map; ///< The DeclMap containing the Decls - llvm::Constant *m_CFStringCreateWithBytes; ///< The address of the function - ///CFStringCreateWithBytes, cast to - ///the - /// appropriate function pointer type - llvm::Constant *m_sel_registerName; ///< The address of the function - ///sel_registerName, cast to the - ///appropriate - /// function pointer type - llvm::Constant *m_objc_getClass; ///< The address of the function - ///objc_getClass, cast to the - ///appropriate - /// function pointer type + llvm::FunctionCallee + m_CFStringCreateWithBytes; ///< The address of the function + /// CFStringCreateWithBytes, cast to the + /// appropriate function pointer type + llvm::FunctionCallee m_sel_registerName; ///< The address of the function + /// sel_registerName, cast to the + /// appropriate function pointer type + llvm::FunctionCallee m_objc_getClass; ///< The address of the function + /// objc_getClass, cast to the + /// appropriate function pointer type llvm::IntegerType *m_intptr_ty; ///< The type of an integer large enough to hold a pointer. lldb_private::Stream @@ -589,7 +499,6 @@ ///final /// location of the static allocation. - //------------------------------------------------------------------ /// UnfoldConstant operates on a constant [Old] which has just been replaced /// with a value [New]. We assume that new_value has been properly placed /// early in the function, in front of the first instruction in the entry @@ -602,12 +511,11 @@ /// instructions replace the constant uses, so UnfoldConstant calls itself /// recursively for those. /// - /// @param[in] llvm_function + /// \param[in] llvm_function /// The function currently being processed. /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ class FunctionValueCache { public: @@ -631,32 +539,28 @@ FunctionValueCache &entry_instruction_finder, lldb_private::Stream &error_stream); - //------------------------------------------------------------------ /// Construct a reference to m_reloc_placeholder with a given type and /// offset. This typically happens after inserting data into /// m_data_allocator. /// - /// @param[in] type + /// \param[in] type /// The type of the value being loaded. /// - /// @param[in] offset + /// \param[in] offset /// The offset of the value from the base of m_data_allocator. /// - /// @return + /// \return /// The Constant for the reference, usually a ConstantExpr. - //------------------------------------------------------------------ llvm::Constant *BuildRelocation(llvm::Type *type, uint64_t offset); - //------------------------------------------------------------------ /// Commit the allocation in m_data_allocator and use its final location to /// replace m_reloc_placeholder. /// - /// @param[in] module + /// \param[in] module /// The module that m_data_allocator resides in /// - /// @return + /// \return /// True on success; false otherwise - //------------------------------------------------------------------ bool CompleteDataAllocation(); };
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ModuleDependencyCollector.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ModuleDependencyCollector.h new file mode 100644 index 0000000..0e959f8 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ModuleDependencyCollector.h
@@ -0,0 +1,38 @@ +//===-- ModuleDependencyCollector.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 liblldb_ModuleDependencyCollector_h_ +#define liblldb_ModuleDependencyCollector_h_ + +#include "lldb/Utility/FileCollector.h" +#include "clang/Frontend/Utils.h" +#include "llvm/ADT/StringRef.h" + +namespace lldb_private { +class ModuleDependencyCollectorAdaptor + : public clang::ModuleDependencyCollector { +public: + ModuleDependencyCollectorAdaptor(FileCollector &file_collector) + : clang::ModuleDependencyCollector(""), m_file_collector(file_collector) { + } + + void addFile(llvm::StringRef Filename, + llvm::StringRef FileDst = {}) override { + m_file_collector.AddFile(Filename); + } + + bool insertSeen(llvm::StringRef Filename) override { return false; } + void addFileMapping(llvm::StringRef VPath, llvm::StringRef RPath) override {} + void writeFileMap() override {} + +private: + FileCollector &m_file_collector; +}; +} // namespace lldb_private + +#endif
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/CMakeLists.txt deleted file mode 100644 index bddec8c..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/CMakeLists.txt +++ /dev/null
@@ -1,19 +0,0 @@ -if(NOT LLDB_BUILT_STANDALONE) - set(tablegen_deps intrinsics_gen) -endif() - -add_lldb_library(lldbPluginExpressionParserRust PLUGIN - RustUserExpression.cpp RustLex.cpp RustParse.cpp RustFunctionCaller.cpp - - LINK_LIBS - lldbCore - lldbExpression - lldbSymbol - lldbTarget - - DEPENDS - ${tablegen_deps} - - LINK_COMPONENTS - Support - )
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustAST.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustAST.h deleted file mode 100644 index e3a0b5d..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustAST.h +++ /dev/null
@@ -1,826 +0,0 @@ -//===-- RustAST.h -------------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_RustAST_h -#define liblldb_RustAST_h - -#include <memory> - -#include "lldb/lldb-forward.h" -#include "lldb/lldb-private.h" -#include "lldb/Utility/Scalar.h" -#include "lldb/Symbol/CompilerType.h" -#include "lldb/Symbol/Variable.h" -#include "lldb/Utility/Stream.h" -#include "RustLex.h" - -namespace lldb_private { - -// Functions which are used in the templates below to construct -// various expression nodes. -namespace rust { - -lldb::ValueObjectSP UnaryDereference(ExecutionContext &exe_ctx, lldb::ValueObjectSP addr, - Status &error); -lldb::ValueObjectSP UnaryAddr(ExecutionContext &exe_ctx, lldb::ValueObjectSP val, - Status &error); -lldb::ValueObjectSP UnaryPlus(ExecutionContext &exe_ctx, lldb::ValueObjectSP val, - Status &error); -lldb::ValueObjectSP UnaryNegate(ExecutionContext &exe_ctx, lldb::ValueObjectSP val, - Status &error); -lldb::ValueObjectSP UnaryComplement(ExecutionContext &exe_ctx, lldb::ValueObjectSP val, - Status &error); -lldb::ValueObjectSP UnarySizeof(ExecutionContext &exe_ctx, lldb::ValueObjectSP val, - Status &error); - -template<typename T, bool ASSIGN> -lldb::ValueObjectSP BinaryOperation (ExecutionContext &exe_ctx, lldb::ValueObjectSP left, - lldb::ValueObjectSP right, Status &error); - -template<typename T> -lldb::ValueObjectSP Comparison (ExecutionContext &exe_ctx, lldb::ValueObjectSP left, - lldb::ValueObjectSP right, Status &error); - -lldb::ValueObjectSP ArrayIndex (ExecutionContext &exe_ctx, lldb::ValueObjectSP left, - lldb::ValueObjectSP right, Status &error); - -} - -class RustExpression; -typedef std::unique_ptr<RustExpression> RustExpressionUP; - -class RustTypeExpression; -typedef std::unique_ptr<RustTypeExpression> RustTypeExpressionUP; - -class RustPath; -typedef std::unique_ptr<RustPath> RustPathUP; - -Stream &operator<< (Stream &stream, const RustExpressionUP &expr); -Stream &operator<< (Stream &stream, const RustTypeExpressionUP &type); -Stream &operator<< (Stream &stream, const Scalar &value); -Stream &operator<< (Stream &stream, const std::pair<std::string, RustExpressionUP> &value); - -template<typename T> -Stream &operator<< (Stream &stream, const std::vector<T> &items) { - bool first = true; - for (const T &item : items) { - if (!first) { - stream << ", "; - } - first = false; - stream << item; - } - return stream; -} - -class RustPath { -public: - - RustPath(bool self, bool relative, int supers, std::vector<std::string> &&path, - std::vector<RustTypeExpressionUP> &&generic_params, - bool turbofish = false) - : m_self(self), - m_relative(relative), - m_supers(supers), - m_path(std::move(path)), - m_generic_params(std::move(generic_params)), - m_turbofish(turbofish) - { - } - - void print(Stream &stream) { - if (m_self) { - stream << "self::"; - } else if (!m_relative) { - stream << "::"; - } - for (int i = 0; i < m_supers; ++i) { - stream << "super::"; - } - bool first = true; - for (const std::string &str : m_path) { - if (!first) { - stream << "::"; - } - first = false; - stream << str; - } - - if (!m_generic_params.empty()) { - if (m_turbofish) { - stream << "::"; - } - stream << "<" << m_generic_params << ">"; - } - } - - bool FindDecl(ExecutionContext &exe_ctx, Status &error, - lldb::VariableSP *var, lldb_private::Function **function, - std::string *base_name); - - CompilerType EvaluateAsType(ExecutionContext &exe_ctx, Status &error); - -private: - - std::string Name(ExecutionContext &exe_ctx, Status &error); - CompilerDeclContext FrameDeclContext(ExecutionContext &exe_ctx, Status &error); - bool GetDeclContext(ExecutionContext &exe_ctx, Status &error, - CompilerDeclContext *result, bool *simple_name); - bool AppendGenerics(ExecutionContext &exe_ctx, Status &error, std::string *name); - - bool m_self; - bool m_relative; - int m_supers; - std::vector<std::string> m_path; - std::vector<RustTypeExpressionUP> m_generic_params; - bool m_turbofish; -}; - -class RustPathExpression; - -class RustExpression { -protected: - - RustExpression() { } - -public: - - virtual ~RustExpression() { } - - virtual void print(Stream &stream) = 0; - - virtual lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) = 0; - - virtual RustPathExpression *AsPath() { - return nullptr; - } -}; - -typedef lldb::ValueObjectSP (*RustUnaryOperator)(ExecutionContext &, lldb::ValueObjectSP, - Status &error); - -template<char TAG, RustUnaryOperator OP> -class RustUnaryExpression : public RustExpression { -public: - - explicit RustUnaryExpression(RustExpressionUP &&expr) - : m_expr(std::move(expr)) - { - } - - void print(Stream &stream) override { - stream << TAG << " (" << m_expr << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override { - lldb::ValueObjectSP value = m_expr->Evaluate(exe_ctx, error); - if (!value) - return value; - return OP(exe_ctx, value, error); - } - -private: - - RustExpressionUP m_expr; -}; - -typedef lldb::ValueObjectSP (*RustBinaryOperator)(ExecutionContext &, - lldb::ValueObjectSP, lldb::ValueObjectSP, - Status &error); - -template<int TAG, RustBinaryOperator OP> -class RustBinaryExpression : public RustExpression { -public: - - RustBinaryExpression(RustExpressionUP &&left, - RustExpressionUP &&right) - : m_left(std::move(left)), - m_right(std::move(right)) - { - } - - void print(Stream &stream) override { - stream << "(" << m_left << " "; - lldb_private::rust::PrintTokenKind(stream, TAG); - stream << " " << m_right << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override { - lldb::ValueObjectSP left = m_left->Evaluate(exe_ctx, error); - if (!left) - return left; - lldb::ValueObjectSP right = m_right->Evaluate(exe_ctx, error); - if (!right) - return right; - return OP(exe_ctx, left, right, error); - } - -private: - - RustExpressionUP m_left; - RustExpressionUP m_right; -}; - -template<int TAG, RustBinaryOperator OP> -class RustAssignExpression : public RustExpression { -public: - - void print(Stream &stream) override { - stream << "(" << m_left << " "; - lldb_private::rust::PrintTokenKind(stream, TAG); - stream << " " << m_right << ")"; - } - - RustAssignExpression(RustExpressionUP &&left, - RustExpressionUP &&right) - : m_left(std::move(left)), - m_right(std::move(right)) - { - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override { - lldb::ValueObjectSP left = m_left->Evaluate(exe_ctx, error); - if (!left) - return left; - lldb::ValueObjectSP right = m_right->Evaluate(exe_ctx, error); - if (!right) - return right; - return OP(exe_ctx, left, right, error); - } - -private: - - RustExpressionUP m_left; - RustExpressionUP m_right; -}; - -class RustAssignment : public RustExpression { -public: - - RustAssignment(RustExpressionUP &&left, - RustExpressionUP &&right) - : m_left(std::move(left)), - m_right(std::move(right)) - { - } - - void print(Stream &stream) override { - stream << "(" << m_left << " = " << m_right << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustExpressionUP m_left; - RustExpressionUP m_right; -}; - -class RustAndAndExpression : public RustExpression { -public: - - RustAndAndExpression(RustExpressionUP &&left, - RustExpressionUP &&right) - : m_left(std::move(left)), - m_right(std::move(right)) - { - } - - void print(Stream &stream) override { - stream << "(" << m_left << " && " << m_right << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustExpressionUP m_left; - RustExpressionUP m_right; -}; - -class RustOrOrExpression : public RustExpression { -public: - - RustOrOrExpression(RustExpressionUP &&left, - RustExpressionUP &&right) - : m_left(std::move(left)), - m_right(std::move(right)) - { - } - - void print(Stream &stream) override { - stream << "(" << m_left << " || " << m_right << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustExpressionUP m_left; - RustExpressionUP m_right; -}; - -class RustRangeExpression : public RustExpression { -public: - - // Either or both can be NULL here. - RustRangeExpression(RustExpressionUP &&left, - RustExpressionUP &&right, - bool inclusive) - : m_left(std::move(left)), - m_right(std::move(right)), - m_inclusive(inclusive) - { - // Inclusive ranges require an upper bound. - assert(m_right || !m_inclusive); - } - - void print(Stream &stream) override { - stream << "(" << m_left << (m_inclusive ? " ..= " : " .. ") << m_right << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustExpressionUP m_left; - RustExpressionUP m_right; - bool m_inclusive; -}; - -class RustFieldExpression : public RustExpression { -public: - - RustFieldExpression(RustExpressionUP &&left, llvm::StringRef field) - : m_left(std::move(left)), - m_field(field.str()) - { - } - - void print(Stream &stream) override { - stream << m_left << "." << m_field; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustExpressionUP m_left; - std::string m_field; -}; - -class RustTupleFieldExpression : public RustExpression { -public: - - RustTupleFieldExpression(RustExpressionUP &&left, uint32_t field) - : m_left(std::move(left)), - m_field(field) - { - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - void print(Stream &stream) override { - stream << m_left << "." << int(m_field); - } - - RustExpressionUP m_left; - uint32_t m_field; -}; - -class RustLiteral : public RustExpression { -public: - - RustLiteral(Scalar value, RustTypeExpressionUP &&type) - : m_value(value), - m_type(std::move(type)) - { - } - - void print(Stream &stream) override { - stream << m_value; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - Scalar m_value; - RustTypeExpressionUP m_type; -}; - -class RustBooleanLiteral : public RustExpression { -public: - - RustBooleanLiteral(bool value) - : m_value(value) - { - } - - void print(Stream &stream) override { - stream << (m_value ? "true" : "false"); - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - bool m_value; -}; - -class RustCharLiteral : public RustExpression { -public: - - RustCharLiteral(uint32_t value, bool is_byte) - : m_value(value), - m_is_byte(is_byte) - { - } - - void print(Stream &stream) override { - stream << (m_is_byte ? "b'" : "'"); - if (m_value >= ' ' && m_value < 128) { - stream << char(m_value); - } else { - if (m_is_byte) { - stream << "\\x"; - stream.PutHex8(m_value); - } else { - stream << "\\u{"; - stream.PutHex32(m_value); - stream << "}"; - } - } - stream << "'"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - uint32_t m_value; - bool m_is_byte; -}; - -class RustStringLiteral : public RustExpression { -public: - - RustStringLiteral(std::string &&value, bool is_byte) - : m_value(std::move(value)), - m_is_byte(is_byte) - { - } - - void print(Stream &stream) override { - stream << (m_is_byte ? "b\"" : "\"") << m_value << "\""; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - std::string m_value; - bool m_is_byte; -}; - -class RustTupleExpression : public RustExpression { -public: - - explicit RustTupleExpression(std::vector<RustExpressionUP> &&exprs) - : m_exprs(std::move(exprs)) - { - } - - void print(Stream &stream) override { - // Maybe emit an extra "," to differentiate from (expr). - stream << "(" << m_exprs << (m_exprs.empty() ? "" : ", ") << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - std::vector<RustExpressionUP> m_exprs; - -}; - -class RustArrayLiteral : public RustExpression { -public: - - explicit RustArrayLiteral(std::vector<RustExpressionUP> &&exprs) - : m_exprs(std::move(exprs)) - { - } - - void print(Stream &stream) override { - stream << "[" << m_exprs << "]"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - std::vector<RustExpressionUP> m_exprs; - -}; - -class RustArrayWithLength : public RustExpression { -public: - - RustArrayWithLength(RustExpressionUP &&value, RustExpressionUP &&length) - : m_value(std::move(value)), - m_length(std::move(length)) - { - } - - void print(Stream &stream) override { - stream << "[" << m_value << "; " << m_length << "]"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustExpressionUP m_value; - RustExpressionUP m_length; -}; - -// Note that this may also represent a tuple-struct expression if the -// "function" is a path referring to a tuple type. -class RustCall : public RustExpression { -public: - - RustCall(RustExpressionUP &&func, std::vector<RustExpressionUP> &&exprs) - : m_func(std::move(func)), - m_exprs(std::move(exprs)) - { - } - - void print(Stream &stream) override { - stream << m_func << " (" << m_exprs << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - lldb::ValueObjectSP MaybeEvalTupleStruct(ExecutionContext &exe_ctx, Status &error); - - RustExpressionUP m_func; - std::vector<RustExpressionUP> m_exprs; - -}; - -class RustCast : public RustExpression { -public: - - RustCast(RustTypeExpressionUP &&type, RustExpressionUP &&expr) - : m_type(std::move(type)), - m_expr(std::move(expr)) - { - } - - void print(Stream &stream) override { - stream << "(" << m_expr << " as " << m_type << ")"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustTypeExpressionUP m_type; - RustExpressionUP m_expr; -}; - -class RustPathExpression : public RustExpression { -public: - - RustPathExpression(RustPathUP &&path) - : m_path(std::move(path)) - { - } - - explicit RustPathExpression(std::string &&item) - { - std::vector<std::string> names; - names.push_back(std::move(item)); - - m_path = llvm::make_unique<RustPath>(false, true, 0, std::move(names), - std::vector<RustTypeExpressionUP>()); - } - - void print(Stream &stream) override { - m_path->print(stream); - } - - CompilerType EvaluateAsType(ExecutionContext &exe_ctx, Status &error) { - return m_path->EvaluateAsType(exe_ctx, error); - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - - RustPathExpression *AsPath() override { - return this; - } - -private: - - RustPathUP m_path; -}; - -class RustStructExpression : public RustExpression { -public: - - // Note that |copy| can be null if no '..' form was seen. - RustStructExpression(RustTypeExpressionUP &&path, - std::vector<std::pair<std::string, RustExpressionUP>> &&inits, - RustExpressionUP &©) - : m_path(std::move(path)), - m_inits(std::move(inits)), - m_copy(std::move(copy)) - { - } - - void print(Stream &stream) override { - stream << m_path << " { " << m_inits; - if (m_copy) { - stream << ", .. " << m_copy; - } - stream << " }"; - } - - lldb::ValueObjectSP Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustTypeExpressionUP m_path; - std::vector<std::pair<std::string, RustExpressionUP>> m_inits; - RustExpressionUP m_copy; -}; - - -class RustTypeExpression { -protected: - - RustTypeExpression() { } - -public: - - virtual ~RustTypeExpression() { } - - virtual void print(Stream &stream) = 0; - - virtual CompilerType Evaluate(ExecutionContext &exe_ctx, Status &error) = 0; -}; - -class RustPathTypeExpression : public RustTypeExpression { -public: - - RustPathTypeExpression(RustPathUP &&path) - : m_path(std::move(path)) - { - } - - explicit RustPathTypeExpression(std::string &&item) - { - std::vector<std::string> names; - names.push_back(std::move(item)); - - m_path = llvm::make_unique<RustPath>(false, true, 0, std::move(names), - std::vector<RustTypeExpressionUP>()); - } - - void print(Stream &stream) override { - m_path->print(stream); - } - - CompilerType Evaluate(ExecutionContext &exe_ctx, Status &error) override { - return m_path->EvaluateAsType(exe_ctx, error); - } - -private: - - RustPathUP m_path; -}; - -class RustArrayTypeExpression : public RustTypeExpression { -public: - - RustArrayTypeExpression(RustTypeExpressionUP &&element, uint64_t len) - : m_element(std::move(element)), - m_len(len) - { - } - - void print(Stream &stream) override { - stream << "[" << m_element << "; " << int64_t(m_len) << "]"; - } - - CompilerType Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustTypeExpressionUP m_element; - uint64_t m_len; -}; - -class RustSliceTypeExpression : public RustTypeExpression { -public: - - RustSliceTypeExpression(RustTypeExpressionUP &&element, bool is_mut) - : m_element(std::move(element)), - m_is_mut(is_mut) - { - } - - void print(Stream &stream) override { - stream << "&" << (m_is_mut ? "mut " : "") << "[" << m_element << "]"; - } - - CompilerType Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustTypeExpressionUP m_element; - bool m_is_mut; -}; - -class RustPointerTypeExpression : public RustTypeExpression { -public: - - RustPointerTypeExpression(RustTypeExpressionUP &&target, bool is_ref, bool is_mut = false) - : m_target(std::move(target)), - m_is_ref(is_ref), - m_is_mut(is_mut) - { - } - - void print(Stream &stream) override { - if (m_is_ref) { - stream << "&" << (m_is_ref ? "mut " : "") << m_target; - } else { - stream << "*" << (m_is_mut ? "mut " : "const ") << m_target; - } - } - - CompilerType Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustTypeExpressionUP m_target; - bool m_is_ref; - bool m_is_mut; -}; - -class RustFunctionTypeExpression : public RustTypeExpression { -public: - - RustFunctionTypeExpression(RustTypeExpressionUP &&result, - std::vector<RustTypeExpressionUP> &&arguments) - : m_result(std::move(result)), - m_arguments(std::move(arguments)) - { - } - - void print(Stream &stream) override { - stream << "fn (" << m_arguments << ") -> " << m_result; - } - - CompilerType Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - RustTypeExpressionUP m_result; - std::vector<RustTypeExpressionUP> m_arguments; -}; - -class RustTupleTypeExpression : public RustTypeExpression { -public: - - RustTupleTypeExpression(std::vector<RustTypeExpressionUP> &&arguments) - : m_arguments(std::move(arguments)) - { - } - - void print(Stream &stream) override { - stream << "(" << m_arguments << ")"; - } - - CompilerType Evaluate(ExecutionContext &exe_ctx, Status &error) override; - -private: - - std::vector<RustTypeExpressionUP> m_arguments; -}; - -} // namespace lldb_private - -#endif // liblldb_RustAST_h
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustFunctionCaller.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustFunctionCaller.cpp deleted file mode 100644 index b9b265e..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustFunctionCaller.cpp +++ /dev/null
@@ -1,200 +0,0 @@ -//===-- RustFunctionCaller.cpp ---------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "Plugins/ExpressionParser/Clang/ASTStructExtractor.h" -#include "RustFunctionCaller.h" - -#include "Plugins/ExpressionParser/Clang/ClangExpressionParser.h" - -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Triple.h" -#include "llvm/ExecutionEngine/ExecutionEngine.h" -#include "llvm/IR/Module.h" - -#include "lldb/Core/Module.h" -#include "lldb/Utility/State.h" -#include "lldb/Core/ValueObject.h" -#include "lldb/Core/ValueObjectList.h" -#include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Expression/IRExecutionUnit.h" -#include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Symbol/RustASTContext.h" -#include "lldb/Symbol/Function.h" -#include "lldb/Symbol/Type.h" -#include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/Process.h" -#include "lldb/Target/RegisterContext.h" -#include "lldb/Target/Target.h" -#include "lldb/Target/Thread.h" -#include "lldb/Target/ThreadPlan.h" -#include "lldb/Target/ThreadPlanCallFunction.h" -#include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Log.h" - -using namespace lldb_private; - -//---------------------------------------------------------------------- -// RustFunctionCaller constructor -//---------------------------------------------------------------------- -RustFunctionCaller::RustFunctionCaller(ExecutionContextScope &exe_scope, - const CompilerType &function_type, - const CompilerType &return_type, - const Address &functionAddress, - const ValueList &arg_value_list, - const char *name) - : ClangFunctionCaller(exe_scope, return_type, functionAddress, arg_value_list, name), - m_function_type(function_type) -{ -} - -//---------------------------------------------------------------------- -// Destructor -//---------------------------------------------------------------------- -RustFunctionCaller::~RustFunctionCaller() {} - -static bool -AppendType(std::string *output, RustASTContext *ast, RustASTContext::TypeNameMap *name_map, - const std::string &varname, CompilerType type) { - std::string value; - if (!ast->GetCABITypeDeclaration(type, varname, name_map, &value)) { - return false; - } - output->append(" "); - output->append(value); - output->append(";\n"); - return true; -} - -unsigned RustFunctionCaller::CompileFunction(lldb::ThreadSP thread_to_use_sp, - DiagnosticManager &diagnostic_manager) { - if (m_compiled) - return 0; - - // Compilation might call code, make sure to keep on the thread the caller - // indicated. - ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher( - thread_to_use_sp); - - RustASTContext *ast = - llvm::dyn_cast_or_null<RustASTContext>(m_function_return_type.GetTypeSystem()); - if (!ast) { - diagnostic_manager.PutString(eDiagnosticSeverityError, "not in a Rust context!?"); - return 1; - } - - // Cons up the function we're going to wrap our call in, then compile it... - // We declare the function "extern "C"" because the compiler might be in C++ - // mode which would mangle the name and then we couldn't find it again... - m_wrapper_function_text.clear(); - - m_wrapper_function_text.append("extern \"C\" void "); - m_wrapper_function_text.append(m_wrapper_function_name); - m_wrapper_function_text.append(" (void *input)\n{\n"); - - // For the Itanium ABI we want to generate a non-standard-layout - // type, so that ASTStructExtractor can see the length of the type - // without padding, so that the size of the final element is - // correct. FIXME this seems horrible, maybe a fix in - // ASTStructExtractor is more appropriate. - m_wrapper_function_text.append(" struct empty { };\n"); - m_wrapper_function_text.append(" struct a : empty { };\n"); - m_wrapper_function_text.append(" struct b : empty { };\n"); - - RustASTContext::TypeNameMap name_map; - std::string code; - code.append(" struct "); - code.append(m_wrapper_struct_name); - code.append(" : a, b {\n"); - - // ASTStructExtractor requires the first argument to be the - // function. - if (!AppendType(&code, ast, &name_map, "fn_ptr", m_function_type)) { - diagnostic_manager.PutString(eDiagnosticSeverityError, - "could not compute Rust type declaration"); - return 1; - } - - // This was ensured by the caller. - assert(unsigned(m_function_type.GetNumberOfFunctionArguments()) == m_arg_values.GetSize()); - - std::string arguments; - for (int i = 0; i < m_function_type.GetFunctionArgumentCount(); ++i) { - // We use the actual argument types in this structure so that - // copy-in always preserves values, and then we let the C++ - // compiler do any scalar conversions. Rust doesn't have - // coercions like this, but it has type inferencing, which we - // don't, so this is handy for users who want to write "32" - // instead of "32f32". - CompilerType arg_type = m_arg_values.GetValueAtIndex(i)->GetCompilerType(); - - // FIXME work around a FunctionCaller problem. Note that the - // actual argument is already a pointer at this point, see - // RustParse. - bool is_aggregate = m_function_type.GetFunctionArgumentTypeAtIndex(i).IsAggregateType(); - - std::string argname = "__arg_" + std::to_string(i); - if (!AppendType(&code, ast, &name_map, argname, arg_type)) { - diagnostic_manager.PutString(eDiagnosticSeverityError, - "could not compute Rust type declaration"); - return 1; - } - if (i > 0) { - arguments.append(", "); - } - if (is_aggregate) { - arguments.append("*"); - } - arguments.append("__lldb_fn_data->"); - arguments.append(argname); - } - - // ASTStructExtractor requires that the last field hold the result. - if (!AppendType(&code, ast, &name_map, "result", - m_function_type.GetFunctionReturnType())) { - diagnostic_manager.PutString(eDiagnosticSeverityError, - "could not compute Rust type declaration"); - return 1; - } - - m_wrapper_function_text.append(name_map.typedefs); - m_wrapper_function_text.append(code); - - m_wrapper_function_text.append(" };\n"); - - m_wrapper_function_text.append(" "); - m_wrapper_function_text.append(m_wrapper_struct_name); - m_wrapper_function_text.append(" *__lldb_fn_data = ("); - m_wrapper_function_text.append(m_wrapper_struct_name); - m_wrapper_function_text.append(" *) input;\n"); - - m_wrapper_function_text.append(" __lldb_fn_data->result = __lldb_fn_data->fn_ptr("); - m_wrapper_function_text.append(arguments); - m_wrapper_function_text.append(");\n}\n"); - - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); - if (log) - log->Printf("Expression: \n\n%s\n\n", m_wrapper_function_text.c_str()); - - // Okay, now compile this expression - - lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); - unsigned num_errors; - if (jit_process_sp) { - m_parser.reset(new ClangExpressionParser(jit_process_sp.get(), *this, true)); - - num_errors = m_parser->Parse(diagnostic_manager); - } else { - diagnostic_manager.PutString(eDiagnosticSeverityError, - "no process - unable to inject function"); - num_errors = 1; - } - - m_compiled = (num_errors == 0); - return num_errors; -}
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustFunctionCaller.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustFunctionCaller.h deleted file mode 100644 index 1a5c54e..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustFunctionCaller.h +++ /dev/null
@@ -1,46 +0,0 @@ -//===-- RustFunctionCaller.h -----------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_RustFunctionCaller_h_ -#define liblldb_RustFunctionCaller_h_ - -#include "lldb/Core/Address.h" -#include "lldb/Core/Value.h" -#include "lldb/Core/ValueObjectList.h" -#include "lldb/Expression/FunctionCaller.h" -#include "lldb/Symbol/CompilerType.h" -#include "lldb/Target/Process.h" -#include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h" - -namespace lldb_private { - -// Derive from ClangFunctionCaller so we don't have to reimplement -// ASTStructExtractor. This is very naughty. -class RustFunctionCaller : public ClangFunctionCaller { - -public: - RustFunctionCaller(ExecutionContextScope &exe_scope, - const CompilerType &function_type, - const CompilerType &return_type, - const Address &function_address, - const ValueList &arg_value_list, const char *name); - - ~RustFunctionCaller() override; - - unsigned CompileFunction(lldb::ThreadSP thread_to_use_sp, - DiagnosticManager &diagnostic_manager) override; - -private: - - CompilerType m_function_type; -}; - -} // namespace lldb_private - -#endif // liblldb_RustFunctionCaller_h_
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustLex.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustLex.cpp deleted file mode 100644 index 99a6cb7..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustLex.cpp +++ /dev/null
@@ -1,654 +0,0 @@ -//===-- RustLex.cpp ------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "RustLex.h" -#include "llvm/Support/ConvertUTF.h" -#include "llvm/ADT/APInt.h" - -using namespace lldb_private::rust; -using namespace lldb_private; -using namespace lldb; -using namespace llvm; - -void lldb_private::rust::PrintTokenKind(Stream &stream, int kind) { - if (kind < STRING) { - stream << char(kind); - } else { - switch (kind) { - case STRING: - case BYTESTRING: - case CHAR: - case BYTE: - case FLOAT: - case INTEGER: - case AS: - case TRUE: - case FALSE: - case SUPER: - case SELF: - case MUT: - case CONST: - case FN: - case SIZEOF: - case IDENTIFIER: - case INVALID: - case THATSALLFOLKS: - // May want to clean this up someday. - stream << "[TOKEN=" << kind << "]"; - break; - - case DOTDOT: - stream << ".."; - break; - - case DOTDOTEQ: - stream << "..="; - break; - - case OROR: - stream << "||"; - break; - - case ANDAND: - stream << "&&"; - break; - - case EQEQ: - stream << "=="; - break; - - case NOTEQ: - stream << "!="; - break; - - case LTEQ: - stream << "<="; - break; - - case GTEQ: - stream << ">="; - break; - - case LSH: - stream << "<<"; - break; - - case RSH: - stream << ">>"; - break; - - case PLUS_EQ: - stream << "+="; - break; - - case MINUS_EQ: - stream << "-="; - break; - - case SLASH_EQ: - stream << "/="; - break; - - case STAR_EQ: - stream << "*="; - break; - - case PERCENT_EQ: - stream << "%="; - break; - - case RSH_EQ: - stream << ">>="; - break; - - case LSH_EQ: - stream << "<<="; - break; - - case AND_EQ: - stream << "&="; - break; - - case OR_EQ: - stream << "|="; - break; - - case XOR_EQ: - stream << "^="; - break; - - case COLONCOLON: - stream << "::"; - break; - - case ARROW: - stream << "->"; - break; - - default: - stream << "!!!OOPS!!!"; - break; - } - } -} - -llvm::StringMap<TokenKind> *Lexer::m_keywords; - -Token Lexer::Next() { - // Skip whitespace. - while (m_iter != m_end && - // FIXME is it possible to see newlines here? - (*m_iter == ' ' || *m_iter == '\t')) - ++m_iter; - if (m_iter == m_end) { - return Token(THATSALLFOLKS); - } - - char c = *m_iter; - if (c >= '0' && c <= '9') { - return Number(); - } else if (c == 'b') { - return MaybeByteLiteral(); - } else if (c == 'r') { - return MaybeRawString(); - } else if (c == '"') { - return String(); - } else if (c == '\'') { - return Character(); - } else { - return Operator(); - } -} - -bool Lexer::Lookup(const ::llvm::StringRef &str, int *result) { - ::llvm::StringMap<TokenKind> *map = Keywords(); - const auto &iter = map->find(str); - if (iter == map->end()) { - return false; - } - *result = iter->second; - return true; -} - -Token Lexer::Operator() { - int result; - - if (Remaining() >= 3 && Lookup(::llvm::StringRef(m_iter, 3), &result)) { - m_iter += 3; - return Token(result); - } - - if (Remaining() >= 2 && Lookup(::llvm::StringRef(m_iter, 2), &result)) { - m_iter += 2; - return Token(result); - } - - if (strchr(".,;|&=!<>+-*/%:[](){}", *m_iter) != nullptr) { - return Token(*m_iter++); - } - - return Identifier(); -} - -bool Lexer::BasicInteger(int *radix_out, std::string *value) { - int radix = 10; - - assert (m_iter != m_end); - assert (*m_iter >= '0' && *m_iter <= '9'); - - bool need_digit = false; - if (radix_out != nullptr && *m_iter == '0') { - // Ignore this digit and see if we have a non-decimal integer. - ++m_iter; - if (m_iter == m_end) { - // Plain "0". - value->push_back('0'); - if (radix_out) { - *radix_out = radix; - } - return true; - } - - if (*m_iter == 'x') { - radix = 16; - need_digit = true; - ++m_iter; - } else if (*m_iter == 'b') { - radix = 2; - need_digit = true; - ++m_iter; - } else if (*m_iter == 'o') { - radix = 8; - need_digit = true; - ++m_iter; - } else { - value->push_back('0'); - } - } - - for (; m_iter != m_end; ++m_iter) { - if (*m_iter == '_') { - continue; - } - if ((radix == 10 || radix == 16) && *m_iter >= '0' && *m_iter <= '9') { - // Ok. - } else if (radix == 2 && *m_iter >= '0' && *m_iter <= '1') { - // Ok. - } else if (radix == 8 && *m_iter >= '0' && *m_iter <= '7') { - // Ok. - } else if (radix == 16 && *m_iter >= 'a' && *m_iter <= 'f') { - // Ok. - } else if (radix == 16 && *m_iter >= 'A' && *m_iter <= 'F') { - // Ok. - } else { - break; - } - - value->push_back(*m_iter); - need_digit = false; - } - - if (radix_out) { - *radix_out = radix; - } - return !need_digit; -} - -const char *Lexer::CheckSuffix(const char *const *suffixes) { - const char *suffix = nullptr; - - size_t left = Remaining(); - for (int i = 0; suffixes[i]; ++i) { - size_t len = strlen(suffixes[i]); - if (left >= len) { - ::llvm::StringRef text(m_iter, len); - if (text == suffixes[i]) { - suffix = suffixes[i]; - m_iter += len; - break; - } - } - } - - return suffix; -} - -int Lexer::Float(std::string *value) { - assert(m_iter != m_end && (*m_iter == '.' || *m_iter == 'e' || *m_iter == 'E')); - - if (*m_iter == '.') { - ++m_iter; - if (m_iter == m_end || !(*m_iter >= '0' && *m_iter <= '9')) { - // Not a floating-point number. - --m_iter; - return INTEGER; - } - - value->push_back('.'); - BasicInteger(nullptr, value); - } - - if (m_iter == m_end || (*m_iter != 'e' && *m_iter != 'E')) { - return FLOAT; - } - - value->push_back(*m_iter++); - if (m_iter == m_end) { - return INVALID; - } - - if (*m_iter == '+' || *m_iter == '-') { - value->push_back(*m_iter++); - if (m_iter == m_end) { - return INVALID; - } - } - - if (!(*m_iter >= '0' && *m_iter <= '9')) { - return INVALID; - } - BasicInteger(nullptr, value); - return FLOAT; -} - -Token Lexer::Number() { - std::string number; - int radix; - - if (!BasicInteger(&radix, &number)) { - return Token(INVALID); - } - - if (m_iter != m_end && radix == 10 && - (*m_iter == '.' || *m_iter == 'e' || *m_iter == 'E')) { - int kind = Float(&number); - if (kind == INVALID) { - return Token(INVALID); - } - if (kind == FLOAT) { - // Actually a float. - ::llvm::StringRef sref(number); - double dval; - if (sref.getAsDouble(dval)) { - return Token(INVALID); - } - - static const char * const float_suffixes[] = { - "f32", - "f64", - nullptr - }; - - const char *suffix = CheckSuffix(float_suffixes); - - return Token(FLOAT, dval, suffix); - } - - // Floating-point lex failed but we still have an integer. - assert(kind == INTEGER); - } - - static const char * const int_suffixes[] = { - "u8", - "i8", - "u16", - "i16", - "u32", - "i32", - "u64", - "i64", - "usize", - "isize", - nullptr - }; - - APInt value; - ::llvm::StringRef sref(number); - if (sref.getAsInteger(radix, value)) { - return Token(INVALID); - } - // FIXME maybe we should just leave it as an APInt through the whole - // process. - if (value.getNumWords() > 1) { - return Token(INVALID); - } - - const char *suffix = CheckSuffix(int_suffixes); - - return Token(INTEGER, value.getLimitedValue(), suffix); -} - -Token Lexer::Identifier() { - assert(m_iter != m_end); - - ::llvm::StringRef::iterator start = m_iter; - char c = *m_iter; - if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')) { - return Token(INVALID); - } - - for (++m_iter; m_iter != m_end; ++m_iter) { - char c = *m_iter; - if (! ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || - (c >= '0' && c <= '9'))) { - break; - } - } - - ::llvm::StringRef text(start, m_iter - start); - int result; - if (Lookup(text, &result)) { - return Token(result); - } - - return Token(IDENTIFIER, text.str()); -} - -Token Lexer::MaybeByteLiteral() { - assert(*m_iter == 'b'); - - if (Remaining() < 2) { - return Identifier(); - } - if (m_iter[1] == 'r') { - return MaybeRawString(true); - } else if (m_iter[1] == '"') { - ++m_iter; - return String(true); - } else if (m_iter[1] == '\'') { - ++m_iter; - return Character(true); - } - return Identifier(); -} - -bool Lexer::ParseHex(uint64_t *result, int min_digits, int max_digits) { - *result = 0; - int i; - for (i = 0; m_iter != m_end && i < max_digits; ++i, ++m_iter) { - uint64_t digit; - if (*m_iter >= 'a' && *m_iter <= 'f') { - digit = *m_iter - 'a' + 10; - } else if (*m_iter >= 'A' && *m_iter <= 'F') { - digit = *m_iter - 'A' + 10; - } else if (*m_iter >= '0' && *m_iter <= '9') { - digit = *m_iter - '0'; - } else { - break; - } - *result = *result * 16 + digit; - } - - return i >= min_digits; -} - -bool Lexer::ParseEscape(uint64_t *result, bool is_byte) { - assert(*m_iter == '\\'); - ++m_iter; - - if (m_iter == m_end) { - return false; - } - switch (*m_iter++) { - case 'x': - return ParseHex(result, 2, 2); - - case 'u': { - if (is_byte) { - return false; - } - if (m_iter == m_end || *m_iter++ != '{') { - return false; - } - if (!ParseHex(result, 1, 6)) { - return false; - } - if (m_iter == m_end || *m_iter++ != '}') { - return false; - } - break; - } - - case 'n': - *result = '\n'; - break; - case 'r': - *result = '\r'; - break; - case 't': - *result = '\t'; - break; - case '\\': - *result = '\\'; - break; - case '0': - *result = 0; - break; - case '\'': - *result = '\''; - break; - case '"': - *result = '"'; - break; - - default: - return false; - } - - return true; -} - -bool Lexer::AppendEscape(std::string *result, bool is_byte) { - uint64_t value; - if (!ParseEscape(&value, is_byte)) { - return false; - } - - char utf8[10]; - char *out = utf8; - if (!ConvertCodePointToUTF8(value, out)) { - return false; - } - - result->append(utf8, out); - return true; -} - -Token Lexer::Character(bool is_byte) { - assert(*m_iter == '\''); - - if (++m_iter == m_end) { - return Token(INVALID); - } - - uint64_t result; - if (*m_iter == '\\') { - if (!ParseEscape(&result, is_byte)) { - return Token(INVALID); - } - } else { - result = *m_iter++; - } - - if (m_iter == m_end || *m_iter++ != '\'') { - return Token(INVALID); - } - - return Token(is_byte ? BYTE : CHAR, result); -} - -Token Lexer::MaybeRawString(bool is_byte) { - // Use a local copy so we can backtrack if need be. - ::llvm::StringRef::iterator iter = m_iter; - - if (is_byte) { - assert(*iter == 'b'); - ++iter; - } - - assert(*iter == 'r'); - ++iter; - - ::llvm::StringRef::iterator before_hashes = iter; - while (iter != m_end && *iter == '#') { - ++iter; - } - if (iter == m_end || *iter != '"') { - return Identifier(); - } - - size_t n_hashes = iter - before_hashes; - ::llvm::StringRef::iterator string_start = ++iter; - - for (; iter != m_end; ++iter) { - if (*iter == '"' && - (n_hashes == 0 || - (size_t(m_end - iter + 1) > n_hashes && - strncmp(iter + 1, before_hashes, n_hashes) == 0))) { - break; - } - } - - m_iter = iter; - if (iter == m_end) { - return Token(INVALID); - } - - assert(*m_iter == '"'); - ++m_iter; - assert(Remaining() >= n_hashes); - m_iter += n_hashes; - - return Token(is_byte ? BYTESTRING : STRING, std::string(string_start, iter)); -} - -Token Lexer::String(bool is_byte) { - assert(*m_iter == '"'); - ++m_iter; - - std::string text; - while (m_iter != m_end && *m_iter != '"') { - if (*m_iter == '\\') { - if (!AppendEscape(&text, is_byte)) { - return Token(INVALID); - } - } else { - text += *m_iter++; - } - } - - if (m_iter == m_end) { - return Token(INVALID); - } - assert(*m_iter == '"'); - ++m_iter; - - return Token(is_byte ? BYTESTRING : STRING, std::move(text)); -} - -::llvm::StringMap<TokenKind> *Lexer::Keywords() { - if (m_keywords == nullptr) { - m_keywords = new ::llvm::StringMap<TokenKind>; - ::llvm::StringMap<TokenKind> &m = *m_keywords; - - m["as"] = AS; - m["true"] = TRUE; - m["false"] = FALSE; - m["super"] = SUPER; - m["self"] = SELF; - m["mut"] = MUT; - m["const"] = CONST; - m["fn"] = FN; - m["sizeof"] = SIZEOF; - m[".."] = DOTDOT; - m["..="] = DOTDOTEQ; - m["||"] = OROR; - m["|="] = OR_EQ; - m["&&"] = ANDAND; - m["&="] = AND_EQ; - m["^="] = XOR_EQ; - m["=="] = EQEQ; - m["!="] = NOTEQ; - m["<="] = LTEQ; - m[">="] = GTEQ; - m["<<"] = LSH; - m[">>"] = RSH; - m["+="] = PLUS_EQ; - m["-="] = MINUS_EQ; - m["*="] = STAR_EQ; - m["/="] = SLASH_EQ; - m["%="] = PERCENT_EQ; - m["<<="] = LSH_EQ; - m[">>="] = RSH_EQ; - m["::"] = COLONCOLON; - m["->"] = ARROW; - } - - return m_keywords; -}
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustLex.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustLex.h deleted file mode 100644 index 84bbbd9..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustLex.h +++ /dev/null
@@ -1,168 +0,0 @@ -//===-- RustLex.h -------------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_RustLex_h -#define liblldb_RustLex_h - -#include <memory> - -#include "lldb/lldb-forward.h" -#include "lldb/lldb-private.h" - -#include "llvm/ADT/Optional.h" -#include "llvm/ADT/StringRef.h" -#include "lldb/Utility/Stream.h" - -namespace lldb_private { - -namespace rust { - -// Note that single-character tokens are represented by the character -// itself. -enum TokenKind { - STRING = 128, - BYTESTRING, - CHAR, - BYTE, - FLOAT, - INTEGER, - AS, - TRUE, - FALSE, - SUPER, - SELF, - MUT, - CONST, - FN, - SIZEOF, - DOTDOT, - DOTDOTEQ, - OROR, - ANDAND, - EQEQ, - NOTEQ, - LTEQ, - GTEQ, - LSH, - RSH, - PLUS_EQ, - MINUS_EQ, - SLASH_EQ, - STAR_EQ, - PERCENT_EQ, - RSH_EQ, - LSH_EQ, - AND_EQ, - OR_EQ, - XOR_EQ, - COLONCOLON, - ARROW, - IDENTIFIER, - INVALID, - THATSALLFOLKS -}; - -void PrintTokenKind(Stream &stream, int kind); - -struct Token { - int kind; - - llvm::Optional<uint64_t> uinteger; - llvm::Optional<double> dvalue; - // This can be NULL if no suffix was specified. - const char *number_suffix = nullptr; - std::string str; - - explicit Token(int kind_) - : kind(kind_) - { - } - - Token(int kind_, uint64_t val_, const char *suffix_ = nullptr) - : kind(kind_), - uinteger(val_), - number_suffix(suffix_) - { - } - - Token(int kind_, double val_, const char *suffix_ = nullptr) - : kind(kind_), - dvalue(val_), - number_suffix(suffix_) - { - } - - Token(int kind_, std::string &&str_) - : kind(kind_), - str(std::move(str_)) - { - } - - bool operator==(const Token &other) const { - if (kind != other.kind || - uinteger != other.uinteger || - dvalue != other.dvalue || - str != other.str) { - return false; - } - - if (number_suffix == nullptr) { - return other.number_suffix == nullptr; - } - if (other.number_suffix == nullptr) { - return false; - } - - return strcmp(number_suffix, other.number_suffix) == 0; - } -}; - -class Lexer { -public: - - explicit Lexer(llvm::StringRef ref) - : m_iter(ref.begin()), - m_end(ref.end()) - { - } - - Token Next(); - -private: - - const char *CheckSuffix(const char *const *suffixes); - bool BasicInteger(int *radix_out, std::string *value); - Token MaybeByteLiteral(); - Token MaybeRawString(bool is_byte = false); - Token String(bool is_byte = false); - Token Character(bool is_byte = false); - Token Operator(); - int Float(std::string *value); - Token Number(); - Token Identifier(); - bool AppendEscape(std::string *result, bool is_byte); - bool ParseHex(uint64_t *result, int min_digits, int max_digits); - bool ParseEscape(uint64_t *result, bool is_byte); - bool Lookup(const ::llvm::StringRef &str, int *result); - - llvm::StringRef::iterator m_iter; - llvm::StringRef::iterator m_end; - - size_t Remaining() const { return m_end - m_iter; } - - static llvm::StringMap<TokenKind> *Keywords(); - - static llvm::StringMap<TokenKind> *m_keywords; -}; - -} // namespace rust - -} // namespace lldb_private - -#endif // liblldb_RustLex_h
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustParse.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustParse.cpp deleted file mode 100644 index c9d3ab9..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustParse.cpp +++ /dev/null
@@ -1,2283 +0,0 @@ -//===-- RustParse.cpp ------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "RustParse.h" -#include "lldb/Core/Module.h" -#include "lldb/Core/ValueObject.h" -#include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Symbol/Block.h" -#include "lldb/Symbol/Function.h" -#include "lldb/Symbol/RustASTContext.h" -#include "lldb/Symbol/SymbolFile.h" -#include "lldb/Symbol/TypeList.h" -#include "lldb/Symbol/VariableList.h" -#include "lldb/Target/Target.h" -#include "lldb/Utility/Status.h" -#include <functional> -#include <set> - -#include "Plugins/ExpressionParser/Clang/ASTStructExtractor.h" -#include "RustFunctionCaller.h" - -using namespace lldb_private::rust; -using namespace lldb_private; -using namespace lldb; -using namespace llvm; - -static std::set<std::string> primitive_type_names - { - "bool", "char", - "u8", "u16", "u32", "u64", "u128", - "i8", "i16", "i32", "i64", "i128", - "f32", "f64" - }; - -static RustASTContext * -GetASTContext(CompilerType type, Status &error) { - RustASTContext *result = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!result) { - error.SetErrorString("not a Rust type!?"); - } - return result; -} - -static RustASTContext * -GetASTContext(ValueObjectSP val, Status &error) { - return GetASTContext(val->GetCompilerType(), error); -} - -static RustASTContext * -GetASTContext(ExecutionContext &ctxt, Status &error) { - Target *target = ctxt.GetTargetPtr(); - TypeSystem *sys = target->GetScratchTypeSystemForLanguage(&error, eLanguageTypeRust); - if (!sys) { - return nullptr; - } - RustASTContext *result = llvm::dyn_cast_or_null<RustASTContext>(sys); - if (!result) { - error.SetErrorString("not a Rust type!?"); - } - return result; -} - -static ValueObjectSP -CreateValueFromScalar(ExecutionContext &exe_ctx, Scalar &scalar, CompilerType type, - Status &error) { - DataExtractor data; - if (!scalar.GetData(data)) { - error.SetErrorString("could not get data from scalar"); - return ValueObjectSP(); - } - ValueObjectSP result = ValueObject::CreateValueObjectFromData("", data, exe_ctx, type); - if (!result) { - error.SetErrorString("could not create value object"); - } - return result; -} - -static ValueObjectSP -CreateValueInMemory(ExecutionContext &exe_ctx, CompilerType type, Status &error) { - if (!exe_ctx.HasProcessScope()) { - error.SetErrorString("need a running inferior to evaluate this"); - return ValueObjectSP(); - } - - Process *proc = exe_ctx.GetProcessPtr(); - uint64_t size = type.GetByteSize(proc).getValueOr(0); - addr_t addr = proc->AllocateMemory(size, - lldb::ePermissionsWritable | lldb::ePermissionsReadable, - error); - if (addr == LLDB_INVALID_ADDRESS) { - return ValueObjectSP(); - } - - return ValueObject::CreateValueObjectFromAddress("", addr, exe_ctx, type); -} - -static bool -SetField(const ValueObjectSP &object, const char *name, uint64_t value, Status &error) { - Scalar scalar(value); - DataExtractor data; - if (!scalar.GetData(data)) { - error.SetErrorString("could not get data from scalar"); - return false; - } - - ValueObjectSP child = object->GetChildMemberWithName(ConstString(name), true); - if (!child) { - error.SetErrorStringWithFormat("could not find child named \"%s\"", name); - return false; - } - return child->SetData(data, error); -} - -static bool -SetField(const ValueObjectSP &object, const char *name, const ValueObjectSP &value, - Status &error) { - DataExtractor data; - if (!value->GetData(data, error)) { - return false; - } - - ValueObjectSP child = object->GetChildMemberWithName(ConstString(name), true); - if (!child) { - error.SetErrorStringWithFormat("could not find child named \"%s\"", name); - return false; - } - return child->SetData(data, error); -} - -static CompilerType -GetTypeByName(ExecutionContext &exe_ctx, const char *name, Status &error) { - Target *target = exe_ctx.GetTargetPtr(); - if (!target) { - error.SetErrorString("could not get target to look up type"); - return CompilerType(); - } - - TypeList type_list; - llvm::DenseSet<SymbolFile *> searched_symbol_files; - uint32_t num_matches = target->GetImages().FindTypes(nullptr, ConstString(name), true, - 2, searched_symbol_files, type_list); - if (num_matches > 0) { - return type_list.GetTypeAtIndex(0)->GetFullCompilerType(); - } - error.SetErrorStringWithFormat("could not find type \"%s\"", name); - return CompilerType(); -} - -ValueObjectSP -lldb_private::rust::UnaryDereference(ExecutionContext &exe_ctx, ValueObjectSP addr, Status &error) { - return addr->Dereference(error); -} - -ValueObjectSP -lldb_private::rust::UnaryAddr(ExecutionContext &exe_ctx, ValueObjectSP val, Status &error) { - return val->AddressOf(error); -} - -ValueObjectSP -lldb_private::rust::UnaryPlus(ExecutionContext &exe_ctx, ValueObjectSP val, Status &error) { - if (RustASTContext *ast = GetASTContext(val, error)) { - CompilerType type = val->GetCompilerType(); - if (type.IsScalarType() && !ast->IsBooleanType(type.GetOpaqueQualType())) { - return val; - } - error.SetErrorString("not a scalar type"); - } - return ValueObjectSP(); -} - -ValueObjectSP -lldb_private::rust::UnaryNegate(ExecutionContext &exe_ctx, ValueObjectSP val, Status &error) { - if (RustASTContext *ast = GetASTContext(val, error)) { - CompilerType type = val->GetCompilerType(); - if (!type.IsScalarType() || ast->IsBooleanType(type.GetOpaqueQualType())) { - error.SetErrorString("not a scalar type"); - return ValueObjectSP(); - } - - Scalar scalar; - if (!val->ResolveValue(scalar)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - if (!scalar.UnaryNegate()) { - error.SetErrorString("could not negate scalar value"); - return ValueObjectSP(); - } - - return CreateValueFromScalar(exe_ctx, scalar, type, error); - } - return ValueObjectSP(); -} - -ValueObjectSP -lldb_private::rust::UnaryComplement(ExecutionContext &exe_ctx, ValueObjectSP val, Status &error) { - RustASTContext *ast = GetASTContext(val, error); - if (!ast) { - return ValueObjectSP(); - } - - CompilerType type = val->GetCompilerType(); - if (!type.IsScalarType()) { - error.SetErrorString("not a scalar type"); - return ValueObjectSP(); - } - - Scalar scalar; - if (!val->ResolveValue(scalar)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - - if (ast->IsBooleanType(type.GetOpaqueQualType())) { - scalar = Scalar(int(scalar.IsZero())); - } else if (!scalar.OnesComplement()) { - error.SetErrorString("could not negate scalar value"); - return ValueObjectSP(); - } - - return CreateValueFromScalar(exe_ctx, scalar, type, error); -} - -ValueObjectSP -lldb_private::rust::UnarySizeof(ExecutionContext &exe_ctx, ValueObjectSP val, Status &error) { - if (RustASTContext *ast = GetASTContext(val, error)) { - uint32_t ptr_size = ast->GetPointerByteSize(); - CompilerType type = ast->CreateIntegralType(ConstString("usize"), false, ptr_size); - Scalar size (val->GetByteSize()); - return CreateValueFromScalar(exe_ctx, size, type, error); - } - return ValueObjectSP(); -} - -template<typename T, bool ASSIGN> -ValueObjectSP -lldb_private::rust::BinaryOperation (ExecutionContext &exe_ctx, lldb::ValueObjectSP left, - lldb::ValueObjectSP right, Status &error) { - RustASTContext *ast = GetASTContext(left, error); - if (!ast) { - return ValueObjectSP(); - } - - if (!left->GetCompilerType().IsScalarType() || !right->GetCompilerType().IsScalarType()) { - error.SetErrorString("not a scalar type"); - return ValueObjectSP(); - } - - Scalar sleft, sright; - if (!left->ResolveValue(sleft) || !right->ResolveValue(sright)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - - Scalar result = T()(sleft, sright); - if (result.GetType() == Scalar::e_void) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - - size_t byte_size = result.GetByteSize(); - CompilerType type; - - // FIXME there has to be a better way. - switch (result.GetType()) { - case Scalar::e_sint: - case Scalar::e_slong: - case Scalar::e_slonglong: - type = ast->CreateIntrinsicIntegralType(true, byte_size); - break; - - case Scalar::e_uint: - case Scalar::e_ulong: - case Scalar::e_ulonglong: - type = ast->CreateIntrinsicIntegralType(false, byte_size); - break; - - case Scalar::e_float: - case Scalar::e_double: - if (byte_size == 4) { - type = ast->CreateFloatType(ConstString("f32"), byte_size); - break; - } else if (byte_size == 8) { - type = ast->CreateFloatType(ConstString("f64"), byte_size); - break; - } - /* FALL THROUGH */ - - default: - error.SetErrorString("unknown type resulting from binary operation"); - return ValueObjectSP(); - } - - ValueObjectSP result_obj = CreateValueFromScalar(exe_ctx, result, type, error); - - if (ASSIGN) { - DataExtractor data; - result_obj->GetData(data, error); - if (error.Fail()) { - return ValueObjectSP(); - } - - if (!left->SetData(data, error)) { - return ValueObjectSP(); - } - - result_obj = left; - } - - return result_obj; -} - -template<typename T> -ValueObjectSP -lldb_private::rust::Comparison (ExecutionContext &exe_ctx, lldb::ValueObjectSP left, - lldb::ValueObjectSP right, Status &error) { - RustASTContext *ast = GetASTContext(left, error); - if (!ast) { - return ValueObjectSP(); - } - - if (!left->GetCompilerType().IsScalarType() || !right->GetCompilerType().IsScalarType()) { - error.SetErrorString("not a scalar type"); - return ValueObjectSP(); - } - - Scalar sleft, sright; - if (!left->ResolveValue(sleft) || !right->ResolveValue(sright)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - - bool result = T()(sleft, sright); - Scalar value = int(result); - - CompilerType type = ast->CreateBoolType(ConstString("bool")); - return CreateValueFromScalar(exe_ctx, value, type, error); -} - -ValueObjectSP -lldb_private::rust::ArrayIndex (ExecutionContext &exe_ctx, lldb::ValueObjectSP left, - lldb::ValueObjectSP right, Status &error) { - if (!right->GetCompilerType().IsScalarType()) { - error.SetErrorString("not a scalar type"); - return ValueObjectSP(); - } - if (RustASTContext *ast = GetASTContext(right, error)) { - CompilerType type = right->GetCompilerType(); - if (ast->IsBooleanType(type.GetOpaqueQualType())) { - error.SetErrorString("not a scalar type"); - return ValueObjectSP(); - } - } - - Scalar sright; - if (!right->ResolveValue(sright)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - unsigned long index = sright.ULong(-1); - - ValueObjectSP result = left->GetChildAtIndex(index, true); - if (!result) { - error.SetErrorString("array index out of bounds"); - } - return result; -} - -CompilerDeclContext -RustPath::FrameDeclContext(ExecutionContext &exe_ctx, Status &error) { - StackFrame *frame = exe_ctx.GetFramePtr(); - if (frame == nullptr) { - // FIXME? - error.SetErrorString("no frame when looking up item"); - return CompilerDeclContext(); - } - - SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | - lldb::eSymbolContextBlock); - - if (sym_ctx.block) { - CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext(); - if (frame_decl_context) { - return frame_decl_context; - } - } - - error.SetErrorString("could not find frame's decl context"); - return CompilerDeclContext(); -} - -bool -RustPath::GetDeclContext(ExecutionContext &exe_ctx, Status &error, - CompilerDeclContext *result, bool *simple_name) { - *simple_name = true; - - RustASTContext *ast = GetASTContext(exe_ctx, error); - if (!ast) { - return false; - } - - CompilerDeclContext decl_ctx = FrameDeclContext(exe_ctx, error); - if (!decl_ctx) { - return false; - } - - if (!m_relative || m_self || m_supers > 0) { - for (int i = 0; !m_relative || i < m_supers; ++i) { - CompilerDeclContext next = ast->GetDeclContextDeclContext(decl_ctx); - if (next.GetName().IsEmpty()) { - if (!m_relative) { - break; - } - error.SetErrorString("too many 'super's"); - return false; - } - decl_ctx = next; - } - - *simple_name = false; - *result = decl_ctx; - } - - *result = decl_ctx; - return true; -} - -bool -RustPath::AppendGenerics(ExecutionContext &exe_ctx, Status &error, std::string *name) { - if (!m_generic_params.empty()) { - *name += "<"; - bool first = true; - for (const RustTypeExpressionUP ¶m : m_generic_params) { - CompilerType type = param->Evaluate(exe_ctx, error); - if (!type) { - return false; - } - if (!first) { - *name += ", "; - } - first = false; - *name += type.GetTypeName().AsCString(); - } - *name += ">"; - } - return true; -} - -bool -RustPath::FindDecl(ExecutionContext &exe_ctx, Status &error, - lldb::VariableSP *var, - lldb_private::Function **function, - std::string *base_name) { - bool simple_name; - CompilerDeclContext decl_ctx; - if (!GetDeclContext(exe_ctx, error, &decl_ctx, &simple_name)) { - return false; - } - - if (m_path.size() > 1) { - simple_name = false; - } - - std::string name = m_path.back(); - if (!AppendGenerics(exe_ctx, error, &name)) { - return false; - } - - if (simple_name) { - *base_name = name; - // ... but still look in the current context. - } - - RustASTContext *ast = GetASTContext(exe_ctx, error); - if (!ast) { - return false; - } - - // Construct the fully-qualified name. - std::vector<ConstString> fullname; - while (decl_ctx.GetName()) { - fullname.push_back(decl_ctx.GetName()); - decl_ctx = ast->GetDeclContextDeclContext(decl_ctx); - } - std::reverse(fullname.begin(), fullname.end()); - - auto end_iter = m_path.end() - 1; - for (auto iter = m_path.begin(); iter != end_iter; ++iter) { - fullname.push_back(ConstString(iter->c_str())); - } - - // Now try to find this name in each Module. - Target *target = exe_ctx.GetTargetPtr(); - if (!target) { - error.SetErrorString("could not get target to look up item"); - return false; - } - - VariableList var_list; - *function = nullptr; - ConstString cs_name(name.c_str()); - const ModuleList &module_list = target->GetImages(); - module_list.ForEach( - [&](const ModuleSP &mod) { - TypeSystem *ts = mod->GetTypeSystemForLanguage(eLanguageTypeRust); - if (!ts) { - return true; - } - SymbolFile *symbol_file = ts->GetSymbolFile(); - if (!symbol_file) { - return true; - } - - CompilerDeclContext found_ns; - for (const ConstString &ns_name : fullname) { - found_ns = symbol_file->FindNamespace(ns_name, &found_ns); - if (!found_ns) { - break; - } - } - - if (found_ns) { - mod->FindGlobalVariables(cs_name, &found_ns, 1, var_list); - - SymbolContextList context_list; - mod->FindFunctions(cs_name, &found_ns, eFunctionNameTypeBase, false, false, - true, context_list); - for (size_t i = 0; i < context_list.GetSize(); ++i) { - SymbolContext sym_context; - if (context_list.GetContextAtIndex(i, sym_context) && sym_context.function) { - *function = sym_context.function; - break; - } - } - } - - return var_list.GetSize() == 0 && *function == nullptr; - }); - - if (var_list.GetSize() != 0) { - *var = var_list.GetVariableAtIndex(0); - } else if (*function != nullptr) { - // Ok. - } else { - if (base_name->empty()) { - error.SetErrorStringWithFormat("could not find decl \"%s\"", name.c_str()); - } - return false; - } - - return true; -} - -CompilerType -RustPath::EvaluateAsType(ExecutionContext &exe_ctx, Status &error) { - std::string fullname = Name(exe_ctx, error); - if (error.Fail()) { - return CompilerType(); - } - return GetTypeByName(exe_ctx, fullname.c_str(), error); -} - -std::string -RustPath::Name(ExecutionContext &exe_ctx, Status &error) { - std::string name; - - CompilerDeclContext decl_ctx; - bool ignore; - if (!GetDeclContext(exe_ctx, error, &decl_ctx, &ignore)) { - return std::string(); - } - - if (m_path.size() == 1 && - primitive_type_names.find(m_path[0]) != primitive_type_names.end()) { - // Primitive. - return m_path[0]; - } - - // FIXME local types - name += "::"; - name += decl_ctx.GetScopeQualifiedName().AsCString(); - name += "::"; - - { - bool first = true; - for (const std::string &str : m_path) { - if (!first) { - name += "::"; - } - first = false; - name += str; - } - } - - if (!AppendGenerics(exe_ctx, error, &name)) { - return std::string(); - } - - return name; -} - -lldb::ValueObjectSP -RustLiteral::Evaluate(ExecutionContext &exe_ctx, Status &error) { - CompilerType type = m_type->Evaluate(exe_ctx, error); - if (!type) { - return ValueObjectSP(); - } - return CreateValueFromScalar(exe_ctx, m_value, type, error); -} - -lldb::ValueObjectSP -RustBooleanLiteral::Evaluate(ExecutionContext &exe_ctx, Status &error) { - RustASTContext *ast = GetASTContext(exe_ctx, error); - if (!ast) { - return ValueObjectSP(); - } - - CompilerType type = ast->CreateBoolType(ConstString("bool")); - Scalar val(m_value); - return CreateValueFromScalar(exe_ctx, val, type, error); -} - -lldb::ValueObjectSP -RustCharLiteral::Evaluate(ExecutionContext &exe_ctx, Status &error) { - RustASTContext *ast = GetASTContext(exe_ctx, error); - if (!ast) { - return ValueObjectSP(); - } - - CompilerType type; - if (m_is_byte) { - type = ast->CreateIntegralType(ConstString("u8"), false, 1); - } else { - type = ast->CreateCharType(); - } - Scalar val(m_value); - return CreateValueFromScalar(exe_ctx, val, type, error); -} - -lldb::ValueObjectSP -RustStringLiteral::Evaluate(ExecutionContext &exe_ctx, Status &error) { - RustASTContext *ast = GetASTContext(exe_ctx, error); - if (!ast) { - return ValueObjectSP(); - } - - CompilerType u8 = ast->CreateIntegralType(ConstString("u8"), false, 1); - CompilerType array_type = ast->CreateArrayType(u8, m_value.size()); - if (!array_type) { - error.SetErrorString("could not create array type"); - return ValueObjectSP(); - } - - // Byte order and address size don't matter here. - DataExtractor data(m_value.c_str(), m_value.size(), eByteOrderInvalid, 4); - ValueObjectSP array = CreateValueInMemory(exe_ctx, array_type, error); - if (!array) { - return array; - } - - if (!array->SetData(data, error)) { - return ValueObjectSP(); - } - - if (m_is_byte) { - return array; - } - - CompilerType str_type = GetTypeByName(exe_ctx, "&str", error); - if (!str_type) { - return ValueObjectSP(); - } - - ValueObjectSP str_val = CreateValueInMemory(exe_ctx, str_type, error); - if (!str_val) { - return str_val; - } - - if (!SetField(str_val, "data_ptr", array->GetAddressOf(), error) || - !SetField(str_val, "length", m_value.size(), error)) { - return ValueObjectSP(); - } - - return str_val; -} - -lldb::ValueObjectSP -RustPathExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - Target *target = exe_ctx.GetTargetPtr(); - if (!target) { - error.SetErrorString("could not get target to look up item"); - return ValueObjectSP(); - } - - StackFrame *frame = exe_ctx.GetFramePtr(); - if (frame == nullptr) { - // FIXME? - error.SetErrorString("no frame when looking up item"); - return ValueObjectSP(); - } - - std::string name; - VariableSP decl; - Function *function; - m_path->FindDecl(exe_ctx, error, &decl, &function, &name); - if (error.Fail()) { - return ValueObjectSP(); - } - - if (!name.empty()) { - VariableListSP frame_vars = frame->GetInScopeVariableList(false); - if (frame_vars) { - if (VariableSP var = frame_vars->FindVariable(ConstString(name.c_str()))) { - // FIXME dynamic? should come from the options, which we aren't - // passing in. - return frame->GetValueObjectForFrameVariable(var, eDynamicDontRunTarget); - } - } - } - if (decl) { - return frame->TrackGlobalVariable(decl, eDynamicDontRunTarget); - } - - if (function) { - Address addr = function->GetAddressRange().GetBaseAddress(); - addr_t address = addr.GetCallableLoadAddress(target); - CompilerType type = function->GetCompilerType().GetPointerType(); - Scalar saddr(address); - return CreateValueFromScalar(exe_ctx, saddr, type, error); - } - - // FIXME use the name - error.SetErrorStringWithFormat("could not find item"); - return ValueObjectSP(); -} - -lldb::ValueObjectSP -RustAndAndExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - ValueObjectSP vleft = m_left->Evaluate(exe_ctx, error); - if (!vleft) { - return vleft; - } - - if (RustASTContext *ast = GetASTContext(vleft, error)) { - CompilerType type = vleft->GetCompilerType(); - if (!ast->IsBooleanType(type.GetOpaqueQualType())) { - error.SetErrorString("not a boolean type"); - return ValueObjectSP(); - } - - Scalar sleft; - if (!vleft->ResolveValue(sleft)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - if (sleft.IsZero()) { - return vleft; - } - } else { - return ValueObjectSP(); - } - - ValueObjectSP vright = m_right->Evaluate(exe_ctx, error); - if (!vright) { - return vright; - } - - // FIXME should probably error out if not boolean. - return vright; -} - -lldb::ValueObjectSP -RustOrOrExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - ValueObjectSP vleft = m_left->Evaluate(exe_ctx, error); - if (!vleft) { - return vleft; - } - - if (RustASTContext *ast = GetASTContext(vleft, error)) { - CompilerType type = vleft->GetCompilerType(); - if (!ast->IsBooleanType(type.GetOpaqueQualType())) { - error.SetErrorString("not a boolean type"); - return ValueObjectSP(); - } - - Scalar sleft; - if (!vleft->ResolveValue(sleft)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - if (!sleft.IsZero()) { - return vleft; - } - } else { - return ValueObjectSP(); - } - - ValueObjectSP vright = m_right->Evaluate(exe_ctx, error); - if (!vright) { - return vright; - } - - // FIXME should probably error out if not boolean. - return vright; -} - -lldb::ValueObjectSP -RustFieldExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - ValueObjectSP left = m_left->Evaluate(exe_ctx, error); - if (!left) { - return left; - } - - // We always want to let users see the real type, because in Rust - // only trait objects and enums can be dynamic. - ValueObjectSP dynamic = left->GetDynamicValue(eDynamicCanRunTarget); - if (dynamic) { - left = dynamic; - } - - ValueObjectSP result = left->GetChildMemberWithName(ConstString(m_field.c_str()), true); - if (!result) { - error.SetErrorStringWithFormat("no field named %s", m_field.c_str()); - } - return result; -} - -lldb::ValueObjectSP -RustTupleFieldExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - ValueObjectSP left = m_left->Evaluate(exe_ctx, error); - if (!left) { - return left; - } - - // We always want to let users see the real type, because in Rust - // only trait objects and enums can be dynamic. - ValueObjectSP dynamic = left->GetDynamicValue(eDynamicCanRunTarget); - if (dynamic) { - left = dynamic; - } - - ValueObjectSP result = left->GetChildAtIndex(m_field, true); - if (!result) { - error.SetErrorStringWithFormat("no field number %d", m_field); - } - return result; -} - -lldb::ValueObjectSP -RustAssignment::Evaluate(ExecutionContext &exe_ctx, Status &error) { - ValueObjectSP left = m_left->Evaluate(exe_ctx, error); - if (!left) { - return left; - } - - ValueObjectSP right = m_right->Evaluate(exe_ctx, error); - if (!right) { - return right; - } - - DataExtractor data; - right->GetData(data, error); - if (error.Fail()) { - return ValueObjectSP(); - } - - if (!left->SetData(data, error)) { - return ValueObjectSP(); - } - - return left; -} - -lldb::ValueObjectSP -RustTupleExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - error.SetErrorString("tuple expressions unimplemented"); - return ValueObjectSP(); -} - -lldb::ValueObjectSP -RustArrayLiteral::Evaluate(ExecutionContext &exe_ctx, Status &error) { - error.SetErrorString("array literals unimplemented"); - return ValueObjectSP(); -} - -lldb::ValueObjectSP -RustArrayWithLength::Evaluate(ExecutionContext &exe_ctx, Status &error) { - ValueObjectSP value = m_value->Evaluate(exe_ctx, error); - if (!value) { - return value; - } - ValueObjectSP length = m_length->Evaluate(exe_ctx, error); - if (!length) { - return length; - } - Scalar slength; - if (!length->ResolveValue(slength)) { - error.SetErrorString("could not resolve scalar value"); - return ValueObjectSP(); - } - - RustASTContext *ast = GetASTContext(value, error); - if (!ast) { - return ValueObjectSP(); - } - CompilerType type = ast->CreateArrayType(value->GetCompilerType(), slength.UInt()); - if (!type) { - error.SetErrorString("could not create array type"); - return ValueObjectSP(); - } - - DataExtractor data; - value->GetData(data, error); - if (error.Fail()) { - return ValueObjectSP(); - } - - DataExtractor array_contents; - for (unsigned i = 0; i < slength.UInt(); ++i) { - if (!array_contents.Append(data)) { - error.SetErrorString("could not create array contents"); - return ValueObjectSP(); - } - } - - ValueObjectSP result = ValueObject::CreateValueObjectFromData("", array_contents, exe_ctx, type); - if (!result) { - error.SetErrorString("could not create array value object"); - } - return result; -} - -lldb::ValueObjectSP -RustCall::MaybeEvalTupleStruct(ExecutionContext &exe_ctx, Status &error) { - RustPathExpression *path_expr = m_func->AsPath(); - if (!path_expr) { - return ValueObjectSP(); - } - - CompilerType type = path_expr->EvaluateAsType(exe_ctx, error); - if (!type) { - // If we didn't find this as a type, keep trying as a function - // call. - error.Clear(); - return ValueObjectSP(); - } - - // After this point, all errors are real. - - RustASTContext *context = GetASTContext(type, error); - if (!context) { - return ValueObjectSP(); - } - if (!context->IsTupleType(type)) { - error.SetErrorString("not a tuple type"); - return ValueObjectSP(); - } - - if (m_exprs.size() < type.GetNumFields()) { - error.SetErrorString("not enough initializers for tuple"); - return ValueObjectSP(); - } else if (m_exprs.size() > type.GetNumFields()) { - error.SetErrorString("too many initializers for tuple"); - return ValueObjectSP(); - } - - ValueObjectSP result = CreateValueInMemory(exe_ctx, type, error); - if (!result) { - return result; - } - - for (size_t i = 0; i < m_exprs.size(); ++i) { - ValueObjectSP init_val = m_exprs[i]->Evaluate(exe_ctx, error); - if (!init_val) { - return init_val; - } - - DataExtractor data; - if (!init_val->GetData(data, error)) { - error.SetErrorString("could not get data from value"); - return ValueObjectSP(); - } - - ValueObjectSP child = result->GetChildAtIndex(i, true); - if (!child) { - error.SetErrorStringWithFormat("could not find child at index \"%d\"", int(i)); - return ValueObjectSP(); - } - if (!child->SetData(data, error)) { - return ValueObjectSP(); - } - } - - return result; -} - -lldb::ValueObjectSP -RustCall::Evaluate(ExecutionContext &exe_ctx, Status &error) { - error.Clear(); - ValueObjectSP result = MaybeEvalTupleStruct(exe_ctx, error); - if (result) { - return result; - } else if (error.Fail()) { - // This looked like a tuple struct expression but failed. - return result; - } - // This was not a tuple struct expression, so fall through to - // function call. - - ValueObjectSP func = m_func->Evaluate(exe_ctx, error); - if (!func) { - return func; - } - if (!func->GetCompilerType().IsFunctionPointerType()) { - error.SetErrorString("not calling a function"); - return ValueObjectSP(); - } - CompilerType function_type = func->GetCompilerType().GetPointeeType(); - CompilerType return_type = function_type.GetFunctionReturnType(); - - if (m_exprs.size() < function_type.GetNumberOfFunctionArguments()) { - error.SetErrorString("too few arguments to function"); - return ValueObjectSP(); - } else if (m_exprs.size() > function_type.GetNumberOfFunctionArguments()) { - error.SetErrorString("too many arguments to function"); - return ValueObjectSP(); - } - - addr_t addr = func->GetPointerValue(); - Address func_addr(addr); - - std::vector<ValueObjectSP> hold; - ValueList args; - for (auto &&arg : m_exprs) { - ValueObjectSP varg = arg->Evaluate(exe_ctx, error); - if (!varg) { - return varg; - } - hold.push_back(varg); - - // FIXME - mega hack to work around FunctionCaller limitation. - // Ideally this would be hidden in RustFunctionCaller at least. - if (varg->GetCompilerType().IsAggregateType()) { - varg = varg->AddressOf(error); - if (!varg) { - return varg; - } - hold.push_back(varg); - } - - args.PushValue(varg->GetValue()); - } - - // FIXME must cast each argument to the correct type here. - - // FIXME might be nice to stick the name in there. - RustFunctionCaller call(*exe_ctx.GetBestExecutionContextScope(), function_type, - return_type, func_addr, args, nullptr); - DiagnosticManager diags; - Value results; - ExpressionResults ef_result = - call.ExecuteFunction(exe_ctx, nullptr, EvaluateExpressionOptions(), diags, results); - - if (ef_result != eExpressionCompleted) { - // FIXME use the diagnostics. - error.SetErrorString("function call failed"); - return ValueObjectSP(); - } - - DataExtractor data; - if (!results.GetData(data)) { - error.SetErrorString("could not extract return value"); - return ValueObjectSP(); - } - - result = ValueObject::CreateValueObjectFromData("", data, exe_ctx, return_type); - if (!result) { - error.SetErrorString("could not create function return value object"); - } - return result; -} - -lldb::ValueObjectSP -RustCast::Evaluate(ExecutionContext &exe_ctx, Status &error) { - CompilerType type = m_type->Evaluate(exe_ctx, error); - if (!type) { - return ValueObjectSP(); - } - - ValueObjectSP value = m_expr->Evaluate(exe_ctx, error); - if (!value) { - return value; - } - - return value->Cast(type); -} - -lldb::ValueObjectSP -RustStructExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - CompilerType type = m_path->Evaluate(exe_ctx, error); - if (!type) { - return ValueObjectSP(); - } - RustASTContext *context = GetASTContext(type, error); - if (!context) { - return ValueObjectSP(); - } - // FIXME could tighten this to really ensure it is a struct and not - // an enum. - if (!type.IsAggregateType() || - type.IsArrayType(nullptr, nullptr, nullptr) || - context->IsTupleType(type)) { - error.SetErrorStringWithFormat("type \"%s\" is not a structure type", - type.GetDisplayTypeName().AsCString()); - return ValueObjectSP(); - } - - ValueObjectSP result = CreateValueInMemory(exe_ctx, type, error); - if (!result) { - return result; - } - - if (m_copy) { - ValueObjectSP copy = m_copy->Evaluate(exe_ctx, error); - if (!copy) { - return copy; - } - - DataExtractor data; - copy->GetData(data, error); - if (error.Fail()) { - return ValueObjectSP(); - } - - if (!result->SetData(data, error)) { - return ValueObjectSP(); - } - } else { - if (m_inits.size() != type.GetNumFields()) { - error.SetErrorStringWithFormat("some initializers missing for \"%s\"", - type.GetDisplayTypeName().AsCString()); - return ValueObjectSP(); - } - } - - for (const auto &init : m_inits) { - ValueObjectSP init_val = init.second->Evaluate(exe_ctx, error); - if (!init_val) { - return init_val; - } - if (!SetField(result, init.first.c_str(), init_val, error)) { - return ValueObjectSP(); - } - } - - return result; -} - -lldb::ValueObjectSP -RustRangeExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - ValueObjectSP left, right; - - if (m_left) { - left = m_left->Evaluate(exe_ctx, error); - if (!left) { - return left; - } - } - if (m_right) { - right = m_right->Evaluate(exe_ctx, error); - if (!right) { - return right; - } - } - - std::string name; - CompilerType element_type; - if (left) { - if (right) { - name = m_inclusive ? "::core::ops::range::RangeInclusive" : "::core::ops::range::Range"; - // FIXME this check seems wrong - if (left->GetCompilerType() != right->GetCompilerType()) { - // FIXME also we could be friendlier about integer promotion - // here. - error.SetErrorString("operands of \"..\" do not have same type"); - return ValueObjectSP(); - } - } else { - name = "::core::ops::range::RangeFrom"; - } - element_type = left->GetCompilerType(); - } else if (right) { - name = m_inclusive ? "::core::ops::range::RangeToInclusive" : "::core::ops::range::RangeTo"; - element_type = right->GetCompilerType(); - } else { - name = "::core::ops::range::RangeFull"; - } - assert(!name.empty()); - - if (element_type) { - name = name + "<" + element_type.GetTypeName().AsCString() + ">"; - } - - CompilerType range_type = GetTypeByName(exe_ctx, name.c_str(), error); - if (!range_type) { - return ValueObjectSP(); - } - - ValueObjectSP result = CreateValueInMemory(exe_ctx, range_type, error); - if (!result) { - return result; - } - - if (left && !SetField(result, "start", left, error)) { - return ValueObjectSP(); - } - if (right && !SetField(result, "end", right, error)) { - return ValueObjectSP(); - } - - return result; -} - -//////////////////////////////////////////////////////////////// -// Types - -CompilerType -RustArrayTypeExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - RustASTContext *context = GetASTContext(exe_ctx, error); - if (!context) { - return CompilerType(); - } - - CompilerType element = m_element->Evaluate(exe_ctx, error); - if (!element) { - return element; - } - - return context->CreateArrayType(element, m_len); -} - -CompilerType -RustPointerTypeExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - CompilerType target = m_target->Evaluate(exe_ctx, error); - if (!target) { - return target; - } - // FIXME references - return target.GetPointerType(); -} - -CompilerType -RustSliceTypeExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - error.SetErrorString("slice type lookup unimplemented"); - return CompilerType(); -} - -CompilerType -RustFunctionTypeExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - RustASTContext *context = GetASTContext(exe_ctx, error); - if (!context) { - return CompilerType(); - } - - CompilerType ret = m_result->Evaluate(exe_ctx, error); - if (!ret) { - return ret; - } - - std::vector<CompilerType> args; - for (const RustTypeExpressionUP &arg : m_arguments) { - CompilerType argtype = arg->Evaluate(exe_ctx, error); - if (!argtype) { - return argtype; - } - args.push_back(argtype); - } - - std::vector<CompilerType> empty; - return context->CreateFunctionType(ConstString(""), ret, std::move(args), std::move(empty)); -} - -CompilerType -RustTupleTypeExpression::Evaluate(ExecutionContext &exe_ctx, Status &error) { - error.SetErrorString("tuple type lookup unimplemented"); - return CompilerType(); -} - -//////////////////////////////////////////////////////////////// -// Output - -Stream &lldb_private::operator<< (Stream &stream, const RustExpressionUP &expr) { - if (expr) { - expr->print(stream); - } - return stream; -} - -Stream &lldb_private::operator<< (Stream &stream, const RustTypeExpressionUP &type) { - type->print(stream); - return stream; -} - -Stream &lldb_private::operator<< (Stream &stream, const Scalar &value) { - value.GetValue(&stream, false); - return stream; -} - -Stream &lldb_private::operator<< (Stream &stream, - const std::pair<std::string, RustExpressionUP> &value) { - return stream << value.first << ": " << value.second; -} - -//////////////////////////////////////////////////////////////// -// The parser - -template<char C, RustUnaryOperator OP> -RustExpressionUP Parser::Unary(Status &error) { - Advance(); - RustExpressionUP result = Term(error); - if (!result) { - return result; - } - return llvm::make_unique<RustUnaryExpression<C, OP>>(std::move(result)); -} - -bool Parser::ExprList(std::vector<RustExpressionUP> *exprs, Status &error) { - while (true) { - RustExpressionUP expr = Expr(error); - if (!expr) { - return false; - } - - exprs->push_back(std::move(expr)); - if (CurrentToken().kind != ',') { - break; - } - Advance(); - } - - return true; -} - -// This handles both a parenthesized expression and a tuple -// expression. -RustExpressionUP Parser::Parens(Status &error) { - assert(CurrentToken().kind == '('); - Advance(); - - if (CurrentToken().kind == ')') { - // Unit tuple. - Advance(); - return llvm::make_unique<RustTupleExpression>(std::vector<RustExpressionUP>()); - } - - RustExpressionUP expr = Expr(error); - if (!expr) { - return expr; - } - - if (CurrentToken().kind == ')') { - // Parenthesized expression. - Advance(); - return expr; - } else if (CurrentToken().kind != ',') { - error.SetErrorString("expected ')' or ','"); - return RustExpressionUP(); - } - - std::vector<RustExpressionUP> exprs; - exprs.push_back(std::move(expr)); - Advance(); - - if (CurrentToken().kind != ')') { - if (!ExprList(&exprs, error)) { - return RustExpressionUP(); - } - } - - if (CurrentToken().kind != ')') { - error.SetErrorString("expected ')'"); - return RustExpressionUP(); - } - Advance(); - - return llvm::make_unique<RustTupleExpression>(std::move(exprs)); -} - -RustExpressionUP Parser::Array(Status &error) { - assert(CurrentToken().kind == '['); - Advance(); - - // This doesn't affect us, so parse and ignore. - if (CurrentToken().kind == MUT) { - Advance(); - } - - RustExpressionUP expr = Expr(error); - if (!expr) { - return expr; - } - - RustExpressionUP result; - if (CurrentToken().kind == ';') { - Advance(); - - RustExpressionUP length = Expr(error); - if (!length) { - return length; - } - - result = llvm::make_unique<RustArrayWithLength>(std::move(expr), std::move(length)); - } else if (CurrentToken().kind == ',') { - Advance(); - std::vector<RustExpressionUP> exprs; - exprs.push_back(std::move(expr)); - - if (ExprList(&exprs, error)) { - result = llvm::make_unique<RustArrayLiteral>(std::move(exprs)); - } - } else { - error.SetErrorString("expected ',' or ';'"); - return result; - } - - if (CurrentToken().kind != ']') { - error.SetErrorString("expected ']'"); - result.reset(); - } else { - Advance(); - } - - return result; -} - -RustExpressionUP Parser::Field(RustExpressionUP &&lhs, Status &error) { - assert(CurrentToken().kind == '.'); - Advance(); - - RustExpressionUP result; - if (CurrentToken().kind == IDENTIFIER) { - result = llvm::make_unique<RustFieldExpression>(std::move(lhs), - CurrentToken().str); - Advance(); - } else if (CurrentToken().kind == INTEGER) { - result = llvm::make_unique<RustTupleFieldExpression>(std::move(lhs), - CurrentToken().uinteger.getValue()); - Advance(); - } else { - error.SetErrorString("identifier or integer expected"); - } - - return result; -} - -RustExpressionUP Parser::Call(RustExpressionUP &&func, Status &error) { - assert(CurrentToken().kind == '('); - Advance(); - - std::vector<RustExpressionUP> exprs; - if (CurrentToken().kind != ')') { - if (!ExprList(&exprs, error)) { - return RustExpressionUP(); - } - } - - if (CurrentToken().kind != ')') { - error.SetErrorString("expected ')'"); - return RustExpressionUP(); - } - Advance(); - - return llvm::make_unique<RustCall>(std::move(func), std::move(exprs)); -} - -RustExpressionUP Parser::Index(RustExpressionUP &&array, Status &error) { - assert(CurrentToken().kind == '['); - Advance(); - - RustExpressionUP idx = Expr(error); - if (!idx) { - return idx; - } - - if (CurrentToken().kind != ']') { - error.SetErrorString("expected ']'"); - return RustExpressionUP(); - } - Advance(); - - return llvm::make_unique<RustBinaryExpression<'@', ArrayIndex>>(std::move(array), - std::move(idx)); -} - -RustExpressionUP Parser::Struct(RustTypeExpressionUP &&path, Status &error) { - assert(CurrentToken().kind == '{'); - Advance(); - - std::vector<std::pair<std::string, RustExpressionUP>> inits; - RustExpressionUP copy; - while (CurrentToken().kind != '}') { - if (CurrentToken().kind == IDENTIFIER) { - std::string field = std::move(CurrentToken().str); - Advance(); - - RustExpressionUP value; - if (CurrentToken().kind == ',' || CurrentToken().kind == '}') { - // Plain "field". - std::string field_copy = field; - value = llvm::make_unique<RustPathExpression>(std::move(field_copy)); - } else if (CurrentToken().kind != ':') { - error.SetErrorString("':' expected"); - return RustExpressionUP(); - } else { - Advance(); - - value = Expr(error); - if (!value) { - return value; - } - } - - // FIXME look for duplicates. - - inits.emplace_back(std::move(field), std::move(value)); - } else if (CurrentToken().kind == DOTDOT) { - // FIXME technically this can't occur first - a field - // initializer is needed. - Advance(); - copy = Expr(error); - if (!copy) { - return copy; - } - break; - } else { - error.SetErrorString("identifier or '..' expected"); - return RustExpressionUP(); - } - - if (CurrentToken().kind != ',') { - break; - } - Advance(); - } - - if (CurrentToken().kind != '}') { - error.SetErrorString("'}' expected"); - return RustExpressionUP(); - } - Advance(); - - return llvm::make_unique<RustStructExpression>(std::move(path), std::move(inits), - std::move(copy)); -} - -RustExpressionUP Parser::Path(Status &error) { - bool relative = true; - int supers = 0; - - bool saw_self = CurrentToken().kind == SELF; - if (saw_self) { - Advance(); - if (CurrentToken().kind != COLONCOLON) { - // This one can't be a struct expression, so we just return - // directly. - return llvm::make_unique<RustPathExpression>(std::string("self")); - } - } - - if (CurrentToken().kind == COLONCOLON) { - if (!saw_self) { - relative = false; - } - Advance(); - } - - if (relative) { - while (CurrentToken().kind == SUPER) { - ++supers; - Advance(); - if (CurrentToken().kind != COLONCOLON) { - error.SetErrorString("'::' expected after 'super'"); - return RustExpressionUP(); - } - Advance(); - } - } - - std::vector<std::string> path; - while (CurrentToken().kind == IDENTIFIER) { - path.emplace_back(std::move(CurrentToken().str)); - Advance(); - if (CurrentToken().kind != COLONCOLON) { - break; - } - Advance(); - if (CurrentToken().kind != IDENTIFIER && CurrentToken().kind != '<') { - error.SetErrorString("identifier or '<' expected"); - return RustExpressionUP(); - } - } - - std::vector<RustTypeExpressionUP> type_list; - if (CurrentToken().kind == '<') { - if (!BracketTypeList(&type_list, error)) { - return RustExpressionUP(); - } - } - - if (path.empty()) { - error.SetErrorString("identifier expected"); - return RustExpressionUP(); - } - - if (CurrentToken().kind == '{') { - RustPathUP name_path = llvm::make_unique<RustPath>(saw_self, relative, supers, - std::move(path), std::move(type_list), - true); - RustTypeExpressionUP type_path = - llvm::make_unique<RustPathTypeExpression>(std::move(name_path)); - return Struct(std::move(type_path), error); - } - - RustPathUP name_path = llvm::make_unique<RustPath>(saw_self, relative, supers, - std::move(path), std::move(type_list)); - return llvm::make_unique<RustPathExpression>(std::move(name_path)); -} - -RustExpressionUP Parser::Sizeof(Status &error) { - assert(CurrentToken().kind == SIZEOF); - Advance(); - - if (CurrentToken().kind != '(') { - error.SetErrorString("'(' expected"); - return RustExpressionUP(); - } - Advance(); - - RustExpressionUP expr = Expr(error); - if (!expr) { - return expr; - } - - if (CurrentToken().kind != ')') { - error.SetErrorString("')' expected"); - return RustExpressionUP(); - } - Advance(); - - return llvm::make_unique<RustUnaryExpression<'@', UnarySizeof>>(std::move(expr)); -} - -bool Parser::StartsTerm() { - // Must be kept in parallel with the switch in Term. - switch (CurrentToken().kind) { - case INTEGER: - case FLOAT: - case STRING: - case BYTESTRING: - case CHAR: - case BYTE: - case TRUE: - case FALSE: - case '[': - case '(': - case SUPER: - case SELF: - case IDENTIFIER: - case COLONCOLON: - case SIZEOF: - case '*': - case '+': - case '-': - case '!': - case '&': - return true; - - default: - return false; - } -} - -RustExpressionUP Parser::Term(Status &error) { - RustExpressionUP term; - - // Double-check StartsTerm. - bool starts = StartsTerm(); - - switch (CurrentToken().kind) { - case INTEGER: { - const char *suffix = CurrentToken().number_suffix; - if (!suffix) { - suffix = "i32"; - } - RustTypeExpressionUP type = llvm::make_unique<RustPathTypeExpression>(suffix); - term = llvm::make_unique<RustLiteral>(CurrentToken().uinteger.getValue(), std::move(type)); - Advance(); - break; - } - - case FLOAT: { - const char *suffix = CurrentToken().number_suffix; - if (!suffix) { - suffix = "f64"; - } - RustTypeExpressionUP type = llvm::make_unique<RustPathTypeExpression>(suffix); - term = llvm::make_unique<RustLiteral>(CurrentToken().dvalue.getValue(), std::move(type)); - Advance(); - break; - } - - case STRING: - case BYTESTRING: - term = llvm::make_unique<RustStringLiteral>(std::move(CurrentToken().str), - CurrentToken().kind == BYTESTRING); - Advance(); - break; - - case CHAR: - case BYTE: - term = llvm::make_unique<RustCharLiteral>(CurrentToken().uinteger.getValue(), - CurrentToken().kind == BYTE); - Advance(); - break; - - case TRUE: - case FALSE: - term = llvm::make_unique<RustBooleanLiteral>(CurrentToken().kind == TRUE); - Advance(); - break; - - case '[': - term = Array(error); - break; - - case '(': - term = Parens(error); - break; - - case SUPER: - case SELF: - case IDENTIFIER: - case COLONCOLON: - term = Path(error); - break; - - case SIZEOF: - assert(starts); - return Sizeof(error); - - case '*': - term = Unary<'*', UnaryDereference>(error); - break; - case '+': - term = Unary<'+', UnaryPlus>(error); - break; - case '-': - term = Unary<'-', UnaryNegate>(error); - break; - case '!': - term = Unary<'!', UnaryComplement>(error); - break; - - case '&': - // FIXME should handle slices here. - term = Unary<'&', UnaryAddr>(error); - break; - - case INVALID: - assert(!starts); - error.SetErrorString(CurrentToken().str); - return RustExpressionUP(); - - case THATSALLFOLKS: - assert(!starts); - error.SetErrorString("unexpected EOF"); - return RustExpressionUP(); - - default: - assert(!starts); - error.SetErrorString("unexpected token"); - return RustExpressionUP(); - } - - assert(starts); - - bool done = false; - while (!done) { - switch (CurrentToken().kind) { - case AS: { - Advance(); - RustTypeExpressionUP type = Type(error); - if (!type) { - return RustExpressionUP(); - } - term = llvm::make_unique<RustCast>(std::move(type), std::move(term)); - break; - } - - case '.': - term = Field(std::move(term), error); - break; - - case '[': - term = Index(std::move(term), error); - break; - - case '(': - term = Call(std::move(term), error); - break; - - default: - done = true; - break; - } - - if (!term) { - return term; - } - } - - return term; -} - -#define BINOP(Tag, What) \ - RustBinaryExpression< Tag, BinaryOperation< What<Scalar>, false > > -#define COMP(Tag, What) \ - RustBinaryExpression< Tag, Comparison< What<Scalar> > > -#define ASSIGN(Tag, What) \ - RustAssignExpression< Tag, BinaryOperation< What<Scalar>, true > > - -// Couldn't find these in <functional>. - -template<typename T> -class left_shift { -public: - T operator()(const T &l, const T&r) { - return l << r; - } -}; - -template<typename T> -class right_shift { -public: - T operator()(const T &l, const T&r) { - return l >> r; - } -}; - - -// Binary operators. Each line has the form: -// DEFINE(token, precedence, type) -#define BINARY_OPERATORS \ - DEFINE(OROR, 3, RustOrOrExpression) \ - DEFINE(ANDAND, 4, RustAndAndExpression) \ - DEFINE(EQEQ, 5, COMP(EQEQ, std::equal_to)) \ - DEFINE(NOTEQ, 5, COMP(NOTEQ, std::not_equal_to)) \ - DEFINE(LTEQ, 5, COMP(LTEQ, std::less_equal)) \ - DEFINE(GTEQ, 5, COMP(GTEQ, std::greater_equal)) \ - DEFINE(LSH, 9, BINOP(LSH, left_shift)) \ - DEFINE(RSH, 9, BINOP(RSH, right_shift)) \ - DEFINE(PLUS_EQ, 1, ASSIGN(PLUS_EQ, std::plus)) \ - DEFINE(MINUS_EQ, 1, ASSIGN(MINUS_EQ, std::minus)) \ - DEFINE(SLASH_EQ, 1, ASSIGN(SLASH_EQ, std::divides)) \ - DEFINE(STAR_EQ, 1, ASSIGN(STAR_EQ, std::multiplies)) \ - DEFINE(PERCENT_EQ, 1, ASSIGN(PERCENT_EQ, std::modulus)) \ - DEFINE(RSH_EQ, 1, ASSIGN(RSH_EQ, right_shift)) \ - DEFINE(LSH_EQ, 1, ASSIGN(LSH_EQ, left_shift)) \ - DEFINE(AND_EQ, 1, ASSIGN(AND_EQ, std::bit_and)) \ - DEFINE(OR_EQ, 1, ASSIGN(OR_EQ, std::bit_or)) \ - DEFINE(XOR_EQ, 1, ASSIGN(XOR_EQ, std::bit_xor)) \ - DEFINE('|', 6, BINOP('|', std::bit_or)) \ - DEFINE('&', 8, BINOP('&', std::bit_and)) \ - DEFINE('=', 1, RustAssignment) \ - DEFINE('<', 5, COMP('<', std::less)) \ - DEFINE('>', 5, COMP('>', std::greater)) \ - DEFINE('+', 10, BINOP('+', std::plus)) \ - DEFINE('-', 10, BINOP('-', std::minus)) \ - DEFINE('*', 11, BINOP('*', std::multiplies)) \ - DEFINE('/', 11, BINOP('/', std::divides)) \ - DEFINE('%', 11, BINOP('%', std::modulus)) - -RustExpressionUP Parser::Binary(Status &error) { - struct Operation { - int precedence; - int op; - RustExpressionUP term; - - Operation(int precedence_, int op_, RustExpressionUP &&term_) - : precedence(precedence_), - op(op_), - term(std::move(term_)) - { - } - }; - - RustExpressionUP term = Term(error); - if (!term) { - return term; - } - - std::vector<Operation> operations; - operations.emplace_back(0, -1, std::move(term)); - - bool done = false; - while (!done) { - int precedence; - int kind = CurrentToken().kind; - - switch (kind) { -#define DEFINE(Token, Prec, Type) \ - case Token: precedence = Prec; Advance(); break; - - BINARY_OPERATORS -#undef DEFINE - - case INVALID: - error.SetErrorString(CurrentToken().str); - return RustExpressionUP(); - - case THATSALLFOLKS: - default: - // Not a binary operator, so we're going to return. - done = true; - // Arrange to pop all the operations now. - precedence = 0; - break; - } - - RustExpressionUP rhs; - if (!done) { - rhs = Term(error); - if (!rhs) { - return rhs; - } - } - - while (precedence < operations.back().precedence) { - Operation top = std::move(operations.back()); - operations.pop_back(); - - assert(!operations.empty()); - Operation &lhs = operations.back(); - - switch (top.op) { -#define DEFINE(Token, Prec, Type) \ - case Token: \ - lhs.term = llvm::make_unique<Type>(std::move(lhs.term), std::move(top.term)); \ - break; - - BINARY_OPERATORS -#undef DEFINE - - default: - assert(0); - } - } - - // This won't be true in the "done" case. - if (rhs) { - operations.emplace_back(precedence, kind, std::move(rhs)); - } - } - - assert(operations.size() == 1); - return std::move(operations.back().term); -} - -RustExpressionUP Parser::Range(Status &error) { - RustExpressionUP lhs; - if (CurrentToken().kind != DOTDOT && CurrentToken().kind != DOTDOTEQ) { - lhs = Binary(error); - if (!lhs) { - return lhs; - } - } - - if (CurrentToken().kind != DOTDOT && CurrentToken().kind != DOTDOTEQ) { - return lhs; - } - bool is_inclusive = CurrentToken().kind == DOTDOTEQ; - Advance(); - - // An inclusive range requires an expression, but an exclusive range - // does not. - RustExpressionUP rhs; - if (is_inclusive || StartsTerm()) { - rhs = Binary(error); - if (!rhs) { - return rhs; - } - } - - return llvm::make_unique<RustRangeExpression>(std::move(lhs), std::move(rhs), is_inclusive); -} - -//////////////////////////////////////////////////////////////// -// Type parsing - -RustTypeExpressionUP Parser::ArrayType(Status &error) { - assert(CurrentToken().kind == '['); - Advance(); - - RustTypeExpressionUP element = Type(error); - if (!element) { - return element; - } - - if (CurrentToken().kind != ';') { - error.SetErrorString("';' expected"); - return RustTypeExpressionUP(); - } - Advance(); - - if (CurrentToken().kind != INTEGER) { - error.SetErrorString("integer expected"); - return RustTypeExpressionUP(); - } - - uint64_t len = CurrentToken().uinteger.getValue(); - Advance(); - - if (CurrentToken().kind != ']') { - error.SetErrorString("']' expected"); - return RustTypeExpressionUP(); - } - Advance(); - - return llvm::make_unique<RustArrayTypeExpression>(std::move(element), len); -} - -RustTypeExpressionUP Parser::ReferenceType(Status &error) { - assert(CurrentToken().kind == '&'); - Advance(); - - bool is_mut = false; - if (CurrentToken().kind == MUT) { - is_mut = true; - Advance(); - } - - bool is_slice = false; - if (CurrentToken().kind == '[') { - is_slice = true; - Advance(); - } - - RustTypeExpressionUP target = Type(error); - if (!target) { - return target; - } - - if (is_slice) { - if (CurrentToken().kind != ']') { - error.SetErrorString("']' expected"); - return RustTypeExpressionUP(); - } - Advance(); - - return llvm::make_unique<RustSliceTypeExpression>(std::move(target), is_mut); - } - - return llvm::make_unique<RustPointerTypeExpression>(std::move(target), true, is_mut); -} - -RustTypeExpressionUP Parser::PointerType(Status &error) { - assert(CurrentToken().kind == '*'); - Advance(); - - bool is_mut = false; - if (CurrentToken().kind == MUT) { - is_mut = true; - } else if (CurrentToken().kind != CONST) { - error.SetErrorString("expected 'mut' or 'const'"); - return RustTypeExpressionUP(); - } - Advance(); - - RustTypeExpressionUP target = Type(error); - if (!target) { - return target; - } - - return llvm::make_unique<RustPointerTypeExpression>(std::move(target), false, is_mut); -} - -bool Parser::TypeList(std::vector<RustTypeExpressionUP> *type_list, Status &error) { - while (true) { - RustTypeExpressionUP t = Type(error); - if (!t) { - return false; - } - type_list->push_back(std::move(t)); - if (CurrentToken().kind != ',') { - break; - } - Advance(); - } - - return true; -} - -bool Parser::ParenTypeList(std::vector<RustTypeExpressionUP> *type_list, Status &error) { - if (CurrentToken().kind != '(') { - error.SetErrorStringWithFormat("'(' expected"); - return false; - } - Advance(); - - if (CurrentToken().kind != ')') { - if (!TypeList(type_list, error)) { - return false; - } - } - - if (CurrentToken().kind != ')') { - error.SetErrorStringWithFormat("')' expected"); - return false; - } - Advance(); - - return true; -} - -bool Parser::BracketTypeList(std::vector<RustTypeExpressionUP> *type_list, Status &error) { - if (CurrentToken().kind != '<') { - error.SetErrorStringWithFormat("'<' expected"); - return false; - } - Advance(); - - if (CurrentToken().kind != '>' && CurrentToken().kind != RSH) { - if (!TypeList(type_list, error)) { - return false; - } - } - - if (CurrentToken().kind == RSH) { - ReplaceTokenKind('>'); - } else if (CurrentToken().kind != '>') { - error.SetErrorStringWithFormat("'>' expected"); - return false; - } else { - Advance(); - } - - return true; -} - -RustTypeExpressionUP Parser::FunctionType(Status &error) { - assert(CurrentToken().kind == FN); - Advance(); - - std::vector<RustTypeExpressionUP> type_list; - if (!ParenTypeList(&type_list, error)) { - return RustTypeExpressionUP(); - } - - if (CurrentToken().kind != ARROW) { - error.SetErrorString("'->' expected"); - return RustTypeExpressionUP(); - } - Advance(); - - RustTypeExpressionUP return_type = Type(error); - if (!return_type) { - return return_type; - } - - return llvm::make_unique<RustFunctionTypeExpression>(std::move(return_type), - std::move(type_list)); -} - -RustTypeExpressionUP Parser::TupleType(Status &error) { - assert(CurrentToken().kind == '('); - // Don't advance here, ParenTypeList is going to deal with the open - // paren. - - std::vector<RustTypeExpressionUP> type_list; - if (!ParenTypeList(&type_list, error)) { - return RustTypeExpressionUP(); - } - - return llvm::make_unique<RustTupleTypeExpression>(std::move(type_list)); -} - -RustTypeExpressionUP Parser::TypePath(Status &error) { - bool relative = true; - int supers = 0; - - bool saw_self = CurrentToken().kind == SELF; - if (saw_self) { - Advance(); - if (CurrentToken().kind != COLONCOLON) { - error.SetErrorString("'::' expected"); - return RustTypeExpressionUP(); - } - } - - if (CurrentToken().kind == COLONCOLON) { - if (!saw_self) { - relative = false; - } - Advance(); - } - - if (relative) { - while (CurrentToken().kind == SUPER) { - ++supers; - Advance(); - if (CurrentToken().kind != COLONCOLON) { - error.SetErrorString("'::' expected after 'super'"); - return RustTypeExpressionUP(); - } - Advance(); - } - } - - std::vector<std::string> path; - while (CurrentToken().kind == IDENTIFIER) { - path.emplace_back(std::move(CurrentToken().str)); - Advance(); - if (CurrentToken().kind != COLONCOLON) { - break; - } - Advance(); - if (CurrentToken().kind != IDENTIFIER && CurrentToken().kind != '<') { - error.SetErrorString("identifier or '<' expected"); - return RustTypeExpressionUP(); - } - } - - std::vector<RustTypeExpressionUP> type_list; - if (CurrentToken().kind == '<') { - if (!BracketTypeList(&type_list, error)) { - return RustTypeExpressionUP(); - } - } - - if (path.empty()) { - error.SetErrorString("identifier expected"); - return RustTypeExpressionUP(); - } - - RustPathUP name_path = llvm::make_unique<RustPath>(saw_self, relative, supers, std::move(path), - std::move(type_list)); - return llvm::make_unique<RustPathTypeExpression>(std::move(name_path)); -} - -RustTypeExpressionUP Parser::Type(Status &error) { - switch (CurrentToken().kind) { - case '[': - return ArrayType(error); - - case '&': - return ReferenceType(error); - - case '*': - return PointerType(error); - - case FN: - return FunctionType(error); - - case '(': - return TupleType(error); - - case SUPER: - case SELF: - case IDENTIFIER: - case COLONCOLON: - return TypePath(error); - - default: - error.SetErrorString("expected type"); - return RustTypeExpressionUP(); - } -}
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustParse.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustParse.h deleted file mode 100644 index e9b6eb4..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustParse.h +++ /dev/null
@@ -1,90 +0,0 @@ -//===-- RustParse.h -------------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_RustParse_h -#define liblldb_RustParse_h - -#include "lldb/lldb-forward.h" -#include "lldb/lldb-private.h" -#include "RustLex.h" -#include "RustAST.h" - -namespace lldb_private { - -namespace rust { - -class Parser { -public: - - Parser(lldb::TargetSP target, llvm::StringRef ref) - : m_target(target), - m_lexer(ref), - // fixme this seems not good - m_current(m_lexer.Next()) - { - } - - RustExpressionUP ParseFully(Status &error) { - RustExpressionUP result = Expr(error); - if (CurrentToken().kind != THATSALLFOLKS) { - error.SetErrorString("extra tokens at EOF"); - return RustExpressionUP(); - } - return result; - } - -private: - - bool StartsTerm(); - template<char C, RustUnaryOperator OP> RustExpressionUP Unary(Status &error); - bool ExprList(std::vector<RustExpressionUP> *exprs, Status &error); - RustExpressionUP Parens(Status &error); - RustExpressionUP Path(Status &error); - RustExpressionUP Array(Status &error); - RustExpressionUP Field(RustExpressionUP &&lhs, Status &error); - RustExpressionUP Call(RustExpressionUP &&func, Status &error); - RustExpressionUP Index(RustExpressionUP &&array, Status &error); - RustExpressionUP Term(Status &error); - RustExpressionUP Binary(Status &error); - RustExpressionUP Sizeof(Status &error); - RustExpressionUP Struct(RustTypeExpressionUP &&path, Status &error); - RustExpressionUP Range(Status &error); - - RustExpressionUP Expr(Status &error) { - return Range(error); - } - - - RustTypeExpressionUP Type(Status &error); - RustTypeExpressionUP ArrayType(Status &error); - RustTypeExpressionUP ReferenceType(Status &error); - RustTypeExpressionUP PointerType(Status &error); - bool TypeList(std::vector<RustTypeExpressionUP> *type_list, Status &error); - bool ParenTypeList(std::vector<RustTypeExpressionUP> *type_list, Status &error); - bool BracketTypeList(std::vector<RustTypeExpressionUP> *type_list, Status &error); - RustTypeExpressionUP FunctionType(Status &error); - RustTypeExpressionUP TupleType(Status &error); - RustTypeExpressionUP TypePath(Status &error); - - Token &CurrentToken() { return m_current; } - void Advance() { m_current = m_lexer.Next(); } - - // There's one case where we need to push-back, but we don't need - // full generality so there's just this little hack. - void ReplaceTokenKind(int k) { m_current.kind = k; } - - lldb::TargetSP m_target; - Lexer m_lexer; - Token m_current; -}; - -} // namespace rust -} // namespace lldb_private - -#endif // liblldb_RustParse_h
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustUserExpression.cpp b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustUserExpression.cpp deleted file mode 100644 index cdea659..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustUserExpression.cpp +++ /dev/null
@@ -1,68 +0,0 @@ -//===-- RustUserExpression.cpp ------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "RustUserExpression.h" -#include "lldb/Core/ValueObject.h" -#include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Expression/ExpressionVariable.h" -#include "lldb/Symbol/RustASTContext.h" -#include "lldb/Target/Target.h" -#include "Plugins/ExpressionParser/Rust/RustParse.h" - -using namespace lldb_private::rust; -using namespace lldb_private; -using namespace lldb; - -bool RustUserExpression::Parse(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx, - lldb_private::ExecutionPolicy execution_policy, - bool keep_result_in_memory, bool generate_debug_info) -{ - InstallContext(exe_ctx); - - Parser parser(exe_ctx.GetTargetSP(), m_expr_text); - Status status; - m_expr = parser.ParseFully(status); - if (!m_expr) { - diagnostic_manager.PutString(eDiagnosticSeverityError, status.AsCString()); - return false; - } - - return true; -} - -lldb::ExpressionResults RustUserExpression::DoExecute(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx, - const EvaluateExpressionOptions &options, - lldb::UserExpressionSP &shared_ptr_to_me, - lldb::ExpressionVariableSP &result) -{ - Status error; - ValueObjectSP value = m_expr->Evaluate(exe_ctx, error); - m_expr.reset(); - - if (!value) { - diagnostic_manager.PutString(eDiagnosticSeverityError, error.AsCString()); - return lldb::eExpressionDiscarded; - } - - result.reset(new ExpressionVariable(ExpressionVariable::eKindRust)); - result->m_live_sp = result->m_frozen_sp = value; - result->m_flags |= ExpressionVariable::EVIsProgramReference; - Target *target = exe_ctx.GetTargetPtr(); - PersistentExpressionState *pv = - target->GetPersistentExpressionStateForLanguage(eLanguageTypeRust); - if (pv != nullptr) { - result->SetName(pv->GetNextPersistentVariableName(*target, - pv->GetPersistentVariablePrefix())); - pv->AddVariable(result); - } - - return lldb::eExpressionCompleted; -}
diff --git a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustUserExpression.h b/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustUserExpression.h deleted file mode 100644 index 13cc8ad..0000000 --- a/src/llvm-project/lldb/source/Plugins/ExpressionParser/Rust/RustUserExpression.h +++ /dev/null
@@ -1,63 +0,0 @@ -//===-- RustUserExpression.h -------------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_RustUserExpression_h -#define liblldb_RustUserExpression_h - -#include <memory> -#include "lldb/Expression/UserExpression.h" -#include "Plugins/ExpressionParser/Rust/RustAST.h" - -namespace lldb_private { - -class RustUserExpression : public UserExpression { -public: - - RustUserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, - llvm::StringRef prefix, lldb::LanguageType language, - ResultType desired_type, - const EvaluateExpressionOptions &options) - : UserExpression(exe_scope, expr, prefix, language, desired_type, options) - { - } - - bool Parse(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx, - lldb_private::ExecutionPolicy execution_policy, - bool keep_result_in_memory, bool generate_debug_info) override; - - bool CanInterpret() override { - return true; - } - - // FIXME - what is this supposed to do. - bool FinalizeJITExecution(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx, - lldb::ExpressionVariableSP &result, - lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS, - lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS) override { - return true; - } - -protected: - - lldb::ExpressionResults DoExecute(DiagnosticManager &diagnostic_manager, - ExecutionContext &exe_ctx, - const EvaluateExpressionOptions &options, - lldb::UserExpressionSP &shared_ptr_to_me, - lldb::ExpressionVariableSP &result) override; - -private: - - RustExpressionUP m_expr; -}; - -} // namespace lldb_private - -#endif // liblldb_RustUserExpression_h
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.cpp b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.cpp index 85bc4a6..6323889 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.cpp +++ b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.cpp
@@ -1,9 +1,8 @@ //===-- EmulateInstructionARM.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -37,11 +36,9 @@ #define AlignPC(pc_val) (pc_val & 0xFFFFFFFC) -//---------------------------------------------------------------------- // // ITSession implementation // -//---------------------------------------------------------------------- static bool GetARMDWARFRegisterInfo(unsigned reg_num, RegisterInfo ®_info) { ::memset(®_info, 0, sizeof(RegisterInfo)); @@ -710,11 +707,9 @@ #define VFPv2_ABOVE (VFPv2 | VFPv3 | AdvancedSIMD) #define VFPv2v3 (VFPv2 | VFPv3) -//---------------------------------------------------------------------- // // EmulateInstructionARM implementation // -//---------------------------------------------------------------------- void EmulateInstructionARM::Initialize() { PluginManager::RegisterPlugin(GetPluginNameStatic(), @@ -740,21 +735,21 @@ if (EmulateInstructionARM::SupportsEmulatingInstructionsOfTypeStatic( inst_type)) { if (arch.GetTriple().getArch() == llvm::Triple::arm) { - std::unique_ptr<EmulateInstructionARM> emulate_insn_ap( + std::unique_ptr<EmulateInstructionARM> emulate_insn_up( new EmulateInstructionARM(arch)); - if (emulate_insn_ap.get()) - return emulate_insn_ap.release(); + if (emulate_insn_up) + return emulate_insn_up.release(); } else if (arch.GetTriple().getArch() == llvm::Triple::thumb) { - std::unique_ptr<EmulateInstructionARM> emulate_insn_ap( + std::unique_ptr<EmulateInstructionARM> emulate_insn_up( new EmulateInstructionARM(arch)); - if (emulate_insn_ap.get()) - return emulate_insn_ap.release(); + if (emulate_insn_up) + return emulate_insn_up.release(); } } - return NULL; + return nullptr; } bool EmulateInstructionARM::SetTargetTriple(const ArchSpec &arch) { @@ -10155,7 +10150,7 @@ shift_t = DecodeRegShift(Bits32(opcode, 6, 5)); // if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE; - if ((d == 15) || (m == 15) || (m == 15) || (s == 15)) + if ((d == 15) || (n == 15) || (m == 15) || (s == 15)) return false; break; @@ -12853,9 +12848,7 @@ EmulateInstructionARM::GetARMOpcodeForInstruction(const uint32_t opcode, uint32_t arm_isa) { static ARMOpcode g_arm_opcodes[] = { - //---------------------------------------------------------------------- // Prologue instructions - //---------------------------------------------------------------------- // push register(s) {0x0fff0000, 0x092d0000, ARMvAll, eEncodingA1, No_VFP, eSize32, @@ -12894,9 +12887,7 @@ {0x0fbf0f00, 0x0d2d0a00, ARMV6T2_ABOVE, eEncodingA2, No_VFP, eSize32, &EmulateInstructionARM::EmulateVPUSH, "vpush.32 <list>"}, - //---------------------------------------------------------------------- // Epilogue instructions - //---------------------------------------------------------------------- {0x0fff0000, 0x08bd0000, ARMvAll, eEncodingA1, No_VFP, eSize32, &EmulateInstructionARM::EmulatePOP, "pop <registers>"}, @@ -12907,15 +12898,11 @@ {0x0fbf0f00, 0x0cbd0a00, ARMV6T2_ABOVE, eEncodingA2, No_VFP, eSize32, &EmulateInstructionARM::EmulateVPOP, "vpop.32 <list>"}, - //---------------------------------------------------------------------- // Supervisor Call (previously Software Interrupt) - //---------------------------------------------------------------------- {0x0f000000, 0x0f000000, ARMvAll, eEncodingA1, No_VFP, eSize32, &EmulateInstructionARM::EmulateSVC, "svc #imm24"}, - //---------------------------------------------------------------------- // Branch instructions - //---------------------------------------------------------------------- // To resolve ambiguity, "blx <label>" should come before "b #imm24" and // "bl <label>". {0xfe000000, 0xfa000000, ARMV5_ABOVE, eEncodingA2, No_VFP, eSize32, @@ -12933,9 +12920,7 @@ {0x0ffffff0, 0x012fff20, ARMvAll, eEncodingA1, No_VFP, eSize32, &EmulateInstructionARM::EmulateBXJRm, "bxj <Rm>"}, - //---------------------------------------------------------------------- // Data-processing instructions - //---------------------------------------------------------------------- // adc (immediate) {0x0fe00000, 0x02a00000, ARMvAll, eEncodingA1, No_VFP, eSize32, &EmulateInstructionARM::EmulateADCImm, "adc{s}<c> <Rd>, <Rn>, #const"}, @@ -13099,9 +13084,7 @@ &EmulateInstructionARM::EmulateSUBSPcLrEtc, "<opc>S<c> PC,<Rn>,<Rm{,<shift>}"}, - //---------------------------------------------------------------------- // Load instructions - //---------------------------------------------------------------------- {0x0fd00000, 0x08900000, ARMvAll, eEncodingA1, No_VFP, eSize32, &EmulateInstructionARM::EmulateLDM, "ldm<c> <Rn>{!} <registers>"}, {0x0fd00000, 0x08100000, ARMvAll, eEncodingA1, No_VFP, eSize32, @@ -13166,9 +13149,7 @@ &EmulateInstructionARM::EmulateVLD1SingleAll, "vld1<c>.<size> <list>, [<Rn>{@<align>}], <Rm>"}, - //---------------------------------------------------------------------- // Store instructions - //---------------------------------------------------------------------- {0x0fd00000, 0x08800000, ARMvAll, eEncodingA1, No_VFP, eSize32, &EmulateInstructionARM::EmulateSTM, "stm<c> <Rn>{!} <registers>"}, {0x0fd00000, 0x08000000, ARMvAll, eEncodingA1, No_VFP, eSize32, @@ -13212,9 +13193,7 @@ &EmulateInstructionARM::EmulateVST1Single, "vst1<c>.<size> <list>, [<Rn>{@<align>}], <Rm>"}, - //---------------------------------------------------------------------- // Other instructions - //---------------------------------------------------------------------- {0x0fff00f0, 0x06af00f0, ARMV6_ABOVE, eEncodingA1, No_VFP, eSize32, &EmulateInstructionARM::EmulateSXTB, "sxtb<c> <Rd>,<Rm>{,<rotation>}"}, {0x0fff00f0, 0x06bf0070, ARMV6_ABOVE, eEncodingA1, No_VFP, eSize32, @@ -13234,7 +13213,7 @@ (g_arm_opcodes[i].variants & arm_isa) != 0) return &g_arm_opcodes[i]; } - return NULL; + return nullptr; } EmulateInstructionARM::ARMOpcode * @@ -13242,9 +13221,7 @@ uint32_t arm_isa) { static ARMOpcode g_thumb_opcodes[] = { - //---------------------------------------------------------------------- // Prologue instructions - //---------------------------------------------------------------------- // push register(s) {0xfffffe00, 0x0000b400, ARMvAll, eEncodingT1, No_VFP, eSize16, @@ -13288,9 +13265,7 @@ {0xffbf0f00, 0xed2d0a00, ARMV6T2_ABOVE, eEncodingT2, No_VFP, eSize32, &EmulateInstructionARM::EmulateVPUSH, "vpush.32 <list>"}, - //---------------------------------------------------------------------- // Epilogue instructions - //---------------------------------------------------------------------- {0xfffff800, 0x0000a800, ARMV4T_ABOVE, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateADDSPImm, "add<c> <Rd>, sp, #imm"}, @@ -13307,15 +13282,11 @@ {0xffbf0f00, 0xecbd0a00, ARMV6T2_ABOVE, eEncodingT2, No_VFP, eSize32, &EmulateInstructionARM::EmulateVPOP, "vpop.32 <list>"}, - //---------------------------------------------------------------------- // Supervisor Call (previously Software Interrupt) - //---------------------------------------------------------------------- {0xffffff00, 0x0000df00, ARMvAll, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateSVC, "svc #imm8"}, - //---------------------------------------------------------------------- // If Then makes up to four following instructions conditional. - //---------------------------------------------------------------------- // The next 5 opcode _must_ come before the if then instruction {0xffffffff, 0x0000bf00, ARMV6T2_ABOVE, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateNop, "nop"}, @@ -13330,9 +13301,7 @@ {0xffffff00, 0x0000bf00, ARMV6T2_ABOVE, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateIT, "it{<x>{<y>{<z>}}} <firstcond>"}, - //---------------------------------------------------------------------- // Branch instructions - //---------------------------------------------------------------------- // To resolve ambiguity, "b<c> #imm8" should come after "svc #imm8". {0xfffff000, 0x0000d000, ARMvAll, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateB, "b<c> #imm8 (outside IT)"}, @@ -13367,9 +13336,7 @@ {0xfff0fff0, 0xe8d0f010, ARMV6T2_ABOVE, eEncodingT1, No_VFP, eSize32, &EmulateInstructionARM::EmulateTB, "tbh<c> <Rn>, <Rm>, lsl #1"}, - //---------------------------------------------------------------------- // Data-processing instructions - //---------------------------------------------------------------------- // adc (immediate) {0xfbe08000, 0xf1400000, ARMV6T2_ABOVE, eEncodingT1, No_VFP, eSize32, &EmulateInstructionARM::EmulateADCImm, "adc{s}<c> <Rd>, <Rn>, #<const>"}, @@ -13597,20 +13564,16 @@ {0xffffff00, 0xf3de8f00, ARMV6T2_ABOVE, eEncodingT1, No_VFP, eSize32, &EmulateInstructionARM::EmulateSUBSPcLrEtc, "SUBS<c> PC, LR, #<imm8>"}, - //---------------------------------------------------------------------- // RFE instructions *** IMPORTANT *** THESE MUST BE LISTED **BEFORE** THE // LDM.. Instructions in this table; // otherwise the wrong instructions will be selected. - //---------------------------------------------------------------------- {0xffd0ffff, 0xe810c000, ARMV6T2_ABOVE, eEncodingT1, No_VFP, eSize32, &EmulateInstructionARM::EmulateRFE, "rfedb<c> <Rn>{!}"}, {0xffd0ffff, 0xe990c000, ARMV6T2_ABOVE, eEncodingT2, No_VFP, eSize32, &EmulateInstructionARM::EmulateRFE, "rfe{ia}<c> <Rn>{!}"}, - //---------------------------------------------------------------------- // Load instructions - //---------------------------------------------------------------------- {0xfffff800, 0x0000c800, ARMV4T_ABOVE, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateLDM, "ldm<c> <Rn>{!} <registers>"}, {0xffd02000, 0xe8900000, ARMV6T2_ABOVE, eEncodingT2, No_VFP, eSize32, @@ -13718,9 +13681,7 @@ &EmulateInstructionARM::EmulateVLD1SingleAll, "vld1<c>.<size> <list>, [<Rn>{@<align>}], <Rm>"}, - //---------------------------------------------------------------------- // Store instructions - //---------------------------------------------------------------------- {0xfffff800, 0x0000c000, ARMV4T_ABOVE, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateSTM, "stm<c> <Rn>{!} <registers>"}, {0xffd00000, 0xe8800000, ARMV6T2_ABOVE, eEncodingT2, No_VFP, eSize32, @@ -13777,9 +13738,7 @@ &EmulateInstructionARM::EmulateVST1Single, "vst1<c>.<size> <list>, [<Rn>{@<align>}], <Rm>"}, - //---------------------------------------------------------------------- // Other instructions - //---------------------------------------------------------------------- {0xffffffc0, 0x0000b240, ARMV6_ABOVE, eEncodingT1, No_VFP, eSize16, &EmulateInstructionARM::EmulateSXTB, "sxtb<c> <Rd>,<Rm>"}, {0xfffff080, 0xfa4ff080, ARMV6_ABOVE, eEncodingT2, No_VFP, eSize32, @@ -13804,7 +13763,7 @@ (g_thumb_opcodes[i].variants & arm_isa) != 0) return &g_thumb_opcodes[i]; } - return NULL; + return nullptr; } bool EmulateInstructionARM::SetArchitecture(const ArchSpec &arch) { @@ -14352,7 +14311,7 @@ } bool EmulateInstructionARM::EvaluateInstruction(uint32_t evaluate_options) { - ARMOpcode *opcode_data = NULL; + ARMOpcode *opcode_data = nullptr; if (m_opcode_mode == eModeThumb) opcode_data = @@ -14441,7 +14400,7 @@ OptionValueSP value_sp = test_data->GetValueForKey(opcode_key); uint32_t test_opcode; - if ((value_sp.get() == NULL) || + if ((value_sp.get() == nullptr) || (value_sp->GetType() != OptionValue::eTypeUInt64)) { out_stream->Printf("TestEmulation: Error reading opcode from test file.\n"); return false; @@ -14467,7 +14426,7 @@ EmulationStateARM after_state; value_sp = test_data->GetValueForKey(before_key); - if ((value_sp.get() == NULL) || + if ((value_sp.get() == nullptr) || (value_sp->GetType() != OptionValue::eTypeDictionary)) { out_stream->Printf("TestEmulation: Failed to find 'before' state.\n"); return false; @@ -14480,7 +14439,7 @@ } value_sp = test_data->GetValueForKey(after_key); - if ((value_sp.get() == NULL) || + if ((value_sp.get() == nullptr) || (value_sp->GetType() != OptionValue::eTypeDictionary)) { out_stream->Printf("TestEmulation: Failed to find 'after' state.\n"); return false;
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h index fb1867c..13d7fc0 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h +++ b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h
@@ -1,9 +1,8 @@ -//===-- lldb_EmulateInstructionARM.h ----------------------------*- C++ -*-===// +//===-- EmulateInstructionARM.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -46,7 +45,7 @@ class EmulateInstructionARM : public EmulateInstruction { public: - typedef enum { + enum ARMEncoding { eEncodingA1, eEncodingA2, eEncodingA3, @@ -57,7 +56,7 @@ eEncodingT3, eEncodingT4, eEncodingT5 - } ARMEncoding; + }; static void Initialize(); @@ -292,7 +291,7 @@ protected: // Typedef for the callback function used during the emulation. // Pass along (ARMEncoding)encoding as the callback data. - typedef enum { eSize16, eSize32 } ARMInstrSize; + enum ARMInstrSize { eSize16, eSize32 }; typedef struct { uint32_t mask;
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.cpp b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.cpp index d770b3b..11c7677 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.cpp +++ b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.cpp
@@ -1,9 +1,8 @@ //===-- EmulationStateARM.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -285,14 +284,14 @@ // Load memory, if present. - if (value_sp.get() != NULL) { + if (value_sp.get() != nullptr) { static ConstString address_key("address"); static ConstString data_key("data"); uint64_t start_address = 0; OptionValueDictionary *mem_dict = value_sp->GetAsDictionary(); value_sp = mem_dict->GetValueForKey(address_key); - if (value_sp.get() == NULL) + if (value_sp.get() == nullptr) return false; else start_address = value_sp->GetUInt64Value(); @@ -307,7 +306,7 @@ for (uint32_t i = 0; i < num_elts; ++i) { value_sp = mem_array->GetValueAtIndex(i); - if (value_sp.get() == NULL) + if (value_sp.get() == nullptr) return false; uint64_t value = value_sp->GetUInt64Value(); StoreToPseudoAddress(address, value); @@ -316,7 +315,7 @@ } value_sp = test_data->GetValueForKey(registers_key); - if (value_sp.get() == NULL) + if (value_sp.get() == nullptr) return false; // Load General Registers @@ -329,7 +328,7 @@ sstr.Printf("r%d", i); ConstString reg_name(sstr.GetString()); value_sp = reg_dict->GetValueForKey(reg_name); - if (value_sp.get() == NULL) + if (value_sp.get() == nullptr) return false; uint64_t reg_value = value_sp->GetUInt64Value(); StorePseudoRegisterValue(dwarf_r0 + i, reg_value); @@ -337,7 +336,7 @@ static ConstString cpsr_name("cpsr"); value_sp = reg_dict->GetValueForKey(cpsr_name); - if (value_sp.get() == NULL) + if (value_sp.get() == nullptr) return false; StorePseudoRegisterValue(dwarf_cpsr, value_sp->GetUInt64Value()); @@ -347,7 +346,7 @@ sstr.Printf("s%d", i); ConstString reg_name(sstr.GetString()); value_sp = reg_dict->GetValueForKey(reg_name); - if (value_sp.get() == NULL) + if (value_sp.get() == nullptr) return false; uint64_t reg_value = value_sp->GetUInt64Value(); StorePseudoRegisterValue(dwarf_s0 + i, reg_value);
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.h b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.h index f27f475..e5af37a 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.h +++ b/src/llvm-project/lldb/source/Plugins/Instruction/ARM/EmulationStateARM.h
@@ -1,9 +1,8 @@ -//===-- lldb_EmulationStateARM.h --------------------------------*- C++ -*-===// +//===-- EmulationStateARM.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp b/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp index 661a651..d7e8e04 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp
@@ -1,9 +1,8 @@ //===-- EmulateInstructionARM64.cpp ------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -118,11 +117,9 @@ return result; } -//---------------------------------------------------------------------- // // EmulateInstructionARM implementation // -//---------------------------------------------------------------------- void EmulateInstructionARM64::Initialize() { PluginManager::RegisterPlugin(GetPluginNameStatic(), @@ -157,7 +154,7 @@ } } - return NULL; + return nullptr; } bool EmulateInstructionARM64::SetTargetTriple(const ArchSpec &arch) { @@ -208,9 +205,7 @@ EmulateInstructionARM64::Opcode * EmulateInstructionARM64::GetOpcodeForInstruction(const uint32_t opcode) { static EmulateInstructionARM64::Opcode g_opcodes[] = { - //---------------------------------------------------------------------- // Prologue instructions - //---------------------------------------------------------------------- // push register(s) {0xff000000, 0xd1000000, No_VFP, @@ -416,7 +411,7 @@ bool EmulateInstructionARM64::EvaluateInstruction(uint32_t evaluate_options) { const uint32_t opcode = m_opcode.GetOpcode32(); Opcode *opcode_data = GetOpcodeForInstruction(opcode); - if (opcode_data == NULL) + if (opcode_data == nullptr) return false; // printf ("opcode template for 0x%8.8x: %s\n", opcode, opcode_data->name); @@ -662,10 +657,10 @@ if (sub_op) { operand2 = NOT(operand2); - carry_in = 1; + carry_in = true; imm = -imm; // For the Register plug offset context below } else { - carry_in = 0; + carry_in = false; } ProcState proc_state;
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h b/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h index 1d1bd74..03a57a2 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h +++ b/src/llvm-project/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h
@@ -1,9 +1,8 @@ //===-- EmulateInstructionARM64.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -74,25 +73,25 @@ bool CreateFunctionEntryUnwind(lldb_private::UnwindPlan &unwind_plan) override; - typedef enum { AddrMode_OFF, AddrMode_PRE, AddrMode_POST } AddrMode; + enum AddrMode { AddrMode_OFF, AddrMode_PRE, AddrMode_POST }; - typedef enum { + enum BranchType { BranchType_CALL, BranchType_ERET, BranchType_DRET, BranchType_RET, BranchType_JMP - } BranchType; + }; - typedef enum { CountOp_CLZ, CountOp_CLS, CountOp_CNT } CountOp; + enum CountOp { CountOp_CLZ, CountOp_CLS, CountOp_CNT }; - typedef enum { RevOp_RBIT, RevOp_REV16, RevOp_REV32, RevOp_REV64 } RevOp; + enum RevOp { RevOp_RBIT, RevOp_REV16, RevOp_REV32, RevOp_REV64 }; - typedef enum { BitwiseOp_NOT, BitwiseOp_RBIT } BitwiseOp; + enum BitwiseOp { BitwiseOp_NOT, BitwiseOp_RBIT }; - typedef enum { EL0 = 0, EL1 = 1, EL2 = 2, EL3 = 3 } ExceptionLevel; + enum ExceptionLevel { EL0 = 0, EL1 = 1, EL2 = 2, EL3 = 3 }; - typedef enum { + enum ExtendType { ExtendType_SXTB, ExtendType_SXTH, ExtendType_SXTW, @@ -101,44 +100,36 @@ ExtendType_UXTH, ExtendType_UXTW, ExtendType_UXTX - } ExtendType; + }; - typedef enum { ExtractType_LEFT, ExtractType_RIGHT } ExtractType; + enum ExtractType { ExtractType_LEFT, ExtractType_RIGHT }; - typedef enum { LogicalOp_AND, LogicalOp_EOR, LogicalOp_ORR } LogicalOp; + enum LogicalOp { LogicalOp_AND, LogicalOp_EOR, LogicalOp_ORR }; - typedef enum { MemOp_LOAD, MemOp_STORE, MemOp_PREFETCH, MemOp_NOP } MemOp; + enum MemOp { MemOp_LOAD, MemOp_STORE, MemOp_PREFETCH, MemOp_NOP }; - typedef enum { MoveWideOp_N, MoveWideOp_Z, MoveWideOp_K } MoveWideOp; + enum MoveWideOp { MoveWideOp_N, MoveWideOp_Z, MoveWideOp_K }; - typedef enum { - ShiftType_LSL, - ShiftType_LSR, - ShiftType_ASR, - ShiftType_ROR - } ShiftType; + enum ShiftType { ShiftType_LSL, ShiftType_LSR, ShiftType_ASR, ShiftType_ROR }; - typedef enum { SP0 = 0, SPx = 1 } StackPointerSelection; + enum StackPointerSelection { SP0 = 0, SPx = 1 }; - typedef enum { - Unpredictable_WBOVERLAP, - Unpredictable_LDPOVERLAP - } Unpredictable; + enum Unpredictable { Unpredictable_WBOVERLAP, Unpredictable_LDPOVERLAP }; - typedef enum { + enum ConstraintType { Constraint_NONE, Constraint_UNKNOWN, Constraint_SUPPRESSWB, Constraint_NOP - } ConstraintType; + }; - typedef enum { + enum AccType { AccType_NORMAL, AccType_UNPRIV, AccType_STREAM, AccType_ALIGNED, AccType_ORDERED - } AccType; + }; typedef struct { uint32_t N : 1, V : 1, C : 1,
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/CMakeLists.txt index b2fe0ee..d25735d 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/CMakeLists.txt
@@ -7,7 +7,6 @@ LINK_LIBS lldbCore - lldbInterpreter lldbSymbol lldbTarget lldbPluginProcessUtility
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp index 7fccb23..cbf3dda 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp +++ b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp
@@ -1,9 +1,8 @@ //===-- EmulateInstructionMIPS.cpp -------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -43,11 +42,9 @@ #define UInt(x) ((uint64_t)x) #define integer int64_t -//---------------------------------------------------------------------- // // EmulateInstructionMIPS implementation // -//---------------------------------------------------------------------- #ifdef __mips__ extern "C" { @@ -216,7 +213,7 @@ } } - return NULL; + return nullptr; } bool EmulateInstructionMIPS::SetTargetTriple(const ArchSpec &arch) { @@ -678,9 +675,7 @@ EmulateInstructionMIPS::MipsOpcode * EmulateInstructionMIPS::GetOpcodeForInstruction(const char *op_name) { static EmulateInstructionMIPS::MipsOpcode g_opcodes[] = { - //---------------------------------------------------------------------- // Prologue/Epilogue instructions - //---------------------------------------------------------------------- {"ADDiu", &EmulateInstructionMIPS::Emulate_ADDiu, "ADDIU rt, rs, immediate"}, {"SW", &EmulateInstructionMIPS::Emulate_SW, "SW rt, offset(rs)"}, @@ -689,9 +684,7 @@ {"ADDU", &EmulateInstructionMIPS::Emulate_SUBU_ADDU, "ADDU rd, rs, rt"}, {"LUI", &EmulateInstructionMIPS::Emulate_LUI, "LUI rt, immediate"}, - //---------------------------------------------------------------------- // MicroMIPS Prologue/Epilogue instructions - //---------------------------------------------------------------------- {"ADDIUSP_MM", &EmulateInstructionMIPS::Emulate_ADDIUSP, "ADDIU immediate"}, {"ADDIUS5_MM", &EmulateInstructionMIPS::Emulate_ADDIUS5, @@ -712,10 +705,8 @@ "LWP rd,offset(base)"}, {"JRADDIUSP", &EmulateInstructionMIPS::Emulate_JRADDIUSP, "JRADDIUSP immediate"}, - //---------------------------------------------------------------------- // Load/Store instructions - //---------------------------------------------------------------------- /* Following list of emulated instructions are required by implementation of hardware watchpoint for MIPS in lldb. As we just need the address accessed by instructions, @@ -835,9 +826,7 @@ {"SCDX", &EmulateInstructionMIPS::Emulate_LDST_Imm, "SCDX rt, offset(base)"}, - //---------------------------------------------------------------------- // MicroMIPS Load/Store instructions - //---------------------------------------------------------------------- {"LBU16_MM", &EmulateInstructionMIPS::Emulate_LDST_Imm, "LBU16 rt, decoded_offset(base)"}, {"LHU16_MM", &EmulateInstructionMIPS::Emulate_LDST_Imm, @@ -855,9 +844,7 @@ {"SB16_MM", &EmulateInstructionMIPS::Emulate_LDST_Imm, "SB16 rt, offset(base)"}, - //---------------------------------------------------------------------- // Branch instructions - //---------------------------------------------------------------------- {"BEQ", &EmulateInstructionMIPS::Emulate_BXX_3ops, "BEQ rs,rt,offset"}, {"BNE", &EmulateInstructionMIPS::Emulate_BXX_3ops, "BNE rs,rt,offset"}, {"BEQL", &EmulateInstructionMIPS::Emulate_BXX_3ops, "BEQL rs,rt,offset"}, @@ -949,9 +936,7 @@ {"BNZ_V", &EmulateInstructionMIPS::Emulate_BNZV, "BNZ.V wt,s16"}, {"BZ_V", &EmulateInstructionMIPS::Emulate_BZV, "BZ.V wt,s16"}, - //---------------------------------------------------------------------- // MicroMIPS Branch instructions - //---------------------------------------------------------------------- {"B16_MM", &EmulateInstructionMIPS::Emulate_B16_MM, "B16 offset"}, {"BEQZ16_MM", &EmulateInstructionMIPS::Emulate_Branch_MM, "BEQZ16 rs, offset"}, @@ -981,7 +966,7 @@ return &g_opcodes[i]; } - return NULL; + return nullptr; } uint32_t @@ -1098,7 +1083,7 @@ */ const char *op_name = m_insn_info->getName(mc_insn.getOpcode()).data(); - if (op_name == NULL) + if (op_name == nullptr) return false; /* @@ -1107,7 +1092,7 @@ */ MipsOpcode *opcode_data = GetOpcodeForInstruction(op_name); - if (opcode_data == NULL) + if (opcode_data == nullptr) return false; uint64_t old_pc = 0, new_pc = 0; @@ -2890,7 +2875,7 @@ bool success = false, branch_hit = true; int32_t target = 0; RegisterValue reg_value; - const uint8_t *ptr = NULL; + const uint8_t *ptr = nullptr; uint32_t wt = m_reg_info->getEncodingValue(insn.getOperand(0).getReg()); int32_t offset = insn.getOperand(1).getImm();
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h index 8d6e0be..cd447ae 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h +++ b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h
@@ -1,10 +1,9 @@ //===-- EmulateInstructionMIPS.h ------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,8 +20,11 @@ class MCInst; } +namespace lldb_private { + class OptionValueDictionary; +} + #include "lldb/Core/EmulateInstruction.h" -#include "lldb/Interpreter/OptionValue.h" #include "lldb/Utility/Status.h" class EmulateInstructionMIPS : public lldb_private::EmulateInstruction {
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp index 9d178dd..69f0278 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp
@@ -1,9 +1,8 @@ //===-- EmulateInstructionMIPS64.cpp -----------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -43,11 +42,9 @@ #define UInt(x) ((uint64_t)x) #define integer int64_t -//---------------------------------------------------------------------- // // EmulateInstructionMIPS64 implementation // -//---------------------------------------------------------------------- #ifdef __mips__ extern "C" { @@ -203,7 +200,7 @@ } } - return NULL; + return nullptr; } bool EmulateInstructionMIPS64::SetTargetTriple(const ArchSpec &arch) { @@ -665,9 +662,7 @@ EmulateInstructionMIPS64::MipsOpcode * EmulateInstructionMIPS64::GetOpcodeForInstruction(const char *op_name) { static EmulateInstructionMIPS64::MipsOpcode g_opcodes[] = { - //---------------------------------------------------------------------- // Prologue/Epilogue instructions - //---------------------------------------------------------------------- {"DADDiu", &EmulateInstructionMIPS64::Emulate_DADDiu, "DADDIU rt, rs, immediate"}, {"ADDiu", &EmulateInstructionMIPS64::Emulate_DADDiu, @@ -684,9 +679,7 @@ "ADDU rd, rs, rt"}, {"LUI", &EmulateInstructionMIPS64::Emulate_LUI, "LUI rt, immediate"}, - //---------------------------------------------------------------------- // Load/Store instructions - //---------------------------------------------------------------------- /* Following list of emulated instructions are required by implementation of hardware watchpoint for MIPS in lldb. As we just need the address accessed by instructions, @@ -792,9 +785,7 @@ {"SWXC1", &EmulateInstructionMIPS64::Emulate_LDST_Reg, "SWXC1 fs, index (base)"}, - //---------------------------------------------------------------------- // Branch instructions - //---------------------------------------------------------------------- {"BEQ", &EmulateInstructionMIPS64::Emulate_BXX_3ops, "BEQ rs,rt,offset"}, {"BEQ64", &EmulateInstructionMIPS64::Emulate_BXX_3ops, "BEQ rs,rt,offset"}, {"BNE", &EmulateInstructionMIPS64::Emulate_BXX_3ops, "BNE rs,rt,offset"}, @@ -940,7 +931,7 @@ return &g_opcodes[i]; } - return NULL; + return nullptr; } bool EmulateInstructionMIPS64::ReadInstruction() { @@ -983,7 +974,7 @@ */ const char *op_name = m_insn_info->getName(mc_insn.getOpcode()).data(); - if (op_name == NULL) + if (op_name == nullptr) return false; /* @@ -992,7 +983,7 @@ */ MipsOpcode *opcode_data = GetOpcodeForInstruction(op_name); - if (opcode_data == NULL) + if (opcode_data == nullptr) return false; uint64_t old_pc = 0, new_pc = 0; @@ -2195,7 +2186,7 @@ bool success = false, branch_hit = true; int64_t target = 0; RegisterValue reg_value; - const uint8_t *ptr = NULL; + const uint8_t *ptr = nullptr; uint32_t wt = m_reg_info->getEncodingValue(insn.getOperand(0).getReg()); int64_t offset = insn.getOperand(1).getImm();
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h index e978363..953a093 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h +++ b/src/llvm-project/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h
@@ -1,9 +1,8 @@ //===-- EmulateInstructionMIPS64.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.cpp b/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.cpp index f3a9ca5..c77fa04 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.cpp
@@ -1,9 +1,8 @@ //===-- EmulateInstructionPPC64.cpp ------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -56,23 +55,15 @@ EmulateInstructionPPC64::CreateInstance(const ArchSpec &arch, InstructionType inst_type) { if (EmulateInstructionPPC64::SupportsEmulatingInstructionsOfTypeStatic( - inst_type)) { - if (arch.GetTriple().getArch() == llvm::Triple::ppc64 || - arch.GetTriple().getArch() == llvm::Triple::ppc64le) { + inst_type)) + if (arch.GetTriple().isPPC64()) return new EmulateInstructionPPC64(arch); - } - } return nullptr; } bool EmulateInstructionPPC64::SetTargetTriple(const ArchSpec &arch) { - if (arch.GetTriple().getArch() == llvm::Triple::ppc64) - return true; - else if (arch.GetTriple().getArch() == llvm::Triple::ppc64le) - return true; - - return false; + return arch.GetTriple().isPPC64(); } static bool LLDBTableGetRegisterInfo(uint32_t reg_num, RegisterInfo ®_info) {
diff --git a/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.h b/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.h index e9a1da6..bf23977 100644 --- a/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.h +++ b/src/llvm-project/lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.h
@@ -1,9 +1,8 @@ //===-- EmulateInstructionPPC64.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.cpp b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.cpp index 9a6e39b..c8ac046 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.cpp
@@ -1,9 +1,8 @@ //===-- ASanRuntime.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -72,7 +71,6 @@ return symbol != nullptr; } -static constexpr std::chrono::seconds g_retrieve_report_data_function_timeout(2); const char *address_sanitizer_retrieve_report_data_prefix = R"( extern "C" { @@ -127,7 +125,7 @@ options.SetTryAllThreads(true); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); - options.SetTimeout(g_retrieve_report_data_function_timeout); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetPrefix(address_sanitizer_retrieve_report_data_prefix); options.SetAutoApplyFixIts(false); options.SetLanguage(eLanguageTypeObjC_plus_plus); @@ -289,7 +287,7 @@ const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType( symbol_name, eSymbolTypeCode); - if (symbol == NULL) + if (symbol == nullptr) return; if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h index 1439f86..0771e62 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h
@@ -1,9 +1,8 @@ -//===-- AddressSanitizerRuntime.h -------------------------------*- C++ -*-===// +//===-- ASanRuntime.h -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.cpp b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.cpp index 32da327..dfe6131 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.cpp
@@ -1,9 +1,8 @@ //===-- MainThreadCheckerRuntime.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,6 +24,8 @@ #include "lldb/Utility/RegularExpression.h" #include "Plugins/Process/Utility/HistoryThread.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -239,7 +240,7 @@ MainThreadCheckerRuntime::GetBacktracesFromExtendedStopInfo( StructuredData::ObjectSP info) { ThreadCollectionSP threads; - threads.reset(new ThreadCollection()); + threads = std::make_shared<ThreadCollection>(); ProcessSP process_sp = GetProcessSP(); @@ -260,11 +261,8 @@ StructuredData::ObjectSP thread_id_obj = info->GetObjectForDotSeparatedPath("tid"); tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0; - - uint32_t stop_id = 0; - bool stop_id_is_valid = false; - HistoryThread *history_thread = - new HistoryThread(*process_sp, tid, PCs, stop_id, stop_id_is_valid); + + HistoryThread *history_thread = new HistoryThread(*process_sp, tid, PCs); ThreadSP new_thread_sp(history_thread); // Save this in the Process' ExtendedThreadList so a strong pointer retains
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h index 516d9fe..1dcbc0f 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h
@@ -1,9 +1,8 @@ //===-- MainThreadCheckerRuntime.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.cpp b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.cpp index 6ce50f5..89f2139 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.cpp
@@ -1,9 +1,8 @@ //===-- TSanRuntime.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,6 +30,8 @@ #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Stream.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -59,8 +60,6 @@ ThreadSanitizerRuntime::~ThreadSanitizerRuntime() { Deactivate(); } -static constexpr std::chrono::seconds g_retrieve_data_function_timeout(2); - const char *thread_sanitizer_retrieve_report_data_prefix = R"( extern "C" { @@ -317,7 +316,7 @@ options.SetTryAllThreads(true); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); - options.SetTimeout(g_retrieve_data_function_timeout); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetPrefix(thread_sanitizer_retrieve_report_data_prefix); options.SetAutoApplyFixIts(false); options.SetLanguage(eLanguageTypeObjC_plus_plus); @@ -901,7 +900,7 @@ const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType( symbol_name, eSymbolTypeCode); - if (symbol == NULL) + if (symbol == nullptr) return; if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid()) @@ -1031,10 +1030,8 @@ o->GetObjectForDotSeparatedPath("thread_os_id"); tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0; - uint32_t stop_id = 0; - bool stop_id_is_valid = false; HistoryThread *history_thread = - new HistoryThread(*process_sp, tid, pcs, stop_id, stop_id_is_valid); + new HistoryThread(*process_sp, tid, pcs); ThreadSP new_thread_sp(history_thread); new_thread_sp->SetName(GenerateThreadName(path, o, info).c_str()); @@ -1051,7 +1048,7 @@ ThreadSanitizerRuntime::GetBacktracesFromExtendedStopInfo( StructuredData::ObjectSP info) { ThreadCollectionSP threads; - threads.reset(new ThreadCollection()); + threads = std::make_shared<ThreadCollection>(); if (info->GetObjectForDotSeparatedPath("instrumentation_class") ->GetStringValue() != "ThreadSanitizer")
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h index e6482d3..db8bb1d 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h
@@ -1,9 +1,8 @@ -//===-- ThreadSanitizerRuntime.h --------------------------------*- C++ -*-===// +//===-- TSanRuntime.h -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.cpp b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.cpp index 1e9280c..367098b 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.cpp
@@ -1,9 +1,8 @@ //===-- UBSanRuntime.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,6 +31,8 @@ #include "lldb/Utility/Stream.h" #include <ctype.h> +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -130,7 +131,7 @@ options.SetTryAllThreads(true); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); - options.SetTimeout(std::chrono::seconds(2)); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetPrefix(ub_sanitizer_retrieve_report_data_prefix); options.SetAutoApplyFixIts(false); options.SetLanguage(eLanguageTypeObjC_plus_plus); @@ -304,7 +305,7 @@ UndefinedBehaviorSanitizerRuntime::GetBacktracesFromExtendedStopInfo( StructuredData::ObjectSP info) { ThreadCollectionSP threads; - threads.reset(new ThreadCollection()); + threads = std::make_shared<ThreadCollection>(); ProcessSP process_sp = GetProcessSP(); @@ -326,10 +327,7 @@ info->GetObjectForDotSeparatedPath("tid"); tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0; - uint32_t stop_id = 0; - bool stop_id_is_valid = false; - HistoryThread *history_thread = - new HistoryThread(*process_sp, tid, PCs, stop_id, stop_id_is_valid); + HistoryThread *history_thread = new HistoryThread(*process_sp, tid, PCs); ThreadSP new_thread_sp(history_thread); std::string stop_reason_description = GetStopReasonDescription(info); new_thread_sp->SetName(stop_reason_description.c_str());
diff --git a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h index 8f138fc..1d854b7 100644 --- a/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h +++ b/src/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h
@@ -1,9 +1,8 @@ -//===-- UndefinedBehaviorSanitizerRuntime.h ---------------------*- C++ -*-===// +//===-- UBSanRuntime.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp b/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp index 3040b8b..140d09e 100644 --- a/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp +++ b/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp
@@ -1,9 +1,8 @@ //===-- JITLoaderGDB.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,17 +29,13 @@ #include "JITLoaderGDB.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ // Debug Interface Structures -//------------------------------------------------------------------ -typedef enum { - JIT_NOACTION = 0, - JIT_REGISTER_FN, - JIT_UNREGISTER_FN -} jit_actions_t; +enum jit_actions_t { JIT_NOACTION = 0, JIT_REGISTER_FN, JIT_UNREGISTER_FN }; template <typename ptr_t> struct jit_code_entry { ptr_t next_entry; // pointer @@ -58,11 +53,27 @@ namespace { -static constexpr PropertyDefinition g_properties[] = { - {"enable-jit-breakpoint", OptionValue::eTypeBoolean, true, true, nullptr, - {}, "Enable breakpoint on __jit_debug_register_code."}}; +enum EnableJITLoaderGDB { + eEnableJITLoaderGDBDefault, + eEnableJITLoaderGDBOn, + eEnableJITLoaderGDBOff, +}; -enum { ePropertyEnableJITBreakpoint }; +static constexpr OptionEnumValueElement g_enable_jit_loader_gdb_enumerators[] = { + {eEnableJITLoaderGDBDefault, "default", "Enable JIT compilation interface " + "for all platforms except macOS"}, + {eEnableJITLoaderGDBOn, "on", "Enable JIT compilation interface"}, + {eEnableJITLoaderGDBOff, "off", "Disable JIT compilation interface"} + }; + +static constexpr PropertyDefinition g_properties[] = { + {"enable", OptionValue::eTypeEnum, true, + eEnableJITLoaderGDBDefault, nullptr, + OptionEnumValues(g_enable_jit_loader_gdb_enumerators), + "Enable GDB's JIT compilation interface (default: enabled on " + "all platforms except macOS)"}}; + +enum { ePropertyEnable, ePropertyEnableJITBreakpoint }; class PluginProperties : public Properties { public: @@ -71,14 +82,14 @@ } PluginProperties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); } - bool GetEnableJITBreakpoint() const { - return m_collection_sp->GetPropertyAtIndexAsBoolean( - nullptr, ePropertyEnableJITBreakpoint, - g_properties[ePropertyEnableJITBreakpoint].default_uint_value != 0); + EnableJITLoaderGDB GetEnable() const { + return (EnableJITLoaderGDB)m_collection_sp->GetPropertyAtIndexAsEnumeration( + nullptr, ePropertyEnable, + g_properties[ePropertyEnable].default_uint_value); } }; @@ -160,13 +171,8 @@ SetJITBreakpoint(module_list); } -//------------------------------------------------------------------ // Setup the JIT Breakpoint -//------------------------------------------------------------------ void JITLoaderGDB::SetJITBreakpoint(lldb_private::ModuleList &module_list) { - if (!GetGlobalPluginProperties()->GetEnableJITBreakpoint()) - return; - if (DidSetJITBreakpoint()) return; @@ -317,6 +323,10 @@ FileSpec(jit_name), symbolfile_addr, symbolfile_size); if (module_sp && module_sp->GetObjectFile()) { + // Object formats (like ELF) have no representation for a JIT type. + // We will get it wrong, if we deduce it from the header. + module_sp->GetObjectFile()->SetType(ObjectFile::eTypeJIT); + // load the symbol table right away module_sp->GetObjectFile()->GetSymtab(); @@ -391,9 +401,7 @@ return false; // Continue Running. } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString JITLoaderGDB::GetPluginNameStatic() { static ConstString g_name("gdb"); return g_name; @@ -401,9 +409,21 @@ JITLoaderSP JITLoaderGDB::CreateInstance(Process *process, bool force) { JITLoaderSP jit_loader_sp; - ArchSpec arch(process->GetTarget().GetArchitecture()); - if (arch.GetTriple().getVendor() != llvm::Triple::Apple) - jit_loader_sp.reset(new JITLoaderGDB(process)); + bool enable; + switch (GetGlobalPluginProperties()->GetEnable()) { + case EnableJITLoaderGDB::eEnableJITLoaderGDBOn: + enable = true; + break; + case EnableJITLoaderGDB::eEnableJITLoaderGDBOff: + enable = false; + break; + case EnableJITLoaderGDB::eEnableJITLoaderGDBDefault: + ArchSpec arch(process->GetTarget().GetArchitecture()); + enable = arch.GetTriple().getVendor() != llvm::Triple::Apple; + break; + } + if (enable) + jit_loader_sp = std::make_shared<JITLoaderGDB>(process); return jit_loader_sp; } @@ -433,7 +453,7 @@ } addr_t JITLoaderGDB::GetSymbolAddress(ModuleList &module_list, - const ConstString &name, + ConstString name, SymbolType symbol_type) const { SymbolContextList target_symbols; Target &target = m_process->GetTarget();
diff --git a/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.h b/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.h index a220166..2a2537c 100644 --- a/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.h +++ b/src/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.h
@@ -1,9 +1,8 @@ //===-- JITLoaderGDB.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,9 +20,7 @@ ~JITLoaderGDB() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -37,16 +34,12 @@ static void DebuggerInitialize(lldb_private::Debugger &debugger); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - //------------------------------------------------------------------ // JITLoader interface - //------------------------------------------------------------------ void DidAttach() override; void DidLaunch() override; @@ -55,7 +48,7 @@ private: lldb::addr_t GetSymbolAddress(lldb_private::ModuleList &module_list, - const lldb_private::ConstString &name, + lldb_private::ConstString name, lldb::SymbolType symbol_type) const; void SetJITBreakpoint(lldb_private::ModuleList &module_list);
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Language/CMakeLists.txt index c58d896..7869074 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Language/CMakeLists.txt
@@ -2,4 +2,3 @@ add_subdirectory(CPlusPlus) add_subdirectory(ObjC) add_subdirectory(ObjCPlusPlus) -add_subdirectory(Rust)
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp index 4020050..87b5b59 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp
@@ -1,9 +1,8 @@ //===-- BlockPointer.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -150,7 +149,7 @@ // maybe return false if the block pointer is, say, null bool MightHaveChildren() override { return true; } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { if (!m_block_struct_type.IsValid()) return UINT32_MAX;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.h index e5008a8..624c17a 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.h
@@ -1,9 +1,8 @@ //===-- BlockPointer.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CMakeLists.txt index bc357aa..ea36c7e 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CMakeLists.txt
@@ -28,6 +28,7 @@ lldbTarget lldbUtility lldbPluginClangCommon + lldbPluginCPPRuntime LINK_COMPONENTS Support
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp index 982b286..44b9e5e 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -1,9 +1,8 @@ //===-- CPlusPlusLanguage.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -57,9 +56,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString CPlusPlusLanguage::GetPluginName() { return GetPluginNameStatic(); @@ -67,9 +64,7 @@ uint32_t CPlusPlusLanguage::GetPluginVersion() { return 1; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ Language *CPlusPlusLanguage::CreateInstance(lldb::LanguageType language) { if (Language::LanguageIsCPlusPlus(language)) @@ -419,61 +414,49 @@ .SetShowMembersOneLiner(false) .SetHideItemNames(false); -#ifndef LLDB_DISABLE_PYTHON - lldb::TypeSummaryImplSP std_string_summary_sp(new CXXFunctionSummaryFormat( - stl_summary_flags, - lldb_private::formatters::LibcxxStringSummaryProviderASCII, - "std::string summary provider")); - lldb::TypeSummaryImplSP std_stringu16_summary_sp(new CXXFunctionSummaryFormat( - stl_summary_flags, - lldb_private::formatters::LibcxxStringSummaryProviderUTF16, - "std::u16string summary provider")); - lldb::TypeSummaryImplSP std_stringu32_summary_sp(new CXXFunctionSummaryFormat( - stl_summary_flags, - lldb_private::formatters::LibcxxStringSummaryProviderUTF32, - "std::u32string summary provider")); - lldb::TypeSummaryImplSP std_wstring_summary_sp(new CXXFunctionSummaryFormat( - stl_summary_flags, lldb_private::formatters::LibcxxWStringSummaryProvider, - "std::wstring summary provider")); + AddCXXSummary(cpp_category_sp, + lldb_private::formatters::LibcxxStringSummaryProviderASCII, + "std::string summary provider", + ConstString("^std::__[[:alnum:]]+::string$"), stl_summary_flags, + true); + AddCXXSummary(cpp_category_sp, + lldb_private::formatters::LibcxxStringSummaryProviderASCII, + "std::string summary provider", + ConstString("^std::__[[:alnum:]]+::basic_string<char, " + "std::__[[:alnum:]]+::char_traits<char>, " + "std::__[[:alnum:]]+::allocator<char> >$"), + stl_summary_flags, true); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__1::string"), std_string_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__ndk1::string"), std_string_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__1::basic_string<char, std::__1::char_traits<char>, " - "std::__1::allocator<char> >"), - std_string_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString( - "std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, " - "std::__1::allocator<char16_t> >"), - std_stringu16_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString( - "std::__1::basic_string<char32_t, std::__1::char_traits<char32_t>, " - "std::__1::allocator<char32_t> >"), - std_stringu32_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__ndk1::basic_string<char, " - "std::__ndk1::char_traits<char>, " - "std::__ndk1::allocator<char> >"), - std_string_summary_sp); + AddCXXSummary(cpp_category_sp, + lldb_private::formatters::LibcxxStringSummaryProviderUTF16, + "std::u16string summary provider", + ConstString( + "^std::__[[:alnum:]]+::basic_string<char16_t, " + "std::__[[:alnum:]]+::char_traits<char16_t>, " + "std::__[[:alnum:]]+::allocator<char16_t> >$"), + stl_summary_flags, true); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__1::wstring"), std_wstring_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__ndk1::wstring"), std_wstring_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__1::basic_string<wchar_t, " - "std::__1::char_traits<wchar_t>, " - "std::__1::allocator<wchar_t> >"), - std_wstring_summary_sp); - cpp_category_sp->GetTypeSummariesContainer()->Add( - ConstString("std::__ndk1::basic_string<wchar_t, " - "std::__ndk1::char_traits<wchar_t>, " - "std::__ndk1::allocator<wchar_t> >"), - std_wstring_summary_sp); + AddCXXSummary(cpp_category_sp, + lldb_private::formatters::LibcxxStringSummaryProviderUTF32, + "std::u32string summary provider", + ConstString( + "^std::__[[:alnum:]]+::basic_string<char32_t, " + "std::__[[:alnum:]]+::char_traits<char32_t>, " + "std::__[[:alnum:]]+::allocator<char32_t> >$"), + stl_summary_flags, true); + + AddCXXSummary(cpp_category_sp, + lldb_private::formatters::LibcxxWStringSummaryProvider, + "std::wstring summary provider", + ConstString("^std::__[[:alnum:]]+::wstring$"), + stl_summary_flags, true); + AddCXXSummary(cpp_category_sp, + lldb_private::formatters::LibcxxWStringSummaryProvider, + "std::wstring summary provider", + ConstString("^std::__[[:alnum:]]+::basic_string<wchar_t, " + "std::__[[:alnum:]]+::char_traits<wchar_t>, " + "std::__[[:alnum:]]+::allocator<wchar_t> >$"), + stl_summary_flags, true); SyntheticChildren::Flags stl_synth_flags; stl_synth_flags.SetCascades(true).SetSkipPointers(false).SetSkipReferences( @@ -485,54 +468,55 @@ cpp_category_sp, lldb_private::formatters::LibcxxBitsetSyntheticFrontEndCreator, "libc++ std::bitset synthetic children", - ConstString("^std::__(ndk)?1::bitset<.+>(( )?&)?$"), stl_deref_flags, + ConstString("^std::__[[:alnum:]]+::bitset<.+>(( )?&)?$"), stl_deref_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdVectorSyntheticFrontEndCreator, "libc++ std::vector synthetic children", - ConstString("^std::__(ndk)?1::vector<.+>(( )?&)?$"), stl_deref_flags, + ConstString("^std::__[[:alnum:]]+::vector<.+>(( )?&)?$"), stl_deref_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdForwardListSyntheticFrontEndCreator, "libc++ std::forward_list synthetic children", - ConstString("^std::__(ndk)?1::forward_list<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::forward_list<.+>(( )?&)?$"), stl_synth_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdListSyntheticFrontEndCreator, "libc++ std::list synthetic children", - ConstString("^std::__(ndk)?1::list<.+>(( )?&)?$"), stl_synth_flags, true); + ConstString("^std::__[[:alnum:]]+::list<.+>(( )?&)?$"), stl_deref_flags, + true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator, "libc++ std::map synthetic children", - ConstString("^std::__(ndk)?1::map<.+> >(( )?&)?$"), stl_synth_flags, + ConstString("^std::__[[:alnum:]]+::map<.+> >(( )?&)?$"), stl_synth_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator, "libc++ std::set synthetic children", - ConstString("^std::__(ndk)?1::set<.+> >(( )?&)?$"), stl_deref_flags, + ConstString("^std::__[[:alnum:]]+::set<.+> >(( )?&)?$"), stl_deref_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator, "libc++ std::multiset synthetic children", - ConstString("^std::__(ndk)?1::multiset<.+> >(( )?&)?$"), stl_deref_flags, - true); + ConstString("^std::__[[:alnum:]]+::multiset<.+> >(( )?&)?$"), + stl_deref_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator, "libc++ std::multimap synthetic children", - ConstString("^std::__(ndk)?1::multimap<.+> >(( )?&)?$"), stl_synth_flags, - true); + ConstString("^std::__[[:alnum:]]+::multimap<.+> >(( )?&)?$"), + stl_synth_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxStdUnorderedMapSyntheticFrontEndCreator, "libc++ std::unordered containers synthetic children", - ConstString("^(std::__(ndk)?1::)unordered_(multi)?(map|set)<.+> >$"), + ConstString("^(std::__[[:alnum:]]+::)unordered_(multi)?(map|set)<.+> >$"), stl_synth_flags, true); AddCXXSynthetic( cpp_category_sp, @@ -542,29 +526,29 @@ true); AddCXXSynthetic(cpp_category_sp, LibcxxQueueFrontEndCreator, "libc++ std::queue synthetic children", - ConstString("^std::__(ndk)?1::queue<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::queue<.+>(( )?&)?$"), stl_synth_flags, true); AddCXXSynthetic(cpp_category_sp, LibcxxTupleFrontEndCreator, "libc++ std::tuple synthetic children", - ConstString("^std::__(ndk)?1::tuple<.*>(( )?&)?$"), stl_synth_flags, - true); + ConstString("^std::__[[:alnum:]]+::tuple<.*>(( )?&)?$"), + stl_synth_flags, true); AddCXXSynthetic(cpp_category_sp, LibcxxOptionalFrontEndCreator, "libc++ std::optional synthetic children", - ConstString("^std::__(ndk)?1::optional<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::optional<.+>(( )?&)?$"), stl_synth_flags, true); AddCXXSynthetic(cpp_category_sp, LibcxxVariantFrontEndCreator, "libc++ std::variant synthetic children", - ConstString("^std::__(ndk)?1::variant<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::variant<.+>(( )?&)?$"), stl_synth_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxAtomicSyntheticFrontEndCreator, "libc++ std::atomic synthetic children", - ConstString("^std::__(ndk)?1::atomic<.+>$"), stl_synth_flags, true); + ConstString("^std::__[[:alnum:]]+::atomic<.+>$"), stl_synth_flags, true); cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add( RegularExpressionSP(new RegularExpression( - llvm::StringRef("^(std::__(ndk)?1::)deque<.+>(( )?&)?$"))), + llvm::StringRef("^(std::__[[:alnum:]]+::)deque<.+>(( )?&)?$"))), SyntheticChildrenSP(new ScriptedSyntheticChildren( stl_synth_flags, "lldb.formatters.cpp.libcxx.stddeque_SynthProvider"))); @@ -573,94 +557,96 @@ cpp_category_sp, lldb_private::formatters::LibcxxSharedPtrSyntheticFrontEndCreator, "shared_ptr synthetic children", - ConstString("^(std::__(ndk)?1::)shared_ptr<.+>(( )?&)?$"), + ConstString("^(std::__[[:alnum:]]+::)shared_ptr<.+>(( )?&)?$"), stl_synth_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibcxxSharedPtrSyntheticFrontEndCreator, "weak_ptr synthetic children", - ConstString("^(std::__(ndk)?1::)weak_ptr<.+>(( )?&)?$"), stl_synth_flags, - true); + ConstString("^(std::__[[:alnum:]]+::)weak_ptr<.+>(( )?&)?$"), + stl_synth_flags, true); AddCXXSummary( cpp_category_sp, lldb_private::formatters::LibcxxFunctionSummaryProvider, "libc++ std::function summary provider", - ConstString("^std::__(ndk)?1::function<.+>$"), stl_summary_flags, true); + ConstString("^std::__[[:alnum:]]+::function<.+>$"), stl_summary_flags, + true); stl_summary_flags.SetDontShowChildren(false); stl_summary_flags.SetSkipPointers(false); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::bitset summary provider", - ConstString("^std::__(ndk)?1::bitset<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::bitset<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::vector summary provider", - ConstString("^std::__(ndk)?1::vector<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::vector<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::list summary provider", - ConstString("^std::__(ndk)?1::forward_list<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::forward_list<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::list summary provider", - ConstString("^std::__(ndk)?1::list<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::list<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::map summary provider", - ConstString("^std::__(ndk)?1::map<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::map<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::deque summary provider", - ConstString("^std::__(ndk)?1::deque<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::deque<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::queue summary provider", - ConstString("^std::__(ndk)?1::queue<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::queue<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::set summary provider", - ConstString("^std::__(ndk)?1::set<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::set<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::multiset summary provider", - ConstString("^std::__(ndk)?1::multiset<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::multiset<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::multimap summary provider", - ConstString("^std::__(ndk)?1::multimap<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::multimap<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary( cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider, "libc++ std::unordered containers summary provider", - ConstString("^(std::__(ndk)?1::)unordered_(multi)?(map|set)<.+> >$"), + ConstString("^(std::__[[:alnum:]]+::)unordered_(multi)?(map|set)<.+> >$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, LibcxxContainerSummaryProvider, "libc++ std::tuple summary provider", - ConstString("^std::__(ndk)?1::tuple<.*>(( )?&)?$"), stl_summary_flags, - true); + ConstString("^std::__[[:alnum:]]+::tuple<.*>(( )?&)?$"), + stl_summary_flags, true); AddCXXSummary( cpp_category_sp, lldb_private::formatters::LibCxxAtomicSummaryProvider, "libc++ std::atomic summary provider", - ConstString("^std::__(ndk)?1::atomic<.+>$"), stl_summary_flags, true); + ConstString("^std::__[[:alnum:]]+::atomic<.+>$"), stl_summary_flags, + true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxOptionalSummaryProvider, "libc++ std::optional summary provider", - ConstString("^std::__(ndk)?1::optional<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::optional<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxVariantSummaryProvider, "libc++ std::variant summary provider", - ConstString("^std::__(ndk)?1::variant<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::variant<.+>(( )?&)?$"), stl_summary_flags, true); stl_summary_flags.SetSkipPointers(true); @@ -668,27 +654,27 @@ AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxSmartPointerSummaryProvider, "libc++ std::shared_ptr summary provider", - ConstString("^std::__(ndk)?1::shared_ptr<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::shared_ptr<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSummary(cpp_category_sp, lldb_private::formatters::LibcxxSmartPointerSummaryProvider, "libc++ std::weak_ptr summary provider", - ConstString("^std::__(ndk)?1::weak_ptr<.+>(( )?&)?$"), + ConstString("^std::__[[:alnum:]]+::weak_ptr<.+>(( )?&)?$"), stl_summary_flags, true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibCxxVectorIteratorSyntheticFrontEndCreator, "std::vector iterator synthetic children", - ConstString("^std::__(ndk)?1::__wrap_iter<.+>$"), stl_synth_flags, true); + ConstString("^std::__[[:alnum:]]+::__wrap_iter<.+>$"), stl_synth_flags, + true); AddCXXSynthetic( cpp_category_sp, lldb_private::formatters::LibCxxMapIteratorSyntheticFrontEndCreator, "std::map iterator synthetic children", - ConstString("^std::__(ndk)?1::__map_iterator<.+>$"), stl_synth_flags, + ConstString("^std::__[[:alnum:]]+::__map_iterator<.+>$"), stl_synth_flags, true); -#endif } static void LoadLibStdcppFormatters(lldb::TypeCategoryImplSP cpp_category_sp) { @@ -759,8 +745,6 @@ "std::char_traits<wchar_t>, std::allocator<wchar_t> >"), cxx11_wstring_summary_sp); -#ifndef LLDB_DISABLE_PYTHON - SyntheticChildren::Flags stl_synth_flags; stl_synth_flags.SetCascades(true).SetSkipPointers(false).SetSkipReferences( false); @@ -849,7 +833,6 @@ "libstdc++ std::weak_ptr summary provider", ConstString("^std::weak_ptr<.+>(( )?&)?$"), stl_summary_flags, true); -#endif } static void LoadSystemFormatters(lldb::TypeCategoryImplSP cpp_category_sp) { @@ -874,7 +857,6 @@ .SetShowMembersOneLiner(false) .SetHideItemNames(false); -#ifndef LLDB_DISABLE_PYTHON // FIXME because of a bug in the FormattersContainer we need to add a summary // for both X* and const X* (<rdar://problem/12717717>) AddCXXSummary( @@ -927,13 +909,12 @@ AddCXXSummary( cpp_category_sp, lldb_private::formatters::Char16SummaryProvider, "unichar summary provider", ConstString("unichar"), widechar_flags); -#endif } std::unique_ptr<Language::TypeScavenger> CPlusPlusLanguage::GetTypeScavenger() { class CPlusPlusTypeScavenger : public Language::ImageListTypeScavenger { public: - virtual CompilerType AdjustForInclusion(CompilerType &candidate) override { + CompilerType AdjustForInclusion(CompilerType &candidate) override { LanguageType lang_type(candidate.GetMinimumLanguage()); if (!Language::LanguageIsC(lang_type) && !Language::LanguageIsCPlusPlus(lang_type)) @@ -954,8 +935,8 @@ llvm::call_once(g_initialize, [this]() -> void { DataVisualization::Categories::GetCategory(GetPluginName(), g_category); if (g_category) { - LoadLibCxxFormatters(g_category); LoadLibStdcppFormatters(g_category); + LoadLibCxxFormatters(g_category); LoadSystemFormatters(g_category); } });
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h index 3c8ca96..d30e560 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h
@@ -1,9 +1,8 @@ //===-- CPlusPlusLanguage.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,7 +31,7 @@ : m_full(), m_basename(), m_context(), m_arguments(), m_qualifiers(), m_parsed(false), m_parse_error(false) {} - MethodName(const ConstString &s) + MethodName(ConstString s) : m_full(s), m_basename(), m_context(), m_arguments(), m_qualifiers(), m_parsed(false), m_parse_error(false) {} @@ -46,7 +45,7 @@ return (bool)m_full; } - const ConstString &GetFullName() const { return m_full; } + ConstString GetFullName() const { return m_full; } std::string GetScopeQualifiedName(); @@ -93,9 +92,7 @@ const Highlighter *GetHighlighter() const override { return &m_highlighter; } - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -128,9 +125,7 @@ FindAlternateFunctionManglings(const ConstString mangled, std::set<ConstString> &candidates); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp index b32fe95..932db17 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp
@@ -1,9 +1,8 @@ //===-- CPlusPlusNameParser.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -641,6 +640,8 @@ } void CPlusPlusNameParser::ExtractTokens() { + if (m_text.empty()) + return; clang::Lexer lexer(clang::SourceLocation(), GetLangOptions(), m_text.data(), m_text.data(), m_text.data() + m_text.size()); const auto &kw_map = GetKeywordsMap();
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.h index d46a53a..414c3a0 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.h
@@ -1,9 +1,8 @@ //===-- CPlusPlusNameParser.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp index 24185b3..9590790 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp
@@ -1,9 +1,8 @@ //===-- CxxStringTypes.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.h index 8e2ec44..92bef23 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.h
@@ -1,10 +1,9 @@ //===-- CxxStringTypes.h ----------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp index 7e8c06b..abe8903 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp
@@ -1,9 +1,8 @@ //===-- LibCxx.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,7 +18,6 @@ #include "lldb/DataFormatters/TypeSummary.h" #include "lldb/DataFormatters/VectorIterator.h" #include "lldb/Symbol/ClangASTContext.h" -#include "lldb/Target/CPPLanguageRuntime.h" #include "lldb/Target/ProcessStructReader.h" #include "lldb/Target/SectionLoadList.h" #include "lldb/Target/Target.h" @@ -28,6 +26,8 @@ #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" +#include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h" + using namespace lldb; using namespace lldb_private; using namespace lldb_private::formatters; @@ -68,7 +68,7 @@ if (process == nullptr) return false; - CPPLanguageRuntime *cpp_runtime = process->GetCPPLanguageRuntime(); + CPPLanguageRuntime *cpp_runtime = CPPLanguageRuntime::Get(*process); if (!cpp_runtime) return false; @@ -300,10 +300,10 @@ } size_t lldb_private::formatters::LibCxxMapIteratorSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { - if (name == ConstString("first")) + GetIndexOfChildWithName(ConstString name) { + if (name == "first") return 0; - if (name == ConstString("second")) + if (name == "second") return 1; return UINT32_MAX; } @@ -430,12 +430,12 @@ } size_t lldb_private::formatters::LibcxxSharedPtrSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { - if (name == ConstString("__ptr_")) + GetIndexOfChildWithName(ConstString name) { + if (name == "__ptr_") return 0; - if (name == ConstString("count")) + if (name == "count") return 1; - if (name == ConstString("weak_count")) + if (name == "weak_count") return 2; return UINT32_MAX; }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.h index 224a540..214f551 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxx.h
@@ -1,10 +1,9 @@ //===-- LibCxx.h ---------------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -67,7 +66,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; ~LibCxxMapIteratorSyntheticFrontEnd() override; @@ -96,7 +95,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; ~LibcxxSharedPtrSyntheticFrontEnd() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp index dea52e2..b4e7a17 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp
@@ -1,10 +1,9 @@ //===-- LibCxxAtomic.cpp ------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,13 +13,68 @@ using namespace lldb_private; using namespace lldb_private::formatters; +// +// We are supporting two versions of libc++ std::atomic +// +// Given std::atomic<int> i; +// +// The previous version of std::atomic was laid out like this +// +// (lldb) frame var -L -R i +// 0x00007ffeefbff9a0: (std::__1::atomic<int>) i = { +// 0x00007ffeefbff9a0: std::__1::__atomic_base<int, true> = { +// 0x00007ffeefbff9a0: std::__1::__atomic_base<int, false> = { +// 0x00007ffeefbff9a0: __a_ = 5 +// } +// } +// } +// +// In this case we need to obtain __a_ and the current version is laid out as so +// +// (lldb) frame var -L -R i +// 0x00007ffeefbff9b0: (std::__1::atomic<int>) i = { +// 0x00007ffeefbff9b0: std::__1::__atomic_base<int, true> = { +// 0x00007ffeefbff9b0: std::__1::__atomic_base<int, false> = { +// 0x00007ffeefbff9b0: __a_ = { +// 0x00007ffeefbff9b0: std::__1::__cxx_atomic_base_impl<int> = { +// 0x00007ffeefbff9b0: __a_value = 5 +// } +// } +// } +// } +//} +// +// In this case we need to obtain __a_value +// +// The below method covers both cases and returns the relevant member as a +// ValueObjectSP +// +ValueObjectSP +lldb_private::formatters::GetLibCxxAtomicValue(ValueObject &valobj) { + ValueObjectSP non_sythetic = valobj.GetNonSyntheticValue(); + if (!non_sythetic) + return {}; + + ValueObjectSP member__a_ = + non_sythetic->GetChildMemberWithName(ConstString("__a_"), true); + if (!member__a_) + return {}; + + ValueObjectSP member__a_value = + member__a_->GetChildMemberWithName(ConstString("__a_value"), true); + if (!member__a_value) + return member__a_; + + return member__a_value; +} + bool lldb_private::formatters::LibCxxAtomicSummaryProvider( ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) { - static ConstString g___a_("__a_"); - if (ValueObjectSP child = valobj.GetChildMemberWithName(g___a_, true)) { + if (ValueObjectSP atomic_value = GetLibCxxAtomicValue(valobj)) { std::string summary; - if (child->GetSummaryAsCString(summary, options) && summary.size() > 0) { + if (atomic_value->GetSummaryAsCString(summary, options) && + summary.size() > 0) { stream.Printf("%s", summary.c_str()); return true; } @@ -45,7 +99,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; lldb::ValueObjectSP GetSyntheticValue() override; @@ -60,9 +114,9 @@ : SyntheticChildrenFrontEnd(*valobj_sp), m_real_child(nullptr) {} bool lldb_private::formatters::LibcxxStdAtomicSyntheticFrontEnd::Update() { - static ConstString g___a_("__a_"); - - m_real_child = m_backend.GetChildMemberWithName(g___a_, true).get(); + ValueObjectSP atomic_value = GetLibCxxAtomicValue(m_backend); + if (atomic_value) + m_real_child = GetLibCxxAtomicValue(m_backend).get(); return false; } @@ -84,7 +138,7 @@ } size_t lldb_private::formatters::LibcxxStdAtomicSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { return m_real_child ? m_real_child->GetIndexOfChildWithName(name) : UINT32_MAX; }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h index a9d948b..8be833d 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h
@@ -1,10 +1,9 @@ //===-- LibCxxAtomic.h -------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,6 +17,9 @@ namespace lldb_private { namespace formatters { + +lldb::ValueObjectSP GetLibCxxAtomicValue(ValueObject &valobj); + bool LibCxxAtomicSummaryProvider(ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options);
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxBitset.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxBitset.cpp index 489ac4d..815dafb 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxBitset.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxBitset.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxBitset.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,7 @@ public: BitsetFrontEnd(ValueObject &valobj); - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return formatters::ExtractIndexFromString(name.GetCString()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxInitializerList.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxInitializerList.cpp index 390483d..79c7434 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxInitializerList.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxInitializerList.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxInitializerList.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -34,7 +33,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: ValueObject *m_start; @@ -109,7 +108,7 @@ } size_t lldb_private::formatters::LibcxxInitializerListSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { if (!m_start) return UINT32_MAX; return ExtractIndexFromString(name.GetCString());
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp index 81606b5..f5281f2 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxList.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -112,7 +111,7 @@ class AbstractListFrontEnd : public SyntheticChildrenFrontEnd { public: - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return ExtractIndexFromString(name.GetCString()); } bool MightHaveChildren() override { return true; } @@ -385,7 +384,7 @@ if (current_sp->GetName() == g_next) { ProcessSP process_sp(current_sp->GetProcessSP()); if (!process_sp) - return nullptr; + return lldb::ValueObjectSP(); // if we grabbed the __next_ pointer, then the child is one pointer deep-er lldb::addr_t addr = current_sp->GetParent()->GetPointerValue(); @@ -393,6 +392,8 @@ ExecutionContext exe_ctx(process_sp); current_sp = CreateValueObjectFromAddress("__value_", addr, exe_ctx, m_element_type); + if (!current_sp) + return lldb::ValueObjectSP(); } // we need to copy current_sp into a new object otherwise we will end up with
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp index 429569d..619c718 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxMap.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -185,7 +184,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: bool GetDataType(); @@ -453,7 +452,7 @@ } size_t lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { return ExtractIndexFromString(name.GetCString()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxOptional.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxOptional.cpp index 762b824..1160215 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxOptional.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxOptional.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxOptional.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,7 @@ Update(); } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return formatters::ExtractIndexFromString(name.GetCString()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxQueue.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxQueue.cpp index c4e0b66..4b72089 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxQueue.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxQueue.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxQueue.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,7 @@ Update(); } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return m_container_sp ? m_container_sp->GetIndexOfChildWithName(name) : UINT32_MAX; }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxTuple.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxTuple.cpp index 9b412a1..8da7460 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxTuple.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxTuple.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxTuple.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,7 @@ Update(); } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return formatters::ExtractIndexFromString(name.GetCString()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp index 51ae8cb..b2c38c9 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxUnorderedMap.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -40,7 +39,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: CompilerType m_element_type; @@ -210,7 +209,7 @@ } size_t lldb_private::formatters::LibcxxStdUnorderedMapSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { return ExtractIndexFromString(name.GetCString()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.cpp index e874616..491cf04 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxVariant.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -174,7 +173,7 @@ Update(); } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return formatters::ExtractIndexFromString(name.GetCString()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.h index 0483458..65db5ae 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVariant.h
@@ -1,10 +1,9 @@ //===-- LibCxxVariant.h -------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp index ed405c8..bcd7442 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp
@@ -1,9 +1,8 @@ //===-- LibCxxVector.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,7 +32,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: ValueObject *m_start; @@ -54,7 +53,7 @@ bool MightHaveChildren() override { return true; } - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: CompilerType m_bool_type; @@ -165,7 +164,7 @@ } size_t lldb_private::formatters::LibcxxStdVectorSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { if (!m_start || !m_finish) return UINT32_MAX; return ExtractIndexFromString(name.GetCString()); @@ -272,7 +271,7 @@ } size_t lldb_private::formatters::LibcxxVectorBoolSyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { if (!m_count || !m_base_data_address) return UINT32_MAX; const char *item_name = name.GetCString(); @@ -291,7 +290,7 @@ if (!type.IsValid() || type.GetNumTemplateArguments() == 0) return nullptr; CompilerType arg_type = type.GetTypeTemplateArgument(0); - if (arg_type.GetTypeName() == ConstString("bool")) + if (arg_type.GetTypeName() == "bool") return new LibcxxVectorBoolSyntheticFrontEnd(valobj_sp); return new LibcxxStdVectorSyntheticFrontEnd(valobj_sp); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp index 695371f..0e0f666 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp
@@ -1,9 +1,8 @@ //===-- LibStdcpp.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -50,7 +49,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: ExecutionContextRef m_exe_ctx_ref; @@ -71,7 +70,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; }; } // end of anonymous namespace @@ -142,10 +141,10 @@ bool LibstdcppMapIteratorSyntheticFrontEnd::MightHaveChildren() { return true; } size_t LibstdcppMapIteratorSyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { - if (name == ConstString("first")) + ConstString name) { + if (name == "first") return 0; - if (name == ConstString("second")) + if (name == "second") return 1; return UINT32_MAX; } @@ -224,8 +223,8 @@ bool VectorIteratorSyntheticFrontEnd::MightHaveChildren() { return true; } size_t VectorIteratorSyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { - if (name == ConstString("item")) + ConstString name) { + if (name == "item") return 0; return UINT32_MAX; } @@ -374,8 +373,8 @@ bool LibStdcppSharedPtrSyntheticFrontEnd::MightHaveChildren() { return true; } size_t LibStdcppSharedPtrSyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { - if (name == ConstString("_M_ptr")) + ConstString name) { + if (name == "_M_ptr") return 0; return UINT32_MAX; }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.h index 1400477..e7f88d6 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.h
@@ -1,9 +1,8 @@ //===-- LibStdcpp.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppTuple.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppTuple.cpp index 943af6e..66624e5 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppTuple.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppTuple.cpp
@@ -1,9 +1,8 @@ //===-- LibStdcppTuple.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,7 +34,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: std::vector<ValueObjectSP> m_members; @@ -96,7 +95,7 @@ } size_t LibStdcppTupleSyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { + ConstString name) { return ExtractIndexFromString(name.GetCString()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp index 9d46e3e..3860f96 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp
@@ -1,9 +1,8 @@ //===-- LibStdcppUniquePointer.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,7 +34,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; bool GetSummary(Stream &stream, const TypeSummaryOptions &options); @@ -130,13 +129,12 @@ } size_t LibStdcppUniquePtrSyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { - if (name == ConstString("ptr") || name == ConstString("pointer")) + ConstString name) { + if (name == "ptr" || name == "pointer") return 0; - if (name == ConstString("del") || name == ConstString("deleter")) + if (name == "del" || name == "deleter") return 1; - if (name == ConstString("obj") || name == ConstString("object") || - name == ConstString("$$dereference$$")) + if (name == "obj" || name == "object" || name == "$$dereference$$") return 2; return UINT32_MAX; }
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.cpp b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.cpp index 84f03e0..248c51a 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.cpp
@@ -1,9 +1,8 @@ //===-- MSVCUndecoratedNameParser.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h index 0c49100..6e20877 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h +++ b/src/llvm-project/lldb/source/Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h
@@ -1,9 +1,8 @@ //===-- MSVCUndecoratedNameParser.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp b/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp index 1fe8482..a9a1b44 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp
@@ -1,14 +1,14 @@ //===-- ClangHighlighter.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "ClangHighlighter.h" +#include "lldb/Host/FileSystem.h" #include "lldb/Target/Language.h" #include "lldb/Utility/AnsiTerminal.h" #include "lldb/Utility/StreamString.h" @@ -136,7 +136,8 @@ using namespace clang; FileSystemOptions file_opts; - FileManager file_mgr(file_opts); + FileManager file_mgr(file_opts, + FileSystem::Instance().GetVirtualFileSystem()); unsigned line_number = previous_lines.count('\n') + 1U;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.h b/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.h index 579c431..f459f94 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.h
@@ -1,9 +1,8 @@ //===-- ClangHighlighter.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.cpp index e3dab5a..5bca260 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.cpp
@@ -1,10 +1,9 @@ //===-- CF.cpp ----------------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,7 +14,6 @@ #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/Language.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" @@ -23,6 +21,8 @@ #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + using namespace lldb; using namespace lldb_private; using namespace lldb_private::formatters; @@ -51,9 +51,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -115,9 +113,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -140,10 +136,8 @@ bool is_type_ok = false; // check to see if this is a CFBag we know about if (descriptor->IsCFType()) { ConstString type_name(valobj.GetTypeName()); - if (type_name == ConstString("__CFMutableBitVector") || - type_name == ConstString("__CFBitVector") || - type_name == ConstString("CFMutableBitVectorRef") || - type_name == ConstString("CFBitVectorRef")) { + if (type_name == "__CFMutableBitVector" || type_name == "__CFBitVector" || + type_name == "CFMutableBitVectorRef" || type_name == "CFBitVectorRef") { if (valobj.IsPointerType()) is_type_ok = true; } @@ -239,9 +233,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.h b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.h index 6945f9e..2abb56d 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CF.h
@@ -1,9 +1,8 @@ //===-- CF.h ---------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.cpp index 4808537..ddf3953 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.cpp
@@ -1,9 +1,8 @@ //===-- Cocoa.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,7 +17,6 @@ #include "lldb/Host/Time.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/Language.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/ProcessStructReader.h" #include "lldb/Target/Target.h" @@ -28,6 +26,7 @@ #include "lldb/Utility/Stream.h" #include "llvm/ADT/APInt.h" +#include "llvm/ADT/bit.h" #include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h" @@ -43,9 +42,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -93,9 +90,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -140,9 +135,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -187,9 +180,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -235,9 +226,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -426,9 +415,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -484,10 +471,9 @@ return true; } else { Status error; - - AppleObjCRuntime *runtime = - llvm::dyn_cast_or_null<AppleObjCRuntime>( - process_sp->GetObjCLanguageRuntime()); + + AppleObjCRuntime *runtime = llvm::dyn_cast_or_null<AppleObjCRuntime>( + ObjCLanguageRuntime::Get(*process_sp)); const bool new_format = (runtime && runtime->GetFoundationVersion() >= 1400); @@ -679,9 +665,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -750,24 +734,18 @@ /// distantFuture, except within about 1e-25 second of the reference date. const int TAGGED_DATE_EXPONENT_BIAS = 0x3ef; -typedef union { - struct { - uint64_t fraction:52; // unsigned - uint64_t exponent:11; // signed - uint64_t sign:1; - }; - uint64_t i; - double d; -} DoubleBits; -typedef union { - struct { - uint64_t fraction:52; // unsigned - uint64_t exponent:7; // signed - uint64_t sign:1; - uint64_t unused:4; // placeholder for pointer tag bits - }; - uint64_t i; -} TaggedDoubleBits; +struct DoubleBits { + uint64_t fraction : 52; // unsigned + uint64_t exponent : 11; // signed + uint64_t sign : 1; +}; + +struct TaggedDoubleBits { + uint64_t fraction : 52; // unsigned + uint64_t exponent : 7; // signed + uint64_t sign : 1; + uint64_t unused : 4; // placeholder for pointer tag bits +}; static uint64_t decodeExponent(uint64_t exp) { // Tagged exponent field is 7-bit signed. Sign-extend the value to 64 bits @@ -775,24 +753,24 @@ return llvm::SignExtend64<7>(exp) + TAGGED_DATE_EXPONENT_BIAS; } -static uint64_t decodeTaggedTimeInterval(uint64_t encodedTimeInterval) { +static double decodeTaggedTimeInterval(uint64_t encodedTimeInterval) { if (encodedTimeInterval == 0) return 0.0; if (encodedTimeInterval == std::numeric_limits<uint64_t>::max()) return (uint64_t)-0.0; - TaggedDoubleBits encodedBits = {}; - encodedBits.i = encodedTimeInterval; - DoubleBits decodedBits; + TaggedDoubleBits encodedBits = + llvm::bit_cast<TaggedDoubleBits>(encodedTimeInterval); + assert(encodedBits.unused == 0); // Sign and fraction are represented exactly. // Exponent is encoded. - assert(encodedBits.unused == 0); + DoubleBits decodedBits; decodedBits.sign = encodedBits.sign; decodedBits.fraction = encodedBits.fraction; decodedBits.exponent = decodeExponent(encodedBits.exponent); - return decodedBits.d; + return llvm::bit_cast<double>(decodedBits); } bool lldb_private::formatters::NSDateSummaryProvider( @@ -801,9 +779,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -869,7 +845,8 @@ // Accomodate for the __NSTaggedDate format introduced in Foundation 1600. if (class_name == g___NSTaggedDate) { - auto *runtime = llvm::dyn_cast_or_null<AppleObjCRuntime>(process_sp->GetObjCLanguageRuntime()); + auto *runtime = llvm::dyn_cast_or_null<AppleObjCRuntime>( + ObjCLanguageRuntime::Get(*process_sp)); if (runtime && runtime->GetFoundationVersion() >= 1600) date_value = decodeTaggedTimeInterval(value_bits << 4); } @@ -897,9 +874,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -940,7 +915,7 @@ bool MightHaveChildren() override { return false; } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { return UINT32_MAX; } }; @@ -958,9 +933,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -1059,8 +1032,8 @@ if (!process_sp) return false; - if (AppleObjCRuntime *objc_runtime = - (AppleObjCRuntime *)process_sp->GetObjCLanguageRuntime()) { + if (AppleObjCRuntime *objc_runtime = llvm::dyn_cast_or_null<AppleObjCRuntime>( + ObjCLanguageRuntime::Get(*process_sp))) { lldb::addr_t cf_true = LLDB_INVALID_ADDRESS, cf_false = LLDB_INVALID_ADDRESS; objc_runtime->GetValuesForGlobalCFBooleans(cf_true, cf_false);
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.h b/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.h index 0f2ca54..388e6f0 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/Cocoa.h
@@ -1,10 +1,9 @@ //===-- Cocoa.h ---------------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,10 @@ #include "lldb/Core/ValueObject.h" #include "lldb/DataFormatters/TypeSummary.h" #include "lldb/DataFormatters/TypeSynthetic.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Utility/Stream.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + namespace lldb_private { namespace formatters { bool NSIndexSetSummaryProvider(ValueObject &valobj, Stream &stream,
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.cpp index cbc38c9..d19290e 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.cpp
@@ -1,10 +1,9 @@ //===-- CoreMedia.cpp --------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.h b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.h index 98561efb..79abb67 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/CoreMedia.h
@@ -1,10 +1,9 @@ //===-- CoreMedia.h -----------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSArray.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSArray.cpp index 6c110da..404dabf 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSArray.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSArray.cpp
@@ -1,9 +1,8 @@ //===-- NSArray.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,13 +11,13 @@ #include "Cocoa.h" #include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h" + #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/Expression/FunctionCaller.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/Language.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" @@ -58,7 +57,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; protected: virtual lldb::addr_t GetDataAddress() = 0; @@ -172,13 +171,8 @@ PtrType _data; uint32_t _offset; uint32_t _size; - union { - PtrType _mutations; - struct { - uint32_t _muts; - uint32_t _used; - }; - }; + uint32_t _muts; + uint32_t _used; }; using NSArrayMSyntheticFrontEnd = @@ -248,7 +242,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: ExecutionContextRef m_exe_ctx_ref; @@ -320,7 +314,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; }; class NSArray1SyntheticFrontEnd : public SyntheticChildrenFrontEnd { @@ -337,7 +331,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; }; } // namespace formatters } // namespace lldb_private @@ -350,9 +344,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -550,7 +542,7 @@ size_t lldb_private::formatters::NSArrayMSyntheticFrontEndBase::GetIndexOfChildWithName( - const ConstString &name) { + ConstString name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren()) @@ -639,7 +631,7 @@ template <typename D32, typename D64, bool Inline> size_t lldb_private::formatters::GenericNSArrayISyntheticFrontEnd<D32, D64, Inline>:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren()) @@ -729,7 +721,7 @@ size_t lldb_private::formatters::NSArray0SyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { + ConstString name) { return UINT32_MAX; } @@ -758,7 +750,7 @@ size_t lldb_private::formatters::NSArray1SyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { + ConstString name) { static const ConstString g_zero("[0]"); if (name == g_zero) @@ -805,7 +797,7 @@ if (!process_sp) return nullptr; AppleObjCRuntime *runtime = llvm::dyn_cast_or_null<AppleObjCRuntime>( - process_sp->GetObjCLanguageRuntime()); + ObjCLanguageRuntime::Get(*process_sp)); if (!runtime) return nullptr;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp index 9a7fc2b..10f66c4 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp
@@ -1,9 +1,8 @@ //===-- NSDictionary.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,7 +19,6 @@ #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/Language.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" @@ -112,7 +110,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: struct DataDescriptor_32 { @@ -155,7 +153,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: ValueObjectSP m_pair; @@ -176,7 +174,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: struct DictionaryItemDescriptor { @@ -209,7 +207,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: struct DataDescriptor_32 { @@ -282,18 +280,11 @@ struct DataDescriptor_32 { uint32_t _buffer; - union { - struct { - uint32_t _mutations; - }; - struct { - uint32_t _muts; - uint32_t _used:25; - uint32_t _kvo:1; - uint32_t _szidx:6; - }; - }; - + uint32_t _muts; + uint32_t _used : 25; + uint32_t _kvo : 1; + uint32_t _szidx : 6; + uint64_t GetSize() { return (_szidx) >= NSDictionaryNumSizeBuckets ? 0 : NSDictionaryCapacities[_szidx]; @@ -302,18 +293,11 @@ struct DataDescriptor_64 { uint64_t _buffer; - union { - struct { - uint64_t _mutations; - }; - struct { - uint32_t _muts; - uint32_t _used:25; - uint32_t _kvo:1; - uint32_t _szidx:6; - }; - }; - + uint32_t _muts; + uint32_t _used : 25; + uint32_t _kvo : 1; + uint32_t _szidx : 6; + uint64_t GetSize() { return (_szidx) >= NSDictionaryNumSizeBuckets ? 0 : NSDictionaryCapacities[_szidx]; @@ -362,9 +346,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -454,8 +436,8 @@ lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) return nullptr; - AppleObjCRuntime *runtime = - llvm::dyn_cast_or_null<AppleObjCRuntime>(process_sp->GetObjCLanguageRuntime()); + AppleObjCRuntime *runtime = llvm::dyn_cast_or_null<AppleObjCRuntime>( + ObjCLanguageRuntime::Get(*process_sp)); if (!runtime) return nullptr; @@ -527,7 +509,7 @@ } size_t lldb_private::formatters::NSDictionaryISyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren()) @@ -663,7 +645,7 @@ : SyntheticChildrenFrontEnd(*valobj_sp.get()), m_pair(nullptr) {} size_t lldb_private::formatters::NSDictionary1SyntheticFrontEnd:: - GetIndexOfChildWithName(const ConstString &name) { + GetIndexOfChildWithName(ConstString name) { static const ConstString g_zero("[0]"); return name == g_zero ? 0 : UINT32_MAX; } @@ -751,7 +733,7 @@ template <typename D32, typename D64> size_t -lldb_private::formatters::GenericNSDictionaryMSyntheticFrontEnd<D32,D64>:: GetIndexOfChildWithName(const ConstString &name) { +lldb_private::formatters::GenericNSDictionaryMSyntheticFrontEnd<D32,D64>:: GetIndexOfChildWithName(ConstString name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren()) @@ -920,7 +902,7 @@ size_t lldb_private::formatters::Foundation1100:: - NSDictionaryMSyntheticFrontEnd::GetIndexOfChildWithName(const ConstString &name) { + NSDictionaryMSyntheticFrontEnd::GetIndexOfChildWithName(ConstString name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren())
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.h b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.h index 6ec9a8e..ecb3fcc 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSDictionary.h
@@ -1,10 +1,9 @@ //===-- NSDictionary.h ---------------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -52,8 +51,8 @@ class Prefix : public Matcher { public: Prefix(ConstString p); - virtual ~Prefix() = default; - virtual bool Match(ConstString class_name) override; + ~Prefix() override = default; + bool Match(ConstString class_name) override; private: ConstString m_prefix; @@ -61,8 +60,8 @@ class Full : public Matcher { public: Full(ConstString n); - virtual ~Full() = default; - virtual bool Match(ConstString class_name) override; + ~Full() override = default; + bool Match(ConstString class_name) override; private: ConstString m_name;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSError.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSError.cpp index 975bda5..97df3be 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSError.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSError.cpp
@@ -1,9 +1,8 @@ //===-- NSError.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,7 +14,6 @@ #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/Symbol/ClangASTContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/ProcessStructReader.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" @@ -24,6 +22,7 @@ #include "lldb/Utility/Stream.h" #include "Plugins/Language/ObjC/NSString.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" using namespace lldb; using namespace lldb_private; @@ -164,7 +163,7 @@ bool MightHaveChildren() override { return true; } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { static ConstString g___userInfo("_userInfo"); if (name == g___userInfo) return 0; @@ -188,9 +187,7 @@ lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) return nullptr; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return nullptr;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSException.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSException.cpp index 2404ef9..931794a 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSException.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSException.cpp
@@ -1,9 +1,8 @@ //===-- NSException.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,7 +14,6 @@ #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/Symbol/ClangASTContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/ProcessStructReader.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" @@ -24,6 +22,7 @@ #include "lldb/Utility/Stream.h" #include "Plugins/Language/ObjC/NSString.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" using namespace lldb; using namespace lldb_private; @@ -150,7 +149,7 @@ bool MightHaveChildren() override { return true; } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { // NSException has 4 members: // NSString *name; // NSString *reason; @@ -180,9 +179,7 @@ lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) return nullptr; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return nullptr;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSIndexPath.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSIndexPath.cpp index 41df9ab..9ee6021 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSIndexPath.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSIndexPath.cpp
@@ -1,9 +1,8 @@ //===-- NSIndexPath.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,10 +13,10 @@ #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/DataFormatters/TypeSynthetic.h" #include "lldb/Symbol/ClangASTContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" using namespace lldb; using namespace lldb_private; using namespace lldb_private::formatters; @@ -69,9 +68,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -128,7 +125,7 @@ bool MightHaveChildren() override { return m_impl.m_mode != Mode::Invalid; } - size_t GetIndexOfChildWithName(const ConstString &name) override { + size_t GetIndexOfChildWithName(ConstString name) override { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren())
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.cpp index 7e03d75..ebaa990 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.cpp
@@ -1,9 +1,8 @@ //===-- NSSet.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,7 +14,6 @@ #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/Language.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" @@ -55,7 +53,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: struct DataDescriptor_32 { @@ -96,7 +94,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; private: @@ -155,28 +153,18 @@ uint32_t _cow; // __table storage uint32_t _objs_addr; - union { - uint32_t _mutations; - struct { - uint32_t _muts; - uint32_t _used : 26; - uint32_t _szidx : 6; - }; - }; + uint32_t _muts; + uint32_t _used : 26; + uint32_t _szidx : 6; }; struct DataDescriptor_64 { uint64_t _cow; // __Table storage uint64_t _objs_addr; - union { - uint64_t _mutations; - struct { - uint32_t _muts; - uint32_t _used : 26; - uint32_t _szidx : 6; - }; - }; + uint32_t _muts; + uint32_t _used : 26; + uint32_t _szidx : 6; }; using NSSetMSyntheticFrontEnd = @@ -222,7 +210,7 @@ bool MightHaveChildren() override; - size_t GetIndexOfChildWithName(const ConstString &name) override; + size_t GetIndexOfChildWithName(ConstString name) override; }; } // namespace formatters } // namespace lldb_private @@ -236,9 +224,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false; @@ -315,9 +301,7 @@ lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) return nullptr; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return nullptr; @@ -385,7 +369,7 @@ size_t lldb_private::formatters::NSSetISyntheticFrontEnd::GetIndexOfChildWithName( - const ConstString &name) { + ConstString name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren()) @@ -540,7 +524,7 @@ size_t lldb_private::formatters:: GenericNSSetMSyntheticFrontEnd<D32, D64>::GetIndexOfChildWithName( - const ConstString &name) { + ConstString name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); if (idx < UINT32_MAX && idx >= CalculateNumChildren())
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.h b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.h index 00451be..f11b6d4 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSSet.h
@@ -1,10 +1,9 @@ //===-- NSSet.h ---------------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.cpp index f882b2a..4800c95 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.cpp
@@ -1,10 +1,9 @@ //===-- NSString.cpp ----------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -60,9 +59,7 @@ if (!process_sp) return false; - ObjCLanguageRuntime *runtime = - (ObjCLanguageRuntime *)process_sp->GetLanguageRuntime( - lldb::eLanguageTypeObjC); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (!runtime) return false;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.h b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.h index 3a923c2..699d8eb 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/NSString.h
@@ -1,10 +1,9 @@ //===-- NSString.h ---------------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,10 @@ #include "lldb/Core/ValueObject.h" #include "lldb/DataFormatters/TypeSummary.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Utility/Stream.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + namespace lldb_private { namespace formatters { bool NSStringSummaryProvider(ValueObject &valobj, Stream &stream,
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp index 0598d69..f9ab186 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
@@ -1,9 +1,8 @@ //===-- ObjCLanguage.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,13 +16,14 @@ #include "lldb/DataFormatters/FormattersHelpers.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/CompilerType.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/StreamString.h" #include "llvm/Support/Threading.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + #include "CF.h" #include "Cocoa.h" #include "CoreMedia.h" @@ -49,9 +49,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ObjCLanguage::GetPluginName() { return GetPluginNameStatic(); @@ -59,9 +57,7 @@ uint32_t ObjCLanguage::GetPluginVersion() { return 1; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ Language *ObjCLanguage::CreateInstance(lldb::LanguageType language) { switch (language) { @@ -120,7 +116,7 @@ return SetName(llvm::StringRef(name), strict); } -const ConstString &ObjCLanguage::MethodName::GetClassName() { +ConstString ObjCLanguage::MethodName::GetClassName() { if (!m_class) { if (IsValid(false)) { const char *full = m_full.GetCString(); @@ -146,7 +142,7 @@ return m_class; } -const ConstString &ObjCLanguage::MethodName::GetClassNameWithCategory() { +ConstString ObjCLanguage::MethodName::GetClassNameWithCategory() { if (!m_class_category) { if (IsValid(false)) { const char *full = m_full.GetCString(); @@ -169,7 +165,7 @@ return m_class_category; } -const ConstString &ObjCLanguage::MethodName::GetSelector() { +ConstString ObjCLanguage::MethodName::GetSelector() { if (!m_selector) { if (IsValid(false)) { const char *full = m_full.GetCString(); @@ -184,7 +180,7 @@ return m_selector; } -const ConstString &ObjCLanguage::MethodName::GetCategory() { +ConstString ObjCLanguage::MethodName::GetCategory() { if (!m_category_is_valid && !m_category) { if (IsValid(false)) { m_category_is_valid = true; @@ -225,43 +221,46 @@ return ConstString(); } -size_t ObjCLanguage::MethodName::GetFullNames(std::vector<ConstString> &names, - bool append) { - if (!append) - names.clear(); - if (IsValid(false)) { +std::vector<ConstString> +ObjCLanguage::GetMethodNameVariants(ConstString method_name) const { + std::vector<ConstString> variant_names; + ObjCLanguage::MethodName objc_method(method_name.GetCString(), false); + if (!objc_method.IsValid(false)) { + return variant_names; + } + + const bool is_class_method = + objc_method.GetType() == MethodName::eTypeClassMethod; + const bool is_instance_method = + objc_method.GetType() == MethodName::eTypeInstanceMethod; + ConstString name_sans_category = + objc_method.GetFullNameWithoutCategory(/*empty_if_no_category*/ true); + + if (is_class_method || is_instance_method) { + if (name_sans_category) + variant_names.emplace_back(name_sans_category); + } else { StreamString strm; - const bool is_class_method = m_type == eTypeClassMethod; - const bool is_instance_method = m_type == eTypeInstanceMethod; - const ConstString &category = GetCategory(); - if (is_class_method || is_instance_method) { - names.push_back(m_full); - if (category) { - strm.Printf("%c[%s %s]", is_class_method ? '+' : '-', - GetClassName().GetCString(), GetSelector().GetCString()); - names.emplace_back(strm.GetString()); - } - } else { - const ConstString &class_name = GetClassName(); - const ConstString &selector = GetSelector(); - strm.Printf("+[%s %s]", class_name.GetCString(), selector.GetCString()); - names.emplace_back(strm.GetString()); + + strm.Printf("+%s", objc_method.GetFullName().GetCString()); + variant_names.emplace_back(strm.GetString()); + strm.Clear(); + + strm.Printf("-%s", objc_method.GetFullName().GetCString()); + variant_names.emplace_back(strm.GetString()); + strm.Clear(); + + if (name_sans_category) { + strm.Printf("+%s", name_sans_category.GetCString()); + variant_names.emplace_back(strm.GetString()); strm.Clear(); - strm.Printf("-[%s %s]", class_name.GetCString(), selector.GetCString()); - names.emplace_back(strm.GetString()); - strm.Clear(); - if (category) { - strm.Printf("+[%s(%s) %s]", class_name.GetCString(), - category.GetCString(), selector.GetCString()); - names.emplace_back(strm.GetString()); - strm.Clear(); - strm.Printf("-[%s(%s) %s]", class_name.GetCString(), - category.GetCString(), selector.GetCString()); - names.emplace_back(strm.GetString()); - } + + strm.Printf("-%s", name_sans_category.GetCString()); + variant_names.emplace_back(strm.GetString()); } } - return names.size(); + + return variant_names; } static void LoadObjCFormatters(TypeCategoryImplSP objc_category_sp) { @@ -286,7 +285,6 @@ objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL *"), ObjC_BOOL_summary); -#ifndef LLDB_DISABLE_PYTHON // we need to skip pointers here since we are special casing a SEL* when // retrieving its value objc_flags.SetSkipPointers(true); @@ -318,7 +316,6 @@ lldb_private::formatters::ObjCClassSyntheticFrontEndCreator, "Class synthetic children", ConstString("Class"), class_synth_flags); -#endif // LLDB_DISABLE_PYTHON objc_flags.SetSkipPointers(false); objc_flags.SetCascades(true); @@ -384,7 +381,6 @@ appkit_flags.SetDontShowChildren(false); -#ifndef LLDB_DISABLE_PYTHON AddCXXSummary( objc_category_sp, lldb_private::formatters::NSArraySummaryProvider, "NSArray summary provider", ConstString("NSArray"), appkit_flags); @@ -841,7 +837,6 @@ lldb_private::formatters::CFBitVectorSummaryProvider, "CFBitVector summary provider", ConstString("__CFMutableBitVector"), appkit_flags); -#endif // LLDB_DISABLE_PYTHON } static void LoadCoreMediaFormatters(TypeCategoryImplSP objc_category_sp) { @@ -857,11 +852,9 @@ .SetSkipPointers(false) .SetSkipReferences(false); -#ifndef LLDB_DISABLE_PYTHON AddCXXSummary(objc_category_sp, lldb_private::formatters::CMTimeSummaryProvider, "CMTime summary provider", ConstString("CMTime"), cm_flags); -#endif // LLDB_DISABLE_PYTHON } lldb::TypeCategoryImplSP ObjCLanguage::GetFormatters() { @@ -898,7 +891,7 @@ lldb::ProcessSP process_sp = valobj.GetProcessSP(); if (!process_sp) break; - ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime(); + ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process_sp); if (runtime == nullptr) break; ObjCLanguageRuntime::ClassDescriptorSP objc_class_sp( @@ -940,26 +933,16 @@ ResultSet &results) override { bool result = false; - Process *process = exe_scope->CalculateProcess().get(); - if (process) { - const bool create_on_demand = false; - auto objc_runtime = process->GetObjCLanguageRuntime(create_on_demand); - if (objc_runtime) { - auto decl_vendor = objc_runtime->GetDeclVendor(); - if (decl_vendor) { - std::vector<clang::NamedDecl *> decls; + if (auto *process = exe_scope->CalculateProcess().get()) { + if (auto *objc_runtime = ObjCLanguageRuntime::Get(*process)) { + if (auto *decl_vendor = objc_runtime->GetDeclVendor()) { ConstString name(key); - decl_vendor->FindDecls(name, true, UINT32_MAX, decls); - for (auto decl : decls) { - if (decl) { - if (CompilerType candidate = - ClangASTContext::GetTypeForDecl(decl)) { - result = true; - std::unique_ptr<Language::TypeScavenger::Result> result( - new ObjCScavengerResult(candidate)); - results.insert(std::move(result)); - } - } + for (const CompilerType &type : + decl_vendor->FindTypes(name, /*max_matches*/ UINT32_MAX)) { + result = true; + std::unique_ptr<Language::TypeScavenger::Result> result( + new ObjCScavengerResult(type)); + results.insert(std::move(result)); } } } @@ -977,21 +960,16 @@ ResultSet &results) override { bool result = false; - Target *target = exe_scope->CalculateTarget().get(); - if (target) { - if (auto clang_modules_decl_vendor = + if (auto *target = exe_scope->CalculateTarget().get()) { + if (auto *clang_modules_decl_vendor = target->GetClangModulesDeclVendor()) { - std::vector<clang::NamedDecl *> decls; ConstString key_cs(key); - - if (clang_modules_decl_vendor->FindDecls(key_cs, false, UINT32_MAX, - decls) > 0 && - !decls.empty()) { - CompilerType module_type = - ClangASTContext::GetTypeForDecl(decls.front()); + auto types = clang_modules_decl_vendor->FindTypes( + key_cs, /*max_matches*/ UINT32_MAX); + if (!types.empty()) { result = true; std::unique_ptr<Language::TypeScavenger::Result> result( - new ObjCScavengerResult(module_type)); + new ObjCScavengerResult(types.front())); results.insert(std::move(result)); } } @@ -1005,7 +983,7 @@ class ObjCDebugInfoScavenger : public Language::ImageListTypeScavenger { public: - virtual CompilerType AdjustForInclusion(CompilerType &candidate) override { + CompilerType AdjustForInclusion(CompilerType &candidate) override { LanguageType lang_type(candidate.GetMinimumLanguage()); if (!Language::LanguageIsObjC(lang_type)) return CompilerType();
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.h b/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.h index 114f932..3e2cc09 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjC/ObjCLanguage.h
@@ -1,9 +1,8 @@ //===-- ObjCLanguage.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -59,32 +58,20 @@ Type GetType() const { return m_type; } - const ConstString &GetFullName() const { return m_full; } + ConstString GetFullName() const { return m_full; } ConstString GetFullNameWithoutCategory(bool empty_if_no_category); bool SetName(const char *name, bool strict); bool SetName(llvm::StringRef name, bool strict); - const ConstString &GetClassName(); + ConstString GetClassName(); - const ConstString &GetClassNameWithCategory(); + ConstString GetClassNameWithCategory(); - const ConstString &GetCategory(); + ConstString GetCategory(); - const ConstString &GetSelector(); - - // Get all possible names for a method. Examples: - // If name is "+[NSString(my_additions) myStringWithCString:]" - // names[0] => "+[NSString(my_additions) myStringWithCString:]" - // names[1] => "+[NSString myStringWithCString:]" - // If name is specified without the leading '+' or '-' like - // "[NSString(my_additions) myStringWithCString:]" - // names[0] => "+[NSString(my_additions) myStringWithCString:]" - // names[1] => "-[NSString(my_additions) myStringWithCString:]" - // names[2] => "+[NSString myStringWithCString:]" - // names[3] => "-[NSString myStringWithCString:]" - size_t GetFullNames(std::vector<ConstString> &names, bool append); + ConstString GetSelector(); protected: ConstString @@ -106,6 +93,18 @@ return lldb::eLanguageTypeObjC; } + // Get all possible names for a method. Examples: + // If method_name is "+[NSString(my_additions) myStringWithCString:]" + // variant_names[0] => "+[NSString myStringWithCString:]" + // If name is specified without the leading '+' or '-' like + // "[NSString(my_additions) myStringWithCString:]" + // variant_names[0] => "+[NSString(my_additions) myStringWithCString:]" + // variant_names[1] => "-[NSString(my_additions) myStringWithCString:]" + // variant_names[2] => "+[NSString myStringWithCString:]" + // variant_names[3] => "-[NSString myStringWithCString:]" + std::vector<ConstString> + GetMethodNameVariants(ConstString method_name) const override; + lldb::TypeCategoryImplSP GetFormatters() override; std::vector<ConstString> @@ -124,9 +123,7 @@ const Highlighter *GetHighlighter() const override { return &m_highlighter; } - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -155,9 +152,7 @@ return false; } - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.cpp b/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.cpp index 5e6d86e..81b3c58 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.cpp +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.cpp
@@ -1,10 +1,9 @@ //===-- ObjCPlusPlusLanguage.cpp --------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -39,18 +38,14 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ObjCPlusPlusLanguage::GetPluginName() { return GetPluginNameStatic(); } uint32_t ObjCPlusPlusLanguage::GetPluginVersion() { return 1; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ Language *ObjCPlusPlusLanguage::CreateInstance(lldb::LanguageType language) { switch (language) { case lldb::eLanguageTypeObjC_plus_plus:
diff --git a/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.h b/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.h index b64f0f8..6224a3f 100644 --- a/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.h +++ b/src/llvm-project/lldb/source/Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.h
@@ -1,9 +1,8 @@ //===-- ObjCPlusPlusLanguage.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,9 +31,7 @@ const Highlighter *GetHighlighter() const override { return &m_highlighter; } - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -43,9 +40,7 @@ static lldb_private::ConstString GetPluginNameStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Language/Rust/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Language/Rust/CMakeLists.txt deleted file mode 100644 index 4ad4166..0000000 --- a/src/llvm-project/lldb/source/Plugins/Language/Rust/CMakeLists.txt +++ /dev/null
@@ -1,11 +0,0 @@ -add_lldb_library(lldbPluginRustLanguage PLUGIN - RustLanguage.cpp - - LINK_LIBS - lldbCore - lldbDataFormatters - lldbSymbol - lldbTarget - LINK_COMPONENTS - Support -)
diff --git a/src/llvm-project/lldb/source/Plugins/Language/Rust/RustLanguage.cpp b/src/llvm-project/lldb/source/Plugins/Language/Rust/RustLanguage.cpp deleted file mode 100644 index b3d5b11..0000000 --- a/src/llvm-project/lldb/source/Plugins/Language/Rust/RustLanguage.cpp +++ /dev/null
@@ -1,60 +0,0 @@ -//===-- RustLanguage.cpp ----------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -// C Includes -#include <string.h> -// C++ Includes -#include <functional> -#include <mutex> - -// Other libraries and framework includes -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/Threading.h" - -// Project includes -#include "RustLanguage.h" -#include "lldb/Core/PluginManager.h" -#include "lldb/DataFormatters/DataVisualization.h" -#include "lldb/DataFormatters/FormattersHelpers.h" -#include "lldb/Symbol/RustASTContext.h" -#include "lldb/Utility/ConstString.h" - -using namespace lldb; -using namespace lldb_private; -using namespace lldb_private::formatters; - -void RustLanguage::Initialize() { - PluginManager::RegisterPlugin(GetPluginNameStatic(), "Rust Language", - CreateInstance); -} - -void RustLanguage::Terminate() { - PluginManager::UnregisterPlugin(CreateInstance); -} - -lldb_private::ConstString RustLanguage::GetPluginNameStatic() { - static ConstString g_name("Rust"); - return g_name; -} - -lldb_private::ConstString RustLanguage::GetPluginName() { - return GetPluginNameStatic(); -} - -uint32_t RustLanguage::GetPluginVersion() { return 1; } - -Language *RustLanguage::CreateInstance(lldb::LanguageType language) { - if (language == eLanguageTypeRust) - return new RustLanguage(); - return nullptr; -} - -bool RustLanguage::IsSourceFile(llvm::StringRef file_path) const { - return file_path.endswith(".rs"); -}
diff --git a/src/llvm-project/lldb/source/Plugins/Language/Rust/RustLanguage.h b/src/llvm-project/lldb/source/Plugins/Language/Rust/RustLanguage.h deleted file mode 100644 index bd073d8..0000000 --- a/src/llvm-project/lldb/source/Plugins/Language/Rust/RustLanguage.h +++ /dev/null
@@ -1,50 +0,0 @@ -//===-- RustLanguage.h ------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_RustLanguage_h_ -#define liblldb_RustLanguage_h_ - -// C Includes -// C++ Includes -#include <vector> - -// Other libraries and framework includes -#include "llvm/ADT/StringRef.h" - -// Project includes -#include "lldb/Target/Language.h" -#include "lldb/Utility/ConstString.h" -#include "lldb/lldb-private.h" - -namespace lldb_private { - -class RustLanguage : public Language { -public: - lldb::LanguageType GetLanguageType() const override { - return lldb::eLanguageTypeRust; - } - - static void Initialize(); - - static void Terminate(); - - static lldb_private::Language *CreateInstance(lldb::LanguageType language); - - static lldb_private::ConstString GetPluginNameStatic(); - - bool IsSourceFile(llvm::StringRef file_path) const override; - - ConstString GetPluginName() override; - - uint32_t GetPluginVersion() override; -}; - -} // namespace lldb_private - -#endif // liblldb_RustLanguage_h_
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CMakeLists.txt index 9b7036e..c627914 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CMakeLists.txt
@@ -1,4 +1,3 @@ add_subdirectory(CPlusPlus) add_subdirectory(ObjC) add_subdirectory(RenderScript) -add_subdirectory(Rust)
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CMakeLists.txt index 26c68c6..508a361 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CMakeLists.txt
@@ -1,2 +1,11 @@ +add_lldb_library(lldbPluginCPPRuntime PLUGIN + CPPLanguageRuntime.cpp + + LINK_LIBS + lldbCore + lldbSymbol + lldbTarget +) + add_subdirectory(ItaniumABI) #add_subdirectory(MicrosoftABI)
diff --git a/src/llvm-project/lldb/source/Target/CPPLanguageRuntime.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp similarity index 90% rename from src/llvm-project/lldb/source/Target/CPPLanguageRuntime.cpp rename to src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp index f0bd175..b392282 100644 --- a/src/llvm-project/lldb/source/Target/CPPLanguageRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
@@ -1,20 +1,21 @@ //===-- CPPLanguageRuntime.cpp -//-------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/CPPLanguageRuntime.h" - #include <string.h> +#include <memory> + +#include "CPPLanguageRuntime.h" + #include "llvm/ADT/StringRef.h" #include "lldb/Symbol/Block.h" +#include "lldb/Symbol/Variable.h" #include "lldb/Symbol/VariableList.h" #include "lldb/Core/PluginManager.h" @@ -31,14 +32,20 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- +static ConstString g_this = ConstString("this"); + +char CPPLanguageRuntime::ID = 0; + // Destructor -//---------------------------------------------------------------------- CPPLanguageRuntime::~CPPLanguageRuntime() {} CPPLanguageRuntime::CPPLanguageRuntime(Process *process) : LanguageRuntime(process) {} +bool CPPLanguageRuntime::IsWhitelistedRuntimeValue(ConstString name) { + return name == g_this; +} + bool CPPLanguageRuntime::GetObjectDescription(Stream &str, ValueObject &object) { // C++ has no generic way to do this. @@ -169,7 +176,7 @@ // // This covers the case of the lambda known at compile time. size_t first_open_angle_bracket = vtable_name.find('<') + 1; - size_t first_comma = vtable_name.find_first_of(','); + size_t first_comma = vtable_name.find(','); llvm::StringRef first_template_parameter = vtable_name.slice(first_open_angle_bracket, first_comma); @@ -196,7 +203,7 @@ return llvm::Regex::escape(first_template_parameter.str()) + R"(::operator\(\)\(.*\))"; - if (symbol != NULL && + if (symbol != nullptr && symbol->GetName().GetStringRef().contains("__invoke")) { llvm::StringRef symbol_name = symbol->GetName().GetStringRef(); @@ -223,8 +230,8 @@ SymbolContextList scl; - target.GetImages().FindFunctions(RegularExpression{func_to_match}, true, true, - true, scl); + target.GetImages().FindSymbolsMatchingRegExAndType( + RegularExpression{R"(^)" + func_to_match}, eSymbolTypeAny, scl, true); // Case 1,2 or 3 if (scl.GetSize() >= 1) { @@ -260,7 +267,7 @@ } // Case 4 or 5 - if (!symbol->GetName().GetStringRef().startswith("vtable for")) { + if (symbol && !symbol->GetName().GetStringRef().startswith("vtable for")) { optional_info.callable_case = LibCppStdFunctionCallableCase::FreeOrMemberFunction; optional_info.callable_address = function_address_resolved; @@ -319,7 +326,7 @@ StackFrameSP frame = thread.GetStackFrameAtIndex(0); if (frame) { - ValueObjectSP value_sp = frame->FindVariable(ConstString("this")); + ValueObjectSP value_sp = frame->FindVariable(g_this); CPPLanguageRuntime::LibCppStdFunctionCallableInfo callable_info = FindLibCppStdFunctionCallableInfo(value_sp); @@ -328,16 +335,16 @@ value_sp->GetValueIsValid()) { // We found the std::function wrapped callable and we have its address. // We now create a ThreadPlan to run to the callable. - ret_plan_sp.reset(new ThreadPlanRunToAddress( - thread, callable_info.callable_address, stop_others)); + ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>( + thread, callable_info.callable_address, stop_others); return ret_plan_sp; } else { // We are in std::function but we could not obtain the callable. // We create a ThreadPlan to keep stepping through using the address range // of the current function. - ret_plan_sp.reset(new ThreadPlanStepInRange(thread, range_of_curr_func, - sc, eOnlyThisThread, - eLazyBoolYes, eLazyBoolYes)); + ret_plan_sp = std::make_shared<ThreadPlanStepInRange>( + thread, range_of_curr_func, sc, eOnlyThisThread, eLazyBoolYes, + eLazyBoolYes); return ret_plan_sp; } }
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h new file mode 100644 index 0000000..2852636 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
@@ -0,0 +1,90 @@ +//===-- CPPLanguageRuntime.h +// +// 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 liblldb_CPPLanguageRuntime_h_ +#define liblldb_CPPLanguageRuntime_h_ + +#include <vector> +#include "lldb/Core/PluginInterface.h" +#include "lldb/Target/LanguageRuntime.h" +#include "lldb/lldb-private.h" + +namespace lldb_private { + +class CPPLanguageRuntime : public LanguageRuntime { +public: + enum class LibCppStdFunctionCallableCase { + Lambda = 0, + CallableObject, + FreeOrMemberFunction, + Invalid + }; + + struct LibCppStdFunctionCallableInfo { + Symbol callable_symbol; + Address callable_address; + LineEntry callable_line_entry; + lldb::addr_t member__f_pointer_value = 0u; + LibCppStdFunctionCallableCase callable_case = + LibCppStdFunctionCallableCase::Invalid; + }; + + LibCppStdFunctionCallableInfo + FindLibCppStdFunctionCallableInfo(lldb::ValueObjectSP &valobj_sp); + + ~CPPLanguageRuntime() override; + + static char ID; + + bool isA(const void *ClassID) const override { + return ClassID == &ID || LanguageRuntime::isA(ClassID); + } + + static bool classof(const LanguageRuntime *runtime) { + return runtime->isA(&ID); + } + + lldb::LanguageType GetLanguageType() const override { + return lldb::eLanguageTypeC_plus_plus; + } + + static CPPLanguageRuntime *Get(Process &process) { + return llvm::cast_or_null<CPPLanguageRuntime>( + process.GetLanguageRuntime(lldb::eLanguageTypeC_plus_plus)); + } + + bool GetObjectDescription(Stream &str, ValueObject &object) override; + + bool GetObjectDescription(Stream &str, Value &value, + ExecutionContextScope *exe_scope) override; + + /// Obtain a ThreadPlan to get us into C++ constructs such as std::function. + /// + /// \param[in] thread + /// Curent thrad of execution. + /// + /// \param[in] stop_others + /// True if other threads should pause during execution. + /// + /// \return + /// A ThreadPlan Shared pointer + lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread, + bool stop_others) override; + + bool IsWhitelistedRuntimeValue(ConstString name) override; +protected: + // Classes that inherit from CPPLanguageRuntime can see and modify these + CPPLanguageRuntime(Process *process); + +private: + DISALLOW_COPY_AND_ASSIGN(CPPLanguageRuntime); +}; + +} // namespace lldb_private + +#endif // liblldb_CPPLanguageRuntime_h_
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/CMakeLists.txt index 14d1f46..52c297d 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/CMakeLists.txt
@@ -7,4 +7,5 @@ lldbInterpreter lldbSymbol lldbTarget + lldbPluginCPPRuntime )
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp index 49a3d40..41f38a4 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp
@@ -1,10 +1,9 @@ //===-- ItaniumABILanguageRuntime.cpp --------------------------------------*- //C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -44,10 +43,12 @@ static const char *vtable_demangled_prefix = "vtable for "; +char ItaniumABILanguageRuntime::ID = 0; + bool ItaniumABILanguageRuntime::CouldHaveDynamicValue(ValueObject &in_value) { const bool check_cxx = true; const bool check_objc = false; - return in_value.GetCompilerType().IsPossibleDynamicType(NULL, check_cxx, + return in_value.GetCompilerType().IsPossibleDynamicType(nullptr, check_cxx, check_objc); } @@ -70,7 +71,7 @@ target.GetImages().ResolveSymbolContextForAddress( vtable_addr, eSymbolContextSymbol, sc); Symbol *symbol = sc.symbol; - if (symbol != NULL) { + if (symbol != nullptr) { const char *name = symbol->GetMangled() .GetDemangledName(lldb::eLanguageTypeC_plus_plus) @@ -236,16 +237,15 @@ if (!class_type_or_name) return false; - TypeSP type_sp = class_type_or_name.GetTypeSP(); + CompilerType type = class_type_or_name.GetCompilerType(); // There can only be one type with a given name, so we've just found // duplicate definitions, and this one will do as well as any other. We // don't consider something to have a dynamic type if it is the same as // the static type. So compare against the value we were handed. - if (!type_sp) + if (!type) return true; - if (ClangASTContext::AreTypesSame(in_value.GetCompilerType(), - type_sp->GetForwardCompilerType())) { + if (ClangASTContext::AreTypesSame(in_value.GetCompilerType(), type)) { // The dynamic type we found was the same type, so we don't have a // dynamic type here... return false; @@ -307,17 +307,7 @@ return ret; } -bool ItaniumABILanguageRuntime::IsVTableName(const char *name) { - if (name == NULL) - return false; - - // Can we maybe ask Clang about this? - return strstr(name, "_vptr$") == name; -} - -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ LanguageRuntime * ItaniumABILanguageRuntime::CreateInstance(Process *process, lldb::LanguageType language) { @@ -330,7 +320,7 @@ language == eLanguageTypeC_plus_plus_14) return new ItaniumABILanguageRuntime(process); else - return NULL; + return nullptr; } class CommandObjectMultiwordItaniumABI_Demangle : public CommandObjectParsed { @@ -429,9 +419,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ItaniumABILanguageRuntime::GetPluginName() { return GetPluginNameStatic(); } @@ -479,16 +467,14 @@ lldb::SearchFilterSP ItaniumABILanguageRuntime::CreateExceptionSearchFilter() { Target &target = m_process->GetTarget(); + FileSpecList filter_modules; if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) { // Limit the number of modules that are searched for these breakpoints for // Apple binaries. - FileSpecList filter_modules; filter_modules.Append(FileSpec("libc++abi.dylib")); filter_modules.Append(FileSpec("libSystem.B.dylib")); - return target.GetSearchFilterForModuleList(&filter_modules); - } else { - return LanguageRuntime::CreateExceptionSearchFilter(); } + return target.GetSearchFilterForModuleList(&filter_modules); } lldb::BreakpointSP ItaniumABILanguageRuntime::CreateExceptionBreakpoint( @@ -496,7 +482,7 @@ Target &target = m_process->GetTarget(); FileSpecList filter_modules; BreakpointResolverSP exception_resolver_sp = - CreateExceptionResolver(NULL, catch_bp, throw_bp, for_expressions); + CreateExceptionResolver(nullptr, catch_bp, throw_bp, for_expressions); SearchFilterSP filter_sp(CreateExceptionSearchFilter()); const bool hardware = false; const bool resolve_indirect_functions = false; @@ -569,7 +555,7 @@ options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetStopOthers(true); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(m_process->GetUtilityExpressionTimeout()); options.SetTryAllThreads(false); thread_sp->CalculateExecutionContext(exe_ctx); @@ -600,6 +586,10 @@ addr_t exception_addr = m_process->ReadPointerFromMemory(result_ptr - ptr_size, error); + if (!error.Success()) { + return ValueObjectSP(); + } + lldb_private::formatters::InferiorSizedWord exception_isw(exception_addr, *m_process); ValueObjectSP exception = ValueObject::CreateValueObjectFromData(
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h index abed370..97cc81b 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h
@@ -1,9 +1,8 @@ //===-- ItaniumABILanguageRuntime.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,19 +16,18 @@ #include "lldb/Breakpoint/BreakpointResolver.h" #include "lldb/Core/Value.h" #include "lldb/Symbol/Type.h" -#include "lldb/Target/CPPLanguageRuntime.h" #include "lldb/Target/LanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h" + namespace lldb_private { class ItaniumABILanguageRuntime : public lldb_private::CPPLanguageRuntime { public: ~ItaniumABILanguageRuntime() override = default; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -39,7 +37,15 @@ static lldb_private::ConstString GetPluginNameStatic(); - bool IsVTableName(const char *name) override; + static char ID; + + bool isA(const void *ClassID) const override { + return ClassID == &ID || CPPLanguageRuntime::isA(ClassID); + } + + static bool classof(const LanguageRuntime *runtime) { + return runtime->isA(&ID); + } bool GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic, @@ -69,9 +75,7 @@ lldb::ValueObjectSP GetExceptionObjectForThread( lldb::ThreadSP thread_sp) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -91,9 +95,8 @@ ItaniumABILanguageRuntime(Process *process) : // Call CreateInstance instead. - lldb_private::CPPLanguageRuntime(process), - m_cxx_exception_bp_sp(), m_dynamic_type_map(), - m_dynamic_type_map_mutex() {} + lldb_private::CPPLanguageRuntime(process), m_cxx_exception_bp_sp(), + m_dynamic_type_map(), m_dynamic_type_map_mutex() {} lldb::BreakpointSP m_cxx_exception_bp_sp; DynamicTypeCache m_dynamic_type_map;
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp index 679c3c8..93aa07f 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp
@@ -1,10 +1,9 @@ //===-- AppleObjCClassDescriptorV2.cpp -----------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -335,9 +334,9 @@ std::unique_ptr<class_rw_t> class_rw; if (!Read_objc_class(process, objc_class)) - return 0; + return false; if (!Read_class_row(process, *objc_class, class_ro, class_rw)) - return 0; + return false; static ConstString NSObject_name("NSObject");
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h index 308ff14..b8ba9db 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h
@@ -1,9 +1,8 @@ //===-- AppleObjCClassDescriptorV2.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,10 @@ #include <mutex> #include "AppleObjCRuntimeV2.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + namespace lldb_private { class ClassDescriptorV2 : public ObjCLanguageRuntime::ClassDescriptor {
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp index 4fc340b..18f2a18 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp
@@ -1,19 +1,18 @@ //===-- AppleObjCDeclVendor.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "AppleObjCDeclVendor.h" #include "Plugins/ExpressionParser/Clang/ASTDumper.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" #include "lldb/Core/Module.h" #include "lldb/Symbol/ClangExternalASTSourceCommon.h" #include "lldb/Symbol/ClangUtil.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/Log.h" @@ -21,6 +20,7 @@ #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" + using namespace lldb_private; class lldb_private::AppleObjCExternalASTSource @@ -63,7 +63,7 @@ non_const_interface_decl->lookup(name); return (result.size() != 0); - } while (0); + } while (false); SetNoExternalVisibleDeclsForName(decl_ctx, name); return false; @@ -174,9 +174,9 @@ m_runtime.GetClassDescriptorFromISA(isa); if (!descriptor) - return NULL; + return nullptr; - const ConstString &name(descriptor->GetClassName()); + ConstString name(descriptor->GetClassName()); clang::IdentifierInfo &identifier_info = ast_ctx->Idents.get(name.GetStringRef()); @@ -204,12 +204,12 @@ ObjCRuntimeMethodType(const char *types) : m_is_valid(false) { const char *cursor = types; enum ParserState { Start = 0, InType, InPos } state = Start; - const char *type = NULL; + const char *type = nullptr; int brace_depth = 0; uint32_t stepsLeft = 256; - while (1) { + while (true) { if (--stepsLeft == 0) { m_is_valid = false; return; @@ -262,7 +262,7 @@ m_is_valid = false; return; } - type = NULL; + type = nullptr; } else { ++cursor; } @@ -320,7 +320,7 @@ bool instance, ObjCLanguageRuntime::EncodingToTypeSP type_realizer_sp) { if (!m_is_valid || m_type_vector.size() < 3) - return NULL; + return nullptr; clang::ASTContext &ast_ctx(interface_decl->getASTContext()); @@ -355,7 +355,7 @@ clang::IdentifierInfo **identifier_infos = selector_components.data(); if (!identifier_infos) { - return NULL; + return nullptr; } clang::Selector sel = ast_ctx.Selectors.getSelector( @@ -368,12 +368,13 @@ for_expression)); if (ret_type.isNull()) - return NULL; + return nullptr; clang::ObjCMethodDecl *ret = clang::ObjCMethodDecl::Create( ast_ctx, clang::SourceLocation(), clang::SourceLocation(), sel, - ret_type, NULL, interface_decl, isInstance, isVariadic, isSynthesized, - isImplicitlyDeclared, isDefined, impControl, HasRelatedResultType); + ret_type, nullptr, interface_decl, isInstance, isVariadic, + isSynthesized, isImplicitlyDeclared, isDefined, impControl, + HasRelatedResultType); std::vector<clang::ParmVarDecl *> parm_vars; @@ -384,12 +385,12 @@ ast_ctx, m_type_vector[ai].c_str(), for_expression)); if (arg_type.isNull()) - return NULL; // well, we just wasted a bunch of time. Wish we could - // delete the stuff we'd just made! + return nullptr; // well, we just wasted a bunch of time. Wish we could + // delete the stuff we'd just made! parm_vars.push_back(clang::ParmVarDecl::Create( - ast_ctx, ret, clang::SourceLocation(), clang::SourceLocation(), NULL, - arg_type, NULL, clang::SC_None, NULL)); + ast_ctx, ret, clang::SourceLocation(), clang::SourceLocation(), + nullptr, arg_type, nullptr, clang::SC_None, nullptr)); } ret->setMethodParams(ast_ctx, @@ -513,7 +514,7 @@ clang::SourceLocation(), &m_ast_ctx.getASTContext()->Idents.get(name), ClangUtil::GetQualType(ivar_type), type_source_info, // TypeSourceInfo * - clang::ObjCIvarDecl::Public, 0, is_synthesized); + clang::ObjCIvarDecl::Public, nullptr, is_synthesized); if (ivar_decl) { interface_decl->addDecl(ivar_decl); @@ -548,7 +549,7 @@ } uint32_t -AppleObjCDeclVendor::FindDecls(const ConstString &name, bool append, +AppleObjCDeclVendor::FindDecls(ConstString name, bool append, uint32_t max_matches, std::vector<clang::NamedDecl *> &decls) { static unsigned int invocation_id = 0; @@ -647,7 +648,7 @@ decls.push_back(iface_decl); ret++; break; - } while (0); + } while (false); return ret; }
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.h index 7f5c0bf..77b30b7 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.h
@@ -1,9 +1,8 @@ //===-- AppleObjCDeclVendor.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,9 +11,10 @@ #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/DeclVendor.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + namespace lldb_private { class AppleObjCExternalASTSource; @@ -23,7 +23,7 @@ public: AppleObjCDeclVendor(ObjCLanguageRuntime &runtime); - uint32_t FindDecls(const ConstString &name, bool append, uint32_t max_matches, + uint32_t FindDecls(ConstString name, bool append, uint32_t max_matches, std::vector<clang::NamedDecl *> &decls) override; clang::ExternalASTMerger::ImporterSource GetImporterSource() override;
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp index ed47b48..52ed362 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp
@@ -1,10 +1,9 @@ //===-- AppleObjCRuntime.cpp -------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,7 +24,6 @@ #include "lldb/Expression/FunctionCaller.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/ObjectFile.h" -#include "lldb/Target/CPPLanguageRuntime.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" @@ -40,19 +38,20 @@ #include "Plugins/Process/Utility/HistoryThread.h" #include "Plugins/Language/ObjC/NSString.h" +#include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h" #include <vector> using namespace lldb; using namespace lldb_private; -static constexpr std::chrono::seconds g_po_function_timeout(15); +char AppleObjCRuntime::ID = 0; AppleObjCRuntime::~AppleObjCRuntime() {} AppleObjCRuntime::AppleObjCRuntime(Process *process) : ObjCLanguageRuntime(process), m_read_objc_library(false), - m_objc_trampoline_handler_ap(), m_Foundation_major() { + m_objc_trampoline_handler_up(), m_Foundation_major() { ReadObjCLibraryIfNeeded(process->GetTarget().GetImages()); } @@ -131,9 +130,9 @@ // ret.SetContext(Value::eContextTypeClangType, return_compiler_type); ret.SetCompilerType(return_compiler_type); - if (exe_ctx.GetFramePtr() == NULL) { + if (exe_ctx.GetFramePtr() == nullptr) { Thread *thread = exe_ctx.GetThreadPtr(); - if (thread == NULL) { + if (thread == nullptr) { exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread()); thread = exe_ctx.GetThreadPtr(); } @@ -172,7 +171,7 @@ options.SetTryAllThreads(true); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); - options.SetTimeout(g_po_function_timeout); + options.SetTimeout(process->GetUtilityExpressionTimeout()); options.SetIsForUtilityExpr(true); ExpressionResults results = m_print_object_caller_up->ExecuteFunction( @@ -218,7 +217,7 @@ } Address *AppleObjCRuntime::GetPrintForDebuggerAddr() { - if (!m_PrintForDebugger_addr.get()) { + if (!m_PrintForDebugger_addr) { const ModuleList &modules = m_process->GetTarget().GetImages(); SymbolContextList contexts; @@ -228,7 +227,7 @@ eSymbolTypeCode, contexts)) && (!modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"), eSymbolTypeCode, contexts))) - return NULL; + return nullptr; contexts.GetContextAtIndex(0, context); @@ -240,7 +239,7 @@ bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) { return in_value.GetCompilerType().IsPossibleDynamicType( - NULL, + nullptr, false, // do not check C++ true); // check ObjC } @@ -328,9 +327,9 @@ // Maybe check here and if we have a handler already, and the UUID of this // module is the same as the one in the current module, then we don't have to // reread it? - m_objc_trampoline_handler_ap.reset( + m_objc_trampoline_handler_up.reset( new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp)); - if (m_objc_trampoline_handler_ap.get() != NULL) { + if (m_objc_trampoline_handler_up != nullptr) { m_read_objc_library = true; return true; } else @@ -340,15 +339,13 @@ ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread, bool stop_others) { ThreadPlanSP thread_plan_sp; - if (m_objc_trampoline_handler_ap.get()) - thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan( + if (m_objc_trampoline_handler_up) + thread_plan_sp = m_objc_trampoline_handler_up->GetStepThroughDispatchPlan( thread, stop_others); return thread_plan_sp; } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ ObjCLanguageRuntime::ObjCRuntimeVersions AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) { if (!process) @@ -456,28 +453,27 @@ lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() { Target &target = m_process->GetTarget(); + FileSpecList filter_modules; if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) { - FileSpecList filter_modules; filter_modules.Append(std::get<0>(GetExceptionThrowLocation())); - return target.GetSearchFilterForModuleList(&filter_modules); - } else { - return LanguageRuntime::CreateExceptionSearchFilter(); } + return target.GetSearchFilterForModuleList(&filter_modules); } ValueObjectSP AppleObjCRuntime::GetExceptionObjectForThread( ThreadSP thread_sp) { - auto cpp_runtime = m_process->GetCPPLanguageRuntime(); + auto *cpp_runtime = m_process->GetLanguageRuntime(eLanguageTypeC_plus_plus); if (!cpp_runtime) return ValueObjectSP(); auto cpp_exception = cpp_runtime->GetExceptionObjectForThread(thread_sp); if (!cpp_exception) return ValueObjectSP(); - - auto descriptor = GetClassDescriptor(*cpp_exception.get()); + + auto descriptor = GetClassDescriptor(*cpp_exception); if (!descriptor || !descriptor->IsValid()) return ValueObjectSP(); while (descriptor) { ConstString class_name(descriptor->GetClassName()); - if (class_name == ConstString("NSException")) return cpp_exception; + if (class_name == "NSException") + return cpp_exception; descriptor = descriptor->GetSuperclass(); } @@ -556,7 +552,7 @@ if (pcs.empty()) return ThreadSP(); - ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs, 0, false)); + ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs)); m_process->GetExtendedThreadList().AddThread(new_thread_sp); return new_thread_sp; }
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h index 8660646..79ac53e 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h
@@ -1,9 +1,8 @@ //===-- AppleObjCRuntime.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,30 +14,29 @@ #include "AppleObjCTrampolineHandler.h" #include "AppleThreadPlanStepThroughObjCTrampoline.h" #include "lldb/Target/LanguageRuntime.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + namespace lldb_private { class AppleObjCRuntime : public lldb_private::ObjCLanguageRuntime { public: ~AppleObjCRuntime() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ // Note there is no CreateInstance, Initialize & Terminate functions here, // because // you can't make an instance of this generic runtime. - static bool classof(const ObjCLanguageRuntime *runtime) { - switch (runtime->GetRuntimeVersion()) { - case ObjCRuntimeVersions::eAppleObjC_V1: - case ObjCRuntimeVersions::eAppleObjC_V2: - return true; - default: - return false; - } + static char ID; + + bool isA(const void *ClassID) const override { + return ClassID == &ID || ObjCLanguageRuntime::isA(ClassID); + } + + static bool classof(const LanguageRuntime *runtime) { + return runtime->isA(&ID); } // These are generic runtime functions: @@ -120,7 +118,7 @@ std::unique_ptr<Address> m_PrintForDebugger_addr; bool m_read_objc_library; std::unique_ptr<lldb_private::AppleObjCTrampolineHandler> - m_objc_trampoline_handler_ap; + m_objc_trampoline_handler_up; lldb::BreakpointSP m_objc_exception_bp_sp; lldb::ModuleWP m_objc_module_wp; std::unique_ptr<FunctionCaller> m_print_object_caller_up;
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp index 1cfc7a1..c8884fd 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp
@@ -1,10 +1,9 @@ //===-- AppleObjCRuntimeV1.cpp --------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,11 +31,14 @@ #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" +#include <memory> #include <vector> using namespace lldb; using namespace lldb_private; +char AppleObjCRuntimeV1::ID = 0; + AppleObjCRuntimeV1::AppleObjCRuntimeV1(Process *process) : AppleObjCRuntime(process), m_hash_signature(), m_isa_hash_table_ptr(LLDB_INVALID_ADDRESS) {} @@ -61,9 +63,7 @@ return !class_type_or_name.IsEmpty(); } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ lldb_private::LanguageRuntime * AppleObjCRuntimeV1::CreateInstance(Process *process, lldb::LanguageType language) { @@ -77,15 +77,16 @@ ObjCRuntimeVersions::eAppleObjC_V1) return new AppleObjCRuntimeV1(process); else - return NULL; + return nullptr; } else - return NULL; + return nullptr; } void AppleObjCRuntimeV1::Initialize() { PluginManager::RegisterPlugin( GetPluginNameStatic(), "Apple Objective-C Language Runtime - Version 1", - CreateInstance); + CreateInstance, + /*command_callback = */ nullptr, GetBreakpointExceptionPrecondition); } void AppleObjCRuntimeV1::Terminate() { @@ -97,9 +98,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString AppleObjCRuntimeV1::GetPluginName() { return GetPluginNameStatic(); } @@ -112,10 +111,10 @@ BreakpointResolverSP resolver_sp; if (throw_bp) - resolver_sp.reset(new BreakpointResolverName( + resolver_sp = std::make_shared<BreakpointResolverName>( bkpt, std::get<1>(GetExceptionThrowLocation()).AsCString(), eFunctionNameTypeBase, eLanguageTypeUnknown, Breakpoint::Exact, 0, - eLazyBoolNo)); + eLazyBoolNo); // FIXME: don't do catch yet. return resolver_sp; }
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h index 442a3a1..6fdae63 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h
@@ -1,9 +1,8 @@ //===-- AppleObjCRuntimeV1.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,18 +10,17 @@ #define liblldb_AppleObjCRuntimeV1_h_ #include "AppleObjCRuntime.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + namespace lldb_private { class AppleObjCRuntimeV1 : public AppleObjCRuntime { public: ~AppleObjCRuntimeV1() override = default; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -32,13 +30,14 @@ static lldb_private::ConstString GetPluginNameStatic(); - static bool classof(const ObjCLanguageRuntime *runtime) { - switch (runtime->GetRuntimeVersion()) { - case ObjCRuntimeVersions::eAppleObjC_V1: - return true; - default: - return false; - } + static char ID; + + bool isA(const void *ClassID) const override { + return ClassID == &ID || AppleObjCRuntime::isA(ClassID); + } + + static bool classof(const LanguageRuntime *runtime) { + return runtime->isA(&ID); } lldb::addr_t GetTaggedPointerObfuscator(); @@ -100,9 +99,7 @@ UtilityFunction *CreateObjectChecker(const char *) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -148,7 +145,7 @@ HashTableSignature m_hash_signature; lldb::addr_t m_isa_hash_table_ptr; - std::unique_ptr<DeclVendor> m_decl_vendor_ap; + std::unique_ptr<DeclVendor> m_decl_vendor_up; private: AppleObjCRuntimeV1(Process *process);
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp index b6ed2fe..635eaff 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp
@@ -1,14 +1,14 @@ //===-- AppleObjCRuntimeV2.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <stdint.h> +#include <memory> #include <string> #include <vector> @@ -65,13 +65,14 @@ #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + #include <vector> using namespace lldb; using namespace lldb_private; -// 2 second timeout when running utility functions -static constexpr std::chrono::seconds g_utility_function_timeout(2); +char AppleObjCRuntimeV2::ID = 0; static const char *g_get_dynamic_class_info_name = "__lldb_apple_objc_v2_get_dynamic_class_info"; @@ -157,6 +158,16 @@ )"; +// We'll substitute in class_getName or class_getNameRaw depending +// on which is present. +static const char *g_shared_cache_class_name_funcptr = R"( +extern "C" +{ + const char *%s(void *objc_class); + const char *(*class_name_lookup_func)(void *) = %s; +} +)"; + static const char *g_get_shared_cache_class_info_name = "__lldb_apple_objc_v2_get_shared_cache_class_info"; // Testing using the new C++11 raw string literals. If this breaks GCC then we @@ -165,7 +176,6 @@ extern "C" { - const char *class_getName(void *objc_class); size_t strlen(const char *); char *strncpy (char * s1, const char * s2, size_t n); int printf(const char * format, ...); @@ -286,13 +296,24 @@ if (class_infos && idx < max_class_infos) { class_infos[idx].isa = (Class)((uint8_t *)clsopt + clsOffset); - const char *name = class_getName (class_infos[idx].isa); + const char *name = class_name_lookup_func (class_infos[idx].isa); DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name); // Hash the class name so we don't have to read it const char *s = name; uint32_t h = 5381; for (unsigned char c = *s; c; c = *++s) + { + // class_getName demangles swift names and the hash must + // be calculated on the mangled name. hash==0 means lldb + // will fetch the mangled name and compute the hash in + // ParseClassInfoArray. + if (c == '.') + { + h = 0; + break; + } h = ((h << 5) + h) + c; + } class_infos[idx].hash = h; } else @@ -318,13 +339,24 @@ if (class_infos && idx < max_class_infos) { class_infos[idx].isa = (Class)((uint8_t *)clsopt + clsOffset); - const char *name = class_getName (class_infos[idx].isa); + const char *name = class_name_lookup_func (class_infos[idx].isa); DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name); // Hash the class name so we don't have to read it const char *s = name; uint32_t h = 5381; for (unsigned char c = *s; c; c = *++s) + { + // class_getName demangles swift names and the hash must + // be calculated on the mangled name. hash==0 means lldb + // will fetch the mangled name and compute the hash in + // ParseClassInfoArray. + if (c == '.') + { + h = 0; + break; + } h = ((h << 5) + h) + c; + } class_infos[idx].hash = h; } ++idx; @@ -384,20 +416,20 @@ m_get_class_info_args(LLDB_INVALID_ADDRESS), m_get_class_info_args_mutex(), m_get_shared_cache_class_info_code(), m_get_shared_cache_class_info_args(LLDB_INVALID_ADDRESS), - m_get_shared_cache_class_info_args_mutex(), m_decl_vendor_ap(), + m_get_shared_cache_class_info_args_mutex(), m_decl_vendor_up(), m_tagged_pointer_obfuscator(LLDB_INVALID_ADDRESS), - m_isa_hash_table_ptr(LLDB_INVALID_ADDRESS), - m_hash_signature(), + m_isa_hash_table_ptr(LLDB_INVALID_ADDRESS), m_hash_signature(), m_has_object_getClass(false), m_loaded_objc_opt(false), - m_non_pointer_isa_cache_ap( + m_non_pointer_isa_cache_up( NonPointerISACache::CreateInstance(*this, objc_module_sp)), - m_tagged_pointer_vendor_ap( + m_tagged_pointer_vendor_up( TaggedPointerVendorV2::CreateInstance(*this, objc_module_sp)), m_encoding_to_type_sp(), m_noclasses_warning_emitted(false), m_CFBoolean_values() { static const ConstString g_gdb_object_getClass("gdb_object_getClass"); - m_has_object_getClass = (objc_module_sp->FindFirstSymbolWithNameAndType( - g_gdb_object_getClass, eSymbolTypeCode) != NULL); + m_has_object_getClass = + (objc_module_sp->FindFirstSymbolWithNameAndType( + g_gdb_object_getClass, eSymbolTypeCode) != nullptr); RegisterObjCExceptionRecognizer(); } @@ -406,7 +438,7 @@ TypeAndOrName &class_type_or_name, Address &address, Value::ValueType &value_type) { // We should never get here with a null process... - assert(m_process != NULL); + assert(m_process != nullptr); // The Runtime is attached to a particular process, you shouldn't pass in a // value from another process. Note, however, the process might be NULL (e.g. @@ -443,12 +475,10 @@ class_type_or_name.SetTypeSP(type_sp); } else { // try to go for a CompilerType at least - DeclVendor *vendor = GetDeclVendor(); - if (vendor) { - std::vector<clang::NamedDecl *> decls; - if (vendor->FindDecls(class_name, false, 1, decls) && decls.size()) - class_type_or_name.SetCompilerType( - ClangASTContext::GetTypeForDecl(decls[0])); + if (auto *vendor = GetDeclVendor()) { + auto types = vendor->FindTypes(class_name, /*max_matches*/ 1); + if (!types.empty()) + class_type_or_name.SetCompilerType(types.front()); } } } @@ -457,9 +487,7 @@ return !class_type_or_name.IsEmpty(); } -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ LanguageRuntime *AppleObjCRuntimeV2::CreateInstance(Process *process, LanguageType language) { // FIXME: This should be a MacOS or iOS process, and we need to look for the @@ -472,9 +500,9 @@ ObjCRuntimeVersions::eAppleObjC_V2) return new AppleObjCRuntimeV2(process, objc_module_sp); else - return NULL; + return nullptr; } else - return NULL; + return nullptr; } static constexpr OptionDefinition g_objc_classtable_dump_options[] = { @@ -572,7 +600,7 @@ } Process *process = m_exe_ctx.GetProcessPtr(); - ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime(); + ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process); if (objc_runtime) { auto iterators_pair = objc_runtime->GetDescriptorIteratorPair(); auto iterator = iterators_pair.first; @@ -674,7 +702,7 @@ Process *process = m_exe_ctx.GetProcessPtr(); ExecutionContext exe_ctx(process); - ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime(); + ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process); if (objc_runtime) { ObjCLanguageRuntime::TaggedPointerVendor *tagged_ptr_vendor = objc_runtime->GetTaggedPointerVendor(); @@ -777,7 +805,8 @@ CreateInstance, [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP { return CommandObjectSP(new CommandObjectMultiwordObjC(interpreter)); - }); + }, + GetBreakpointExceptionPrecondition); } void AppleObjCRuntimeV2::Terminate() { @@ -789,9 +818,7 @@ return g_name; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString AppleObjCRuntimeV2::GetPluginName() { return GetPluginNameStatic(); } @@ -804,10 +831,10 @@ BreakpointResolverSP resolver_sp; if (throw_bp) - resolver_sp.reset(new BreakpointResolverName( + resolver_sp = std::make_shared<BreakpointResolverName>( bkpt, std::get<1>(GetExceptionThrowLocation()).AsCString(), eFunctionNameTypeBase, eLanguageTypeUnknown, Breakpoint::Exact, 0, - eLazyBoolNo)); + eLazyBoolNo); // FIXME: We don't do catch breakpoints for ObjC yet. // Should there be some way for the runtime to specify what it can do in this // regard? @@ -872,20 +899,16 @@ const char *class_name = parent_ast_type.GetConstTypeName().AsCString(); if (class_name && class_name[0] && ivar_name && ivar_name[0]) { - //---------------------------------------------------------------------- // Make the objective C V2 mangled name for the ivar offset from the class // name and ivar name - //---------------------------------------------------------------------- std::string buffer("OBJC_IVAR_$_"); buffer.append(class_name); buffer.push_back('.'); buffer.append(ivar_name); ConstString ivar_const_str(buffer.c_str()); - //---------------------------------------------------------------------- // Try to get the ivar offset address from the symbol table first using the // name we created above - //---------------------------------------------------------------------- SymbolContextList sc_list; Target &target = m_process->GetTarget(); target.GetImages().FindSymbolsWithNameAndType(ivar_const_str, @@ -902,10 +925,8 @@ ivar_offset_symbol.symbol->GetLoadAddress(&target); } - //---------------------------------------------------------------------- // If we didn't get the ivar offset address from the symbol table, fall // back to getting it from the runtime - //---------------------------------------------------------------------- if (ivar_offset_address == LLDB_INVALID_ADDRESS) ivar_offset_address = LookupRuntimeSymbol(ivar_const_str); @@ -921,16 +942,16 @@ // computational effort as possible whether something could possibly be a // tagged pointer - false positives are possible but false negatives shouldn't bool AppleObjCRuntimeV2::IsTaggedPointer(addr_t ptr) { - if (!m_tagged_pointer_vendor_ap) + if (!m_tagged_pointer_vendor_up) return false; - return m_tagged_pointer_vendor_ap->IsPossibleTaggedPointer(ptr); + return m_tagged_pointer_vendor_up->IsPossibleTaggedPointer(ptr); } class RemoteNXMapTable { public: RemoteNXMapTable() : m_count(0), m_num_buckets_minus_one(0), - m_buckets_ptr(LLDB_INVALID_ADDRESS), m_process(NULL), + m_buckets_ptr(LLDB_INVALID_ADDRESS), m_process(nullptr), m_end_iterator(*this, -1), m_load_addr(LLDB_INVALID_ADDRESS), m_map_pair_size(0), m_invalid_key(0) {} @@ -1148,8 +1169,8 @@ ObjCLanguageRuntime::ClassDescriptorSP AppleObjCRuntimeV2::GetClassDescriptorFromISA(ObjCISA isa) { ObjCLanguageRuntime::ClassDescriptorSP class_descriptor_sp; - if (m_non_pointer_isa_cache_ap.get()) - class_descriptor_sp = m_non_pointer_isa_cache_ap->GetClassDescriptor(isa); + if (m_non_pointer_isa_cache_up) + class_descriptor_sp = m_non_pointer_isa_cache_up->GetClassDescriptor(isa); if (!class_descriptor_sp) class_descriptor_sp = ObjCLanguageRuntime::GetClassDescriptorFromISA(isa); return class_descriptor_sp; @@ -1176,7 +1197,7 @@ // tagged pointer if (IsTaggedPointer(isa_pointer)) { - return m_tagged_pointer_vendor_ap->GetClassDescriptor(isa_pointer); + return m_tagged_pointer_vendor_up->GetClassDescriptor(isa_pointer); } else { ExecutionContext exe_ctx(valobj.GetExecutionContextRef()); @@ -1265,7 +1286,7 @@ RemoteNXMapTable &hash_table) { Process *process = GetProcess(); - if (process == NULL) + if (process == nullptr) return DescriptorMapUpdateResult::Fail(); uint32_t num_class_infos = 0; @@ -1310,7 +1331,7 @@ ValueList arguments; FunctionCaller *get_class_info_function = nullptr; - if (!m_get_class_info_code.get()) { + if (!m_get_class_info_code) { Status error; m_get_class_info_code.reset(GetTargetRef().GetUtilityFunctionForLanguage( g_get_dynamic_class_info_body, eLanguageTypeObjC, @@ -1332,7 +1353,7 @@ m_get_class_info_code.reset(); } } - if (!m_get_class_info_code.get()) + if (!m_get_class_info_code) return DescriptorMapUpdateResult::Fail(); // Next make the runner function for our implementation utility function. @@ -1411,7 +1432,7 @@ options.SetTryAllThreads(false); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); - options.SetTimeout(g_utility_function_timeout); + options.SetTimeout(process->GetUtilityExpressionTimeout()); options.SetIsForUtilityExpr(true); Value return_value; @@ -1501,8 +1522,18 @@ } else { // Read the 32 bit hash for the class name const uint32_t name_hash = data.GetU32(&offset); - ClassDescriptorSP descriptor_sp(new ClassDescriptorV2(*this, isa, NULL)); - AddClass(isa, descriptor_sp, name_hash); + ClassDescriptorSP descriptor_sp( + new ClassDescriptorV2(*this, isa, nullptr)); + + // The code in g_get_shared_cache_class_info_body sets the value of the hash + // to 0 to signal a demangled symbol. We use class_getName() in that code to + // find the class name, but this returns a demangled name for Swift symbols. + // For those symbols, recompute the hash here by reading their name from the + // runtime. + if (name_hash) + AddClass(isa, descriptor_sp, name_hash); + else + AddClass(isa, descriptor_sp, descriptor_sp->GetClassName().AsCString(nullptr)); num_parsed++; if (should_log) log->Printf("AppleObjCRuntimeV2 added isa=0x%" PRIx64 @@ -1521,7 +1552,7 @@ AppleObjCRuntimeV2::UpdateISAToDescriptorMapSharedCache() { Process *process = GetProcess(); - if (process == NULL) + if (process == nullptr) return DescriptorMapUpdateResult::Fail(); Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_TYPES)); @@ -1565,11 +1596,54 @@ ValueList arguments; FunctionCaller *get_shared_cache_class_info_function = nullptr; - if (!m_get_shared_cache_class_info_code.get()) { + if (!m_get_shared_cache_class_info_code) { Status error; + + // If the inferior objc.dylib has the class_getNameRaw function, + // use that in our jitted expression. Else fall back to the old + // class_getName. + static ConstString g_class_getName_symbol_name("class_getName"); + static ConstString g_class_getNameRaw_symbol_name("class_getNameRaw"); + ConstString class_name_getter_function_name = g_class_getName_symbol_name; + + ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process); + if (objc_runtime) { + const ModuleList &images = process->GetTarget().GetImages(); + std::lock_guard<std::recursive_mutex> guard(images.GetMutex()); + for (size_t i = 0; i < images.GetSize(); ++i) { + lldb::ModuleSP mod_sp = images.GetModuleAtIndexUnlocked(i); + if (objc_runtime->IsModuleObjCLibrary(mod_sp)) { + const Symbol *symbol = + mod_sp->FindFirstSymbolWithNameAndType(g_class_getNameRaw_symbol_name, + lldb::eSymbolTypeCode); + if (symbol && + (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())) { + class_name_getter_function_name = g_class_getNameRaw_symbol_name; + } + } + } + } + + // Substitute in the correct class_getName / class_getNameRaw function name, + // concatenate the two parts of our expression text. The format string + // has two %s's, so provide the name twice. + int prefix_string_size = snprintf (nullptr, 0, + g_shared_cache_class_name_funcptr, + class_name_getter_function_name.AsCString(), + class_name_getter_function_name.AsCString()); + + char *class_name_func_ptr_expr = (char*) malloc (prefix_string_size + 1); + snprintf (class_name_func_ptr_expr, prefix_string_size + 1, + g_shared_cache_class_name_funcptr, + class_name_getter_function_name.AsCString(), + class_name_getter_function_name.AsCString()); + std::string shared_class_expression = class_name_func_ptr_expr; + shared_class_expression += g_get_shared_cache_class_info_body; + free (class_name_func_ptr_expr); + m_get_shared_cache_class_info_code.reset( GetTargetRef().GetUtilityFunctionForLanguage( - g_get_shared_cache_class_info_body, eLanguageTypeObjC, + shared_class_expression.c_str(), eLanguageTypeObjC, g_get_shared_cache_class_info_name, error)); if (error.Fail()) { if (log) @@ -1589,7 +1663,7 @@ } } - if (!m_get_shared_cache_class_info_code.get()) + if (!m_get_shared_cache_class_info_code) return DescriptorMapUpdateResult::Fail(); // Next make the function caller for our implementation utility function. @@ -1662,7 +1736,7 @@ options.SetTryAllThreads(false); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); - options.SetTimeout(g_utility_function_timeout); + options.SetTimeout(process->GetUtilityExpressionTimeout()); options.SetIsForUtilityExpr(true); Value return_value; @@ -1686,9 +1760,7 @@ if (log) log->Printf("Discovered %u ObjC classes in shared cache\n", num_class_infos); -#ifdef LLDB_CONFIGURATION_DEBUG assert(num_class_infos <= num_classes); -#endif if (num_class_infos > 0) { if (num_class_infos > num_classes) { num_class_infos = num_classes; @@ -1737,7 +1809,7 @@ Process *process = GetProcess(); - if (process == NULL) + if (process == nullptr) return false; uint32_t num_map_table_isas = 0; @@ -1946,13 +2018,13 @@ } DeclVendor *AppleObjCRuntimeV2::GetDeclVendor() { - if (!m_decl_vendor_ap.get()) - m_decl_vendor_ap.reset(new AppleObjCDeclVendor(*this)); + if (!m_decl_vendor_up) + m_decl_vendor_up.reset(new AppleObjCDeclVendor(*this)); - return m_decl_vendor_ap.get(); + return m_decl_vendor_up.get(); } -lldb::addr_t AppleObjCRuntimeV2::LookupRuntimeSymbol(const ConstString &name) { +lldb::addr_t AppleObjCRuntimeV2::LookupRuntimeSymbol(ConstString name) { lldb::addr_t ret = LLDB_INVALID_ADDRESS; const char *name_cstr = name.AsCString(); @@ -2022,18 +2094,18 @@ auto objc_debug_isa_magic_mask = ExtractRuntimeGlobalSymbol( process, ConstString("objc_debug_isa_magic_mask"), objc_module_sp, error); if (error.Fail()) - return NULL; + return nullptr; auto objc_debug_isa_magic_value = ExtractRuntimeGlobalSymbol( process, ConstString("objc_debug_isa_magic_value"), objc_module_sp, error); if (error.Fail()) - return NULL; + return nullptr; auto objc_debug_isa_class_mask = ExtractRuntimeGlobalSymbol( process, ConstString("objc_debug_isa_class_mask"), objc_module_sp, error); if (error.Fail()) - return NULL; + return nullptr; if (log) log->PutCString("AOCRT::NPI: Found all the non-indexed ISA masks"); @@ -2550,7 +2622,8 @@ ObjCLanguageRuntime::EncodingToTypeSP AppleObjCRuntimeV2::GetEncodingToType() { if (!m_encoding_to_type_sp) - m_encoding_to_type_sp.reset(new AppleObjCTypeEncodingParser(*this)); + m_encoding_to_type_sp = + std::make_shared<AppleObjCTypeEncodingParser>(*this); return m_encoding_to_type_sp; } @@ -2558,8 +2631,8 @@ AppleObjCRuntimeV2::GetPointerISA(ObjCISA isa) { ObjCISA ret = isa; - if (m_non_pointer_isa_cache_ap) - m_non_pointer_isa_cache_ap->EvaluateNonPointerISA(isa, ret); + if (m_non_pointer_isa_cache_up) + m_non_pointer_isa_cache_up->EvaluateNonPointerISA(isa, ret); return ret; } @@ -2629,6 +2702,8 @@ value.SetCompilerType(voidstar); exception = ValueObjectConstResult::Create(frame_sp.get(), value, ConstString("exception")); + exception = ValueObjectRecognizerSynthesizedValue::Create( + *exception, eValueTypeVariableArgument); exception = exception->GetDynamicValue(eDynamicDontRunTarget); m_arguments = ValueObjectListSP(new ValueObjectList()); @@ -2641,7 +2716,8 @@ }; class ObjCExceptionThrowFrameRecognizer : public StackFrameRecognizer { - lldb::RecognizedStackFrameSP RecognizeFrame(lldb::StackFrameSP frame) { + lldb::RecognizedStackFrameSP + RecognizeFrame(lldb::StackFrameSP frame) override { return lldb::RecognizedStackFrameSP( new ObjCExceptionRecognizedStackFrame(frame)); };
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h index aa91f85..a0fd39d 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h
@@ -1,9 +1,8 @@ //===-- AppleObjCRuntimeV2.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,10 @@ #include <mutex> #include "AppleObjCRuntime.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + class RemoteNXMapTable; namespace lldb_private { @@ -26,9 +26,7 @@ public: ~AppleObjCRuntimeV2() override = default; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -38,13 +36,14 @@ static lldb_private::ConstString GetPluginNameStatic(); - static bool classof(const ObjCLanguageRuntime *runtime) { - switch (runtime->GetRuntimeVersion()) { - case ObjCRuntimeVersions::eAppleObjC_V2: - return true; - default: - return false; - } + static char ID; + + bool isA(const void *ClassID) const override { + return ClassID == &ID || AppleObjCRuntime::isA(ClassID); + } + + static bool classof(const LanguageRuntime *runtime) { + return runtime->isA(&ID); } // These are generic runtime functions: @@ -56,9 +55,7 @@ UtilityFunction *CreateObjectChecker(const char *) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -80,14 +77,14 @@ DeclVendor *GetDeclVendor() override; - lldb::addr_t LookupRuntimeSymbol(const ConstString &name) override; + lldb::addr_t LookupRuntimeSymbol(ConstString name) override; EncodingToTypeSP GetEncodingToType() override; bool IsTaggedPointer(lldb::addr_t ptr) override; TaggedPointerVendor *GetTaggedPointerVendor() override { - return m_tagged_pointer_vendor_ap.get(); + return m_tagged_pointer_vendor_up.get(); } lldb::addr_t GetTaggedPointerObfuscator(); @@ -327,14 +324,14 @@ lldb::addr_t m_get_shared_cache_class_info_args; std::mutex m_get_shared_cache_class_info_args_mutex; - std::unique_ptr<DeclVendor> m_decl_vendor_ap; + std::unique_ptr<DeclVendor> m_decl_vendor_up; lldb::addr_t m_tagged_pointer_obfuscator; lldb::addr_t m_isa_hash_table_ptr; HashTableSignature m_hash_signature; bool m_has_object_getClass; bool m_loaded_objc_opt; - std::unique_ptr<NonPointerISACache> m_non_pointer_isa_cache_ap; - std::unique_ptr<TaggedPointerVendor> m_tagged_pointer_vendor_ap; + std::unique_ptr<NonPointerISACache> m_non_pointer_isa_cache_up; + std::unique_ptr<TaggedPointerVendor> m_tagged_pointer_vendor_up; EncodingToTypeSP m_encoding_to_type_sp; bool m_noclasses_warning_emitted; llvm::Optional<std::pair<lldb::addr_t, lldb::addr_t>> m_CFBoolean_values;
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp index e9182c5..b3eb09c 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp
@@ -1,15 +1,13 @@ //===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "AppleObjCTrampolineHandler.h" - #include "AppleThreadPlanStepThroughObjCTrampoline.h" #include "lldb/Breakpoint/StoppointCallbackContext.h" @@ -25,7 +23,6 @@ #include "lldb/Symbol/Symbol.h" #include "lldb/Target/ABI.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Target.h" @@ -37,6 +34,10 @@ #include "llvm/ADT/STLExtras.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -457,8 +458,9 @@ size_t num_modules = target_modules.GetSize(); if (!m_objc_module_sp) { for (size_t i = 0; i < num_modules; i++) { - if (process_sp->GetObjCLanguageRuntime()->IsModuleObjCLibrary( - target_modules.GetModuleAtIndexUnlocked(i))) { + if (ObjCLanguageRuntime::Get(*process_sp) + ->IsModuleObjCLibrary( + target_modules.GetModuleAtIndexUnlocked(i))) { m_objc_module_sp = target_modules.GetModuleAtIndexUnlocked(i); break; } @@ -470,7 +472,7 @@ const Symbol *trampoline_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name, eSymbolTypeData); - if (trampoline_symbol != NULL) { + if (trampoline_symbol != nullptr) { m_trampoline_header = trampoline_symbol->GetLoadAddress(&target); if (m_trampoline_header == LLDB_INVALID_ADDRESS) return false; @@ -480,7 +482,7 @@ const Symbol *changed_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name, eSymbolTypeCode); - if (changed_symbol != NULL) { + if (changed_symbol != nullptr) { const Address changed_symbol_addr = changed_symbol->GetAddress(); if (!changed_symbol_addr.IsValid()) return false; @@ -541,7 +543,7 @@ Status error; DataExtractor data; error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data, - 0, NULL); + 0, nullptr); lldb::offset_t offset = 0; lldb::addr_t region_addr = data.GetPointer(&offset); @@ -668,7 +670,7 @@ ConstString msg_forward_name("_objc_msgForward"); ConstString msg_forward_stret_name("_objc_msgForward_stret"); - Target *target = process_sp ? &process_sp->GetTarget() : NULL; + Target *target = process_sp ? &process_sp->GetTarget() : nullptr; const Symbol *class_getMethodImplementation = m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name, eSymbolTypeCode); @@ -748,9 +750,9 @@ } // Build our vtable dispatch handler here: - m_vtables_ap.reset(new AppleObjCVTables(process_sp, m_objc_module_sp)); - if (m_vtables_ap.get()) - m_vtables_ap->ReadRegions(); + m_vtables_up.reset(new AppleObjCVTables(process_sp, m_objc_module_sp)); + if (m_vtables_up) + m_vtables_up->ReadRegions(); } lldb::addr_t @@ -770,8 +772,8 @@ // First stage is to make the ClangUtility to hold our injected function: - if (!m_impl_code.get()) { - if (m_lookup_implementation_function_code != NULL) { + if (!m_impl_code) { + if (m_lookup_implementation_function_code != nullptr) { Status error; m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( m_lookup_implementation_function_code, eLanguageTypeObjC, @@ -864,8 +866,8 @@ if (!found_it) { uint32_t flags; - if (m_vtables_ap.get()) { - found_it = m_vtables_ap->IsAddressInVTables(curr_pc, flags); + if (m_vtables_up) { + found_it = m_vtables_up->IsAddressInVTables(curr_pc, flags); if (found_it) { this_dispatch.name = "vtable"; this_dispatch.stret_return = @@ -886,11 +888,11 @@ lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0); - const ABI *abi = NULL; + const ABI *abi = nullptr; ProcessSP process_sp(thread.CalculateProcess()); if (process_sp) abi = process_sp->GetABI().get(); - if (abi == NULL) + if (abi == nullptr) return ret_plan_sp; TargetSP target_sp(thread.CalculateTarget()); @@ -1036,8 +1038,8 @@ isa_addr, sel_addr); } ObjCLanguageRuntime *objc_runtime = - thread.GetProcess()->GetObjCLanguageRuntime(); - assert(objc_runtime != NULL); + ObjCLanguageRuntime::Get(*thread.GetProcess()); + assert(objc_runtime != nullptr); impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr); } @@ -1049,8 +1051,8 @@ log->Printf("Found implementation address in cache: 0x%" PRIx64, impl_addr); - ret_plan_sp.reset( - new ThreadPlanRunToAddress(thread, impl_addr, stop_others)); + ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr, + stop_others); } else { // We haven't seen this class/selector pair yet. Look it up. StreamString errors; @@ -1129,9 +1131,9 @@ // is not safe to run only one thread. So we override the // stop_others value passed in to us here: const bool trampoline_stop_others = false; - ret_plan_sp.reset(new AppleThreadPlanStepThroughObjCTrampoline( + ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>( thread, this, dispatch_values, isa_addr, sel_addr, - trampoline_stop_others)); + trampoline_stop_others); if (log) { StreamString s; ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.h index fe33907..d120d67 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.h
@@ -1,9 +1,8 @@ //===-- AppleObjCTrampolineHandler.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -37,7 +36,7 @@ struct DispatchFunction { public: - typedef enum { eFixUpNone, eFixUpFixed, eFixUpToFix } FixUpState; + enum FixUpState { eFixUpNone, eFixUpFixed, eFixUpToFix }; const char *name; bool stret_return; @@ -75,8 +74,9 @@ class VTableRegion { public: VTableRegion() - : m_valid(false), m_owner(NULL), m_header_addr(LLDB_INVALID_ADDRESS), - m_code_start_addr(0), m_code_end_addr(0), m_next_region(0) {} + : m_valid(false), m_owner(nullptr), + m_header_addr(LLDB_INVALID_ADDRESS), m_code_start_addr(0), + m_code_end_addr(0), m_next_region(0) {} VTableRegion(AppleObjCVTables *owner, lldb::addr_t header_addr); @@ -150,7 +150,7 @@ lldb::addr_t m_impl_stret_fn_addr; lldb::addr_t m_msg_forward_addr; lldb::addr_t m_msg_forward_stret_addr; - std::unique_ptr<AppleObjCVTables> m_vtables_ap; + std::unique_ptr<AppleObjCVTables> m_vtables_up; }; } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.cpp index 9bb1a4e..26654e9 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.cpp
@@ -1,9 +1,8 @@ //===-- AppleObjCTypeEncodingParser.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,8 +23,8 @@ AppleObjCTypeEncodingParser::AppleObjCTypeEncodingParser( ObjCLanguageRuntime &runtime) : ObjCLanguageRuntime::EncodingToType(), m_runtime(runtime) { - if (!m_scratch_ast_ctx_ap) - m_scratch_ast_ctx_ap.reset(new ClangASTContext(runtime.GetProcess() + if (!m_scratch_ast_ctx_up) + m_scratch_ast_ctx_up.reset(new ClangASTContext(runtime.GetProcess() ->GetTarget() .GetArchitecture() .GetTriple() @@ -246,25 +245,19 @@ if (!decl_vendor) return clang::QualType(); - const bool append = false; - const uint32_t max_matches = 1; - std::vector<clang::NamedDecl *> decls; - - uint32_t num_types = - decl_vendor->FindDecls(ConstString(name), append, max_matches, decls); + auto types = decl_vendor->FindTypes(ConstString(name), /*max_matches*/ 1); // The user can forward-declare something that has no definition. The runtime // doesn't prohibit this at all. This is a rare and very weird case. We keep // this assert in debug builds so we catch other weird cases. #ifdef LLDB_CONFIGURATION_DEBUG - assert(num_types); + assert(!types.empty()); #else - if (!num_types) + if (types.empty()) return ast_ctx.getObjCIdType(); #endif - return ClangUtil::GetQualType( - ClangASTContext::GetTypeForDecl(decls[0]).GetPointerType()); + return ClangUtil::GetQualType(types.front().GetPointerType()); } else { // We're going to resolve this dynamically anyway, so just smile and wave. return ast_ctx.getObjCIdType();
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.h index fac564e..e576e8f 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTypeEncodingParser.h
@@ -1,9 +1,8 @@ //===-- AppleObjCTypeEncodingParser.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,9 +11,10 @@ #include "clang/AST/ASTContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + namespace lldb_utility { class StringLexer; }
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp index 2b54d0a..d18435c 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp
@@ -1,32 +1,32 @@ //===-- AppleThreadPlanStepThroughObjCTrampoline.cpp -//--------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "AppleThreadPlanStepThroughObjCTrampoline.h" + #include "AppleObjCTrampolineHandler.h" #include "lldb/Expression/DiagnosticManager.h" #include "lldb/Expression/FunctionCaller.h" #include "lldb/Expression/UtilityFunction.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlanRunToAddress.h" #include "lldb/Target/ThreadPlanStepOut.h" #include "lldb/Utility/Log.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" + +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanStepThroughObjCTrampoline constructor -//---------------------------------------------------------------------- AppleThreadPlanStepThroughObjCTrampoline:: AppleThreadPlanStepThroughObjCTrampoline( Thread &thread, AppleObjCTrampolineHandler *trampoline_handler, @@ -37,12 +37,10 @@ eVoteNoOpinion), m_trampoline_handler(trampoline_handler), m_args_addr(LLDB_INVALID_ADDRESS), m_input_values(input_values), - m_isa_addr(isa_addr), m_sel_addr(sel_addr), m_impl_function(NULL), + m_isa_addr(isa_addr), m_sel_addr(sel_addr), m_impl_function(nullptr), m_stop_others(stop_others) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- AppleThreadPlanStepThroughObjCTrampoline:: ~AppleThreadPlanStepThroughObjCTrampoline() {} @@ -174,8 +172,8 @@ target_addr); ObjCLanguageRuntime *objc_runtime = - GetThread().GetProcess()->GetObjCLanguageRuntime(); - assert(objc_runtime != NULL); + ObjCLanguageRuntime::Get(*GetThread().GetProcess()); + assert(objc_runtime != nullptr); objc_runtime->AddToMethodCache(m_isa_addr, m_sel_addr, target_addr); if (log) log->Printf("Adding {isa-addr=0x%" PRIx64 ", sel-addr=0x%" PRIx64 @@ -184,8 +182,8 @@ // Extract the target address from the value: - m_run_to_sp.reset( - new ThreadPlanRunToAddress(m_thread, target_so_addr, m_stop_others)); + m_run_to_sp = std::make_shared<ThreadPlanRunToAddress>( + m_thread, target_so_addr, m_stop_others); m_thread.QueueThreadPlan(m_run_to_sp, false); m_run_to_sp->SetPrivate(true); return false;
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.h index 5758e19..96f3785 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.h
@@ -1,9 +1,8 @@ //===-- AppleThreadPlanStepThroughObjCTrampoline.h --------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/CMakeLists.txt index 18f3ae1..29d9ba1 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/CMakeLists.txt
@@ -19,6 +19,7 @@ lldbTarget lldbUtility lldbPluginExpressionParserClang + lldbPluginCPPRuntime LINK_COMPONENTS Support )
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/CMakeLists.txt index af13dc6..5b3ea2f 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/CMakeLists.txt
@@ -1 +1,10 @@ +add_lldb_library(lldbPluginObjCRuntime PLUGIN + ObjCLanguageRuntime.cpp + + LINK_LIBS + lldbCore + lldbSymbol + lldbTarget + lldbUtility +) add_subdirectory(AppleObjCRuntime)
diff --git a/src/llvm-project/lldb/source/Target/ObjCLanguageRuntime.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.cpp similarity index 84% rename from src/llvm-project/lldb/source/Target/ObjCLanguageRuntime.cpp rename to src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.cpp index 8627da9..631c15c 100644 --- a/src/llvm-project/lldb/source/Target/ObjCLanguageRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.cpp
@@ -1,13 +1,14 @@ //===-- ObjCLanguageRuntime.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "clang/AST/Type.h" +#include "ObjCLanguageRuntime.h" + #include "lldb/Core/MappedHash.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" @@ -17,7 +18,7 @@ #include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/Type.h" #include "lldb/Symbol/TypeList.h" -#include "lldb/Target/ObjCLanguageRuntime.h" +#include "lldb/Symbol/Variable.h" #include "lldb/Target/Target.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Timer.h" @@ -28,9 +29,9 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- +char ObjCLanguageRuntime::ID = 0; + // Destructor -//---------------------------------------------------------------------- ObjCLanguageRuntime::~ObjCLanguageRuntime() {} ObjCLanguageRuntime::ObjCLanguageRuntime(Process *process) @@ -40,6 +41,12 @@ m_isa_to_descriptor_stop_id(UINT32_MAX), m_complete_class_cache(), m_negative_complete_class_cache() {} +bool ObjCLanguageRuntime::IsWhitelistedRuntimeValue(ConstString name) { + static ConstString g_self = ConstString("self"); + static ConstString g_cmd = ConstString("_cmd"); + return name == g_self || name == g_cmd; +} + bool ObjCLanguageRuntime::AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp, const char *class_name) { @@ -154,7 +161,7 @@ } ObjCLanguageRuntime::ObjCISA -ObjCLanguageRuntime::GetISA(const ConstString &name) { +ObjCLanguageRuntime::GetISA(ConstString name) { ISAToDescriptorIterator pos = GetDescriptorIterator(name); if (pos != m_isa_to_descriptor.end()) return pos->first; @@ -162,7 +169,7 @@ } ObjCLanguageRuntime::ISAToDescriptorIterator -ObjCLanguageRuntime::GetDescriptorIterator(const ConstString &name) { +ObjCLanguageRuntime::GetDescriptorIterator(ConstString name) { ISAToDescriptorIterator end = m_isa_to_descriptor.end(); if (name) { @@ -227,7 +234,7 @@ ObjCLanguageRuntime::ClassDescriptorSP ObjCLanguageRuntime::GetClassDescriptorFromClassName( - const ConstString &class_name) { + ConstString class_name) { ISAToDescriptorIterator pos = GetDescriptorIterator(class_name); if (pos != m_isa_to_descriptor.end()) return pos->second; @@ -303,8 +310,8 @@ CompilerType ObjCLanguageRuntime::EncodingToType::RealizeType(const char *name, bool for_expression) { - if (m_scratch_ast_ctx_ap) - return RealizeType(*m_scratch_ast_ctx_ap, name, for_expression); + if (m_scratch_ast_ctx_up) + return RealizeType(*m_scratch_ast_ctx_up, name, for_expression); return CompilerType(); } @@ -356,9 +363,19 @@ return found; } -//------------------------------------------------------------------ +lldb::BreakpointPreconditionSP +ObjCLanguageRuntime::GetBreakpointExceptionPrecondition(LanguageType language, + bool throw_bp) { + if (language != eLanguageTypeObjC) + return lldb::BreakpointPreconditionSP(); + if (!throw_bp) + return lldb::BreakpointPreconditionSP(); + BreakpointPreconditionSP precondition_sp( + new ObjCLanguageRuntime::ObjCExceptionPrecondition()); + return precondition_sp; +} + // Exception breakpoint Precondition class for ObjC: -//------------------------------------------------------------------ void ObjCLanguageRuntime::ObjCExceptionPrecondition::AddClassName( const char *class_name) { m_class_names.insert(class_name); @@ -382,3 +399,38 @@ "The ObjC Exception breakpoint doesn't support extra options."); return error; } + +llvm::Optional<CompilerType> +ObjCLanguageRuntime::GetRuntimeType(CompilerType base_type) { + CompilerType class_type; + bool is_pointer_type = false; + + if (ClangASTContext::IsObjCObjectPointerType(base_type, &class_type)) + is_pointer_type = true; + else if (ClangASTContext::IsObjCObjectOrInterfaceType(base_type)) + class_type = base_type; + else + return llvm::None; + + if (!class_type) + return llvm::None; + + ConstString class_name(class_type.GetConstTypeName()); + if (!class_name) + return llvm::None; + + TypeSP complete_objc_class_type_sp = LookupInCompleteClassCache(class_name); + if (!complete_objc_class_type_sp) + return llvm::None; + + CompilerType complete_class( + complete_objc_class_type_sp->GetFullCompilerType()); + if (complete_class.GetCompleteType()) { + if (is_pointer_type) + return complete_class.GetPointerType(); + else + return complete_class; + } + + return llvm::None; +}
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h new file mode 100644 index 0000000..1925c78 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h
@@ -0,0 +1,429 @@ +//===-- ObjCLanguageRuntime.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 liblldb_ObjCLanguageRuntime_h_ +#define liblldb_ObjCLanguageRuntime_h_ + +#include <functional> +#include <map> +#include <memory> +#include <unordered_set> + +#include "llvm/Support/Casting.h" + +#include "lldb/Breakpoint/BreakpointPrecondition.h" +#include "lldb/Core/PluginInterface.h" +#include "lldb/Core/ThreadSafeDenseMap.h" +#include "lldb/Symbol/CompilerType.h" +#include "lldb/Symbol/Type.h" +#include "lldb/Target/LanguageRuntime.h" +#include "lldb/lldb-private.h" + +class CommandObjectObjC_ClassTable_Dump; + +namespace lldb_private { + +class UtilityFunction; + +class ObjCLanguageRuntime : public LanguageRuntime { +public: + enum class ObjCRuntimeVersions { + eObjC_VersionUnknown = 0, + eAppleObjC_V1 = 1, + eAppleObjC_V2 = 2 + }; + + typedef lldb::addr_t ObjCISA; + + class ClassDescriptor; + typedef std::shared_ptr<ClassDescriptor> ClassDescriptorSP; + + // the information that we want to support retrieving from an ObjC class this + // needs to be pure virtual since there are at least 2 different + // implementations of the runtime, and more might come + class ClassDescriptor { + public: + ClassDescriptor() + : m_is_kvo(eLazyBoolCalculate), m_is_cf(eLazyBoolCalculate), + m_type_wp() {} + + virtual ~ClassDescriptor() = default; + + virtual ConstString GetClassName() = 0; + + virtual ClassDescriptorSP GetSuperclass() = 0; + + virtual ClassDescriptorSP GetMetaclass() const = 0; + + // virtual if any implementation has some other version-specific rules but + // for the known v1/v2 this is all that needs to be done + virtual bool IsKVO() { + if (m_is_kvo == eLazyBoolCalculate) { + const char *class_name = GetClassName().AsCString(); + if (class_name && *class_name) + m_is_kvo = + (LazyBool)(strstr(class_name, "NSKVONotifying_") == class_name); + } + return (m_is_kvo == eLazyBoolYes); + } + + // virtual if any implementation has some other version-specific rules but + // for the known v1/v2 this is all that needs to be done + virtual bool IsCFType() { + if (m_is_cf == eLazyBoolCalculate) { + const char *class_name = GetClassName().AsCString(); + if (class_name && *class_name) + m_is_cf = (LazyBool)(strcmp(class_name, "__NSCFType") == 0 || + strcmp(class_name, "NSCFType") == 0); + } + return (m_is_cf == eLazyBoolYes); + } + + virtual bool IsValid() = 0; + + virtual bool GetTaggedPointerInfo(uint64_t *info_bits = nullptr, + uint64_t *value_bits = nullptr, + uint64_t *payload = nullptr) = 0; + + virtual uint64_t GetInstanceSize() = 0; + + // use to implement version-specific additional constraints on pointers + virtual bool CheckPointer(lldb::addr_t value, uint32_t ptr_size) const { + return true; + } + + virtual ObjCISA GetISA() = 0; + + // This should return true iff the interface could be completed + virtual bool + Describe(std::function<void(ObjCISA)> const &superclass_func, + std::function<bool(const char *, const char *)> const + &instance_method_func, + std::function<bool(const char *, const char *)> const + &class_method_func, + std::function<bool(const char *, const char *, lldb::addr_t, + uint64_t)> const &ivar_func) const { + return false; + } + + lldb::TypeSP GetType() { return m_type_wp.lock(); } + + void SetType(const lldb::TypeSP &type_sp) { m_type_wp = type_sp; } + + struct iVarDescriptor { + ConstString m_name; + CompilerType m_type; + uint64_t m_size; + int32_t m_offset; + }; + + virtual size_t GetNumIVars() { return 0; } + + virtual iVarDescriptor GetIVarAtIndex(size_t idx) { + return iVarDescriptor(); + } + + protected: + bool IsPointerValid(lldb::addr_t value, uint32_t ptr_size, + bool allow_NULLs = false, bool allow_tagged = false, + bool check_version_specific = false) const; + + private: + LazyBool m_is_kvo; + LazyBool m_is_cf; + lldb::TypeWP m_type_wp; + }; + + class EncodingToType { + public: + virtual ~EncodingToType(); + + virtual CompilerType RealizeType(ClangASTContext &ast_ctx, const char *name, + bool for_expression); + virtual CompilerType RealizeType(const char *name, bool for_expression); + + virtual CompilerType RealizeType(clang::ASTContext &ast_ctx, + const char *name, bool for_expression) = 0; + + protected: + std::unique_ptr<ClangASTContext> m_scratch_ast_ctx_up; + }; + + class ObjCExceptionPrecondition : public BreakpointPrecondition { + public: + ObjCExceptionPrecondition(); + + ~ObjCExceptionPrecondition() override = default; + + bool EvaluatePrecondition(StoppointCallbackContext &context) override; + void GetDescription(Stream &stream, lldb::DescriptionLevel level) override; + Status ConfigurePrecondition(Args &args) override; + + protected: + void AddClassName(const char *class_name); + + private: + std::unordered_set<std::string> m_class_names; + }; + + static lldb::BreakpointPreconditionSP + GetBreakpointExceptionPrecondition(lldb::LanguageType language, + bool throw_bp); + + class TaggedPointerVendor { + public: + virtual ~TaggedPointerVendor() = default; + + virtual bool IsPossibleTaggedPointer(lldb::addr_t ptr) = 0; + + virtual ObjCLanguageRuntime::ClassDescriptorSP + GetClassDescriptor(lldb::addr_t ptr) = 0; + + protected: + TaggedPointerVendor() = default; + + private: + DISALLOW_COPY_AND_ASSIGN(TaggedPointerVendor); + }; + + ~ObjCLanguageRuntime() override; + + static char ID; + + bool isA(const void *ClassID) const override { + return ClassID == &ID || LanguageRuntime::isA(ClassID); + } + + static bool classof(const LanguageRuntime *runtime) { + return runtime->isA(&ID); + } + + static ObjCLanguageRuntime *Get(Process &process) { + return llvm::cast_or_null<ObjCLanguageRuntime>( + process.GetLanguageRuntime(lldb::eLanguageTypeObjC)); + } + + virtual TaggedPointerVendor *GetTaggedPointerVendor() { return nullptr; } + + typedef std::shared_ptr<EncodingToType> EncodingToTypeSP; + + virtual EncodingToTypeSP GetEncodingToType(); + + virtual ClassDescriptorSP GetClassDescriptor(ValueObject &in_value); + + ClassDescriptorSP GetNonKVOClassDescriptor(ValueObject &in_value); + + virtual ClassDescriptorSP + GetClassDescriptorFromClassName(ConstString class_name); + + virtual ClassDescriptorSP GetClassDescriptorFromISA(ObjCISA isa); + + ClassDescriptorSP GetNonKVOClassDescriptor(ObjCISA isa); + + lldb::LanguageType GetLanguageType() const override { + return lldb::eLanguageTypeObjC; + } + + virtual bool IsModuleObjCLibrary(const lldb::ModuleSP &module_sp) = 0; + + virtual bool ReadObjCLibrary(const lldb::ModuleSP &module_sp) = 0; + + virtual bool HasReadObjCLibrary() = 0; + + lldb::addr_t LookupInMethodCache(lldb::addr_t class_addr, lldb::addr_t sel); + + void AddToMethodCache(lldb::addr_t class_addr, lldb::addr_t sel, + lldb::addr_t impl_addr); + + TypeAndOrName LookupInClassNameCache(lldb::addr_t class_addr); + + void AddToClassNameCache(lldb::addr_t class_addr, const char *name, + lldb::TypeSP type_sp); + + void AddToClassNameCache(lldb::addr_t class_addr, + const TypeAndOrName &class_or_type_name); + + lldb::TypeSP LookupInCompleteClassCache(ConstString &name); + + llvm::Optional<CompilerType> GetRuntimeType(CompilerType base_type) override; + + virtual UtilityFunction *CreateObjectChecker(const char *) = 0; + + virtual ObjCRuntimeVersions GetRuntimeVersion() const { + return ObjCRuntimeVersions::eObjC_VersionUnknown; + } + + bool IsValidISA(ObjCISA isa) { + UpdateISAToDescriptorMap(); + return m_isa_to_descriptor.count(isa) > 0; + } + + virtual void UpdateISAToDescriptorMapIfNeeded() = 0; + + void UpdateISAToDescriptorMap() { + if (m_process && m_process->GetStopID() != m_isa_to_descriptor_stop_id) { + UpdateISAToDescriptorMapIfNeeded(); + } + } + + virtual ObjCISA GetISA(ConstString name); + + virtual ConstString GetActualTypeName(ObjCISA isa); + + virtual ObjCISA GetParentClass(ObjCISA isa); + + // Finds the byte offset of the child_type ivar in parent_type. If it can't + // find the offset, returns LLDB_INVALID_IVAR_OFFSET. + + virtual size_t GetByteOffsetForIvar(CompilerType &parent_qual_type, + const char *ivar_name); + + bool HasNewLiteralsAndIndexing() { + if (m_has_new_literals_and_indexing == eLazyBoolCalculate) { + if (CalculateHasNewLiteralsAndIndexing()) + m_has_new_literals_and_indexing = eLazyBoolYes; + else + m_has_new_literals_and_indexing = eLazyBoolNo; + } + + return (m_has_new_literals_and_indexing == eLazyBoolYes); + } + + void SymbolsDidLoad(const ModuleList &module_list) override { + m_negative_complete_class_cache.clear(); + } + + bool GetTypeBitSize(const CompilerType &compiler_type, + uint64_t &size) override; + + /// Check whether the name is "self" or "_cmd" and should show up in + /// "frame variable". + bool IsWhitelistedRuntimeValue(ConstString name) override; + +protected: + // Classes that inherit from ObjCLanguageRuntime can see and modify these + ObjCLanguageRuntime(Process *process); + + virtual bool CalculateHasNewLiteralsAndIndexing() { return false; } + + bool ISAIsCached(ObjCISA isa) const { + return m_isa_to_descriptor.find(isa) != m_isa_to_descriptor.end(); + } + + bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp) { + if (isa != 0) { + m_isa_to_descriptor[isa] = descriptor_sp; + return true; + } + return false; + } + + bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp, + const char *class_name); + + bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp, + uint32_t class_name_hash) { + if (isa != 0) { + m_isa_to_descriptor[isa] = descriptor_sp; + m_hash_to_isa_map.insert(std::make_pair(class_name_hash, isa)); + return true; + } + return false; + } + +private: + // We keep a map of <Class,Selector>->Implementation so we don't have to call + // the resolver function over and over. + + // FIXME: We need to watch for the loading of Protocols, and flush the cache + // for any + // class that we see so changed. + + struct ClassAndSel { + ClassAndSel() { + sel_addr = LLDB_INVALID_ADDRESS; + class_addr = LLDB_INVALID_ADDRESS; + } + + ClassAndSel(lldb::addr_t in_sel_addr, lldb::addr_t in_class_addr) + : class_addr(in_class_addr), sel_addr(in_sel_addr) {} + + bool operator==(const ClassAndSel &rhs) { + if (class_addr == rhs.class_addr && sel_addr == rhs.sel_addr) + return true; + else + return false; + } + + bool operator<(const ClassAndSel &rhs) const { + if (class_addr < rhs.class_addr) + return true; + else if (class_addr > rhs.class_addr) + return false; + else { + if (sel_addr < rhs.sel_addr) + return true; + else + return false; + } + } + + lldb::addr_t class_addr; + lldb::addr_t sel_addr; + }; + + typedef std::map<ClassAndSel, lldb::addr_t> MsgImplMap; + typedef std::map<ObjCISA, ClassDescriptorSP> ISAToDescriptorMap; + typedef std::multimap<uint32_t, ObjCISA> HashToISAMap; + typedef ISAToDescriptorMap::iterator ISAToDescriptorIterator; + typedef HashToISAMap::iterator HashToISAIterator; + typedef ThreadSafeDenseMap<void *, uint64_t> TypeSizeCache; + + MsgImplMap m_impl_cache; + LazyBool m_has_new_literals_and_indexing; + ISAToDescriptorMap m_isa_to_descriptor; + HashToISAMap m_hash_to_isa_map; + TypeSizeCache m_type_size_cache; + +protected: + uint32_t m_isa_to_descriptor_stop_id; + + typedef std::map<ConstString, lldb::TypeWP> CompleteClassMap; + CompleteClassMap m_complete_class_cache; + + struct ConstStringSetHelpers { + size_t operator()(ConstString arg) const // for hashing + { + return (size_t)arg.GetCString(); + } + bool operator()(ConstString arg1, + ConstString arg2) const // for equality + { + return arg1.operator==(arg2); + } + }; + typedef std::unordered_set<ConstString, ConstStringSetHelpers, + ConstStringSetHelpers> + CompleteClassSet; + CompleteClassSet m_negative_complete_class_cache; + + ISAToDescriptorIterator GetDescriptorIterator(ConstString name); + + friend class ::CommandObjectObjC_ClassTable_Dump; + + std::pair<ISAToDescriptorIterator, ISAToDescriptorIterator> + GetDescriptorIteratorPair(bool update_if_needed = true); + + void ReadObjCLibraryIfNeeded(const ModuleList &module_list); + + DISALLOW_COPY_AND_ASSIGN(ObjCLanguageRuntime); +}; + +} // namespace lldb_private + +#endif // liblldb_ObjCLanguageRuntime_h_
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.cpp index 2c12cf9..6054966 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.cpp
@@ -1,9 +1,8 @@ //===-- RenderScriptExpressionOpts.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.h index 6475581..3ec4e37 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptExpressionOpts.h
@@ -1,9 +1,8 @@ //===-- RenderScriptExpressionOpts.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,7 +34,7 @@ RenderScriptRuntimeModulePass(const lldb_private::Process *process) : ModulePass(ID), m_process_ptr(process) {} - bool runOnModule(llvm::Module &module); + bool runOnModule(llvm::Module &module) override; private: const lldb_private::Process *m_process_ptr;
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp index fa775d9..c9cd34c 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp
@@ -1,14 +1,11 @@ //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "llvm/ADT/StringSwitch.h" - #include "RenderScriptRuntime.h" #include "RenderScriptScriptGroup.h" @@ -41,12 +38,18 @@ #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Status.h" +#include "llvm/ADT/StringSwitch.h" + +#include <memory> + using namespace lldb; using namespace lldb_private; using namespace lldb_renderscript; #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")" +char RenderScriptRuntime::ID = 0; + namespace { // The empirical_type adds a basic level of validation to arbitrary data @@ -591,7 +594,7 @@ array_size; // Number of items in array, only needed for structs ConstString type_name; // Name of type, only needed for structs - static const ConstString & + static ConstString GetFallbackStructName(); // Print this as the type name of a struct Element // If we can't resolve the actual struct name @@ -691,7 +694,7 @@ } }; -const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() { +ConstString RenderScriptRuntime::Element::GetFallbackStructName() { static const ConstString FallbackStructName("struct"); return FallbackStructName; } @@ -789,9 +792,7 @@ // RS_TYPE_MATRIX_2X2 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}}; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ LanguageRuntime * RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language) { @@ -1029,17 +1030,13 @@ } } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString RenderScriptRuntime::GetPluginName() { return GetPluginNameStatic(); } uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; } -bool RenderScriptRuntime::IsVTableName(const char *name) { return false; } - bool RenderScriptRuntime::GetDynamicTypeAndAddress( ValueObject &in_value, lldb::DynamicValueType use_dynamic, TypeAndOrName &class_type_or_name, Address &address, @@ -1126,9 +1123,9 @@ RuntimeHook *hook = (RuntimeHook *)baton; ExecutionContext exe_ctx(ctx->exe_ctx_ref); - RenderScriptRuntime *lang_rt = - (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime( - eLanguageTypeExtRenderScript); + RenderScriptRuntime *lang_rt = llvm::cast<RenderScriptRuntime>( + exe_ctx.GetProcessPtr()->GetLanguageRuntime( + eLanguageTypeExtRenderScript)); lang_rt->HookCallback(hook, exe_ctx); @@ -1212,7 +1209,7 @@ } } if (!group) { - group.reset(new RSScriptGroupDescriptor); + group = std::make_shared<RSScriptGroupDescriptor>(); group->m_name = group_name; m_scriptGroups.push_back(group); } else { @@ -1501,9 +1498,9 @@ uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc])); for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) { - auto &allocation_ap = *iter; // get the unique pointer - if (allocation_ap->address.isValid() && - *allocation_ap->address.get() == addr_t(args[eRsAlloc])) { + auto &allocation_up = *iter; // get the unique pointer + if (allocation_up->address.isValid() && + *allocation_up->address.get() == addr_t(args[eRsAlloc])) { m_allocations.erase(iter); if (log) log->Printf("%s - deleted allocation entry.", __FUNCTION__); @@ -1975,8 +1972,8 @@ // We want 4 elements from packed data const uint32_t num_exprs = 4; - assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && - "Invalid number of expressions"); + static_assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1), + "Invalid number of expressions"); char expr_bufs[num_exprs][jit_max_expr_size]; uint64_t results[num_exprs]; @@ -2034,8 +2031,8 @@ // We want 4 elements from packed data const uint32_t num_exprs = 4; - assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && - "Invalid number of expressions"); + static_assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1), + "Invalid number of expressions"); char expr_bufs[num_exprs][jit_max_expr_size]; uint64_t results[num_exprs]; @@ -2093,8 +2090,8 @@ } const short num_exprs = 3; - assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && - "Invalid number of expressions"); + static_assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1), + "Invalid number of expressions"); char expr_buffer[jit_max_expr_size]; uint64_t results; @@ -2362,7 +2359,7 @@ size_diff); for (uint32_t i = 0; i < size_diff; ++i) { - const ConstString &name = elem.children[num_children + i].type_name; + ConstString name = elem.children[num_children + i].type_name; if (strcmp(name.AsCString(), "#rs_padding") < 0) found = false; } @@ -2855,7 +2852,7 @@ switch (GetModuleKind(module_sp)) { case eModuleKindKernelObj: { RSModuleDescriptorSP module_desc; - module_desc.reset(new RSModuleDescriptor(module_sp)); + module_desc = std::make_shared<RSModuleDescriptor>(module_sp); if (module_desc->ParseRSInfo()) { m_rsmodules.push_back(module_desc); module_desc->WarnIfVersionMismatch(GetProcess() @@ -3593,7 +3590,7 @@ // Given the name of a kernel this function creates a breakpoint using our own // breakpoint resolver, and returns the Breakpoint shared pointer. BreakpointSP -RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) { +RenderScriptRuntime::CreateKernelBreakpoint(ConstString name) { Log *log( GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); @@ -3621,7 +3618,7 @@ } BreakpointSP -RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name, +RenderScriptRuntime::CreateReductionBreakpoint(ConstString name, int kernel_types) { Log *log( GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); @@ -3862,7 +3859,7 @@ } BreakpointSP -RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name, +RenderScriptRuntime::CreateScriptGroupBreakpoint(ConstString name, bool stop_on_all) { Log *log( GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); @@ -3892,7 +3889,7 @@ bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target, Stream &strm, - const ConstString &name, + ConstString name, bool multi) { InitSearchFilter(target); BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi); @@ -4125,9 +4122,9 @@ ~CommandObjectRenderScriptRuntimeModuleDump() override = default; bool DoExecute(Args &command, CommandReturnObject &result) override { - RenderScriptRuntime *runtime = - (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( - eLanguageTypeExtRenderScript); + RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>( + m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( + eLanguageTypeExtRenderScript)); runtime->DumpModules(result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); return true; @@ -4160,9 +4157,9 @@ ~CommandObjectRenderScriptRuntimeKernelList() override = default; bool DoExecute(Args &command, CommandReturnObject &result) override { - RenderScriptRuntime *runtime = - (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( - eLanguageTypeExtRenderScript); + RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>( + m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( + eLanguageTypeExtRenderScript)); runtime->DumpKernels(result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); return true; @@ -4407,9 +4404,9 @@ return false; } - RenderScriptRuntime *runtime = - (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( - eLanguageTypeExtRenderScript); + RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>( + m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( + eLanguageTypeExtRenderScript)); auto &outstream = result.GetOutputStream(); auto &target = m_exe_ctx.GetTargetSP(); @@ -4591,9 +4588,9 @@ ~CommandObjectRenderScriptRuntimeContextDump() override = default; bool DoExecute(Args &command, CommandReturnObject &result) override { - RenderScriptRuntime *runtime = - (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( - eLanguageTypeExtRenderScript); + RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>( + m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( + eLanguageTypeExtRenderScript)); runtime->DumpContexts(result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); return true; @@ -4983,9 +4980,9 @@ ~CommandObjectRenderScriptRuntimeStatus() override = default; bool DoExecute(Args &command, CommandReturnObject &result) override { - RenderScriptRuntime *runtime = - (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( - eLanguageTypeExtRenderScript); + RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>( + m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( + eLanguageTypeExtRenderScript)); runtime->DumpStatus(result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); return true;
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h index 31714dd..3923221 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h
@@ -1,9 +1,8 @@ //===-- RenderScriptRuntime.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,10 +19,11 @@ #include "llvm/ADT/StringRef.h" #include "lldb/Core/Module.h" #include "lldb/Expression/LLVMUserExpression.h" -#include "lldb/Target/CPPLanguageRuntime.h" #include "lldb/Target/LanguageRuntime.h" #include "lldb/lldb-private.h" +#include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h" + namespace lldb_private { namespace lldb_renderscript { @@ -246,7 +246,7 @@ class RSScriptGroupBreakpointResolver : public BreakpointResolver { public: - RSScriptGroupBreakpointResolver(Breakpoint *bp, const ConstString &name, + RSScriptGroupBreakpointResolver(Breakpoint *bp, ConstString name, const RSScriptGroupList &groups, bool stop_on_all) : BreakpointResolver(bp, BreakpointResolver::NameResolver), @@ -276,7 +276,7 @@ protected: const RSScriptGroupDescriptorSP - FindScriptGroup(const ConstString &name) const { + FindScriptGroup(ConstString name) const { for (auto sg : m_script_groups) { if (ConstString::Compare(sg->m_name, name) == 0) return sg; @@ -302,9 +302,7 @@ ~RenderScriptRuntime() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -317,6 +315,16 @@ static lldb_private::ConstString GetPluginNameStatic(); + static char ID; + + bool isA(const void *ClassID) const override { + return ClassID == &ID || CPPLanguageRuntime::isA(ClassID); + } + + static bool classof(const LanguageRuntime *runtime) { + return runtime->isA(&ID); + } + static bool IsRenderScriptModule(const lldb::ModuleSP &module_sp); static ModuleKind GetModuleKind(const lldb::ModuleSP &module_sp); @@ -324,8 +332,6 @@ static void ModulesDidLoad(const lldb::ProcessSP &process_sp, const ModuleList &module_list); - bool IsVTableName(const char *name) override; - bool GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic, TypeAndOrName &class_type_or_name, @@ -366,7 +372,7 @@ int kernel_types = ~(0)); bool PlaceBreakpointOnScriptGroup(lldb::TargetSP target, Stream &strm, - const ConstString &name, bool stop_on_all); + ConstString name, bool stop_on_all); void SetBreakAllKernels(bool do_break, lldb::TargetSP target); @@ -388,7 +394,7 @@ return m_scriptGroups; }; - bool IsKnownKernel(const ConstString &name) { + bool IsKnownKernel(ConstString name) { for (const auto &module : m_rsmodules) for (const auto &kernel : module->m_kernels) if (kernel.m_name == name) @@ -396,9 +402,7 @@ return false; } - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -429,12 +433,12 @@ bool EvalRSExpression(const char *expression, StackFrame *frame_ptr, uint64_t *result); - lldb::BreakpointSP CreateScriptGroupBreakpoint(const ConstString &name, + lldb::BreakpointSP CreateScriptGroupBreakpoint(ConstString name, bool multi); - lldb::BreakpointSP CreateKernelBreakpoint(const ConstString &name); + lldb::BreakpointSP CreateKernelBreakpoint(ConstString name); - lldb::BreakpointSP CreateReductionBreakpoint(const ConstString &name, + lldb::BreakpointSP CreateReductionBreakpoint(ConstString name, int kernel_types); void BreakOnModuleKernels(
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp index 7786d68..45d0d02 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp
@@ -1,9 +1,8 @@ //===-- RenderScriptScriptGroup.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.h index 5c5608c..c25e240 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.h
@@ -1,9 +1,8 @@ //===-- RenderScriptScriptGroup.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.cpp index 0b298c9..4725e8c 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.cpp +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.cpp
@@ -1,9 +1,8 @@ //===-- RenderScriptx86ABIFixups.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -193,8 +192,9 @@ llvm::LoadInst *new_func_addr_load = new llvm::LoadInst(new_func_ptr, "load_func_pointer", call_inst); // and create a callinstruction from it - llvm::CallInst *new_call_inst = llvm::CallInst::Create( - new_func_addr_load, new_call_args, "new_func_call", call_inst); + llvm::CallInst *new_call_inst = + llvm::CallInst::Create(new_func_type, new_func_addr_load, new_call_args, + "new_func_call", call_inst); new_call_inst->setCallingConv(call_inst->getCallingConv()); new_call_inst->setTailCall(call_inst->isTailCall()); llvm::LoadInst *lldb_save_result_address =
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.h index b2caea4..a5efc99 100644 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.h +++ b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.h
@@ -1,9 +1,8 @@ //===-- RenderScriptx86ABIFixups.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/CMakeLists.txt deleted file mode 100644 index 17d4c55..0000000 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/CMakeLists.txt +++ /dev/null
@@ -1,10 +0,0 @@ -add_lldb_library(lldbPluginLanguageRuntimeRust PLUGIN - RustLanguageRuntime.cpp - - LINK_LIBS - lldbCore - lldbSymbol - lldbTarget - LINK_COMPONENTS - Support - )
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/RustLanguageRuntime.cpp b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/RustLanguageRuntime.cpp deleted file mode 100644 index 8c91e5f..0000000 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/RustLanguageRuntime.cpp +++ /dev/null
@@ -1,119 +0,0 @@ -//===-- RustLanguageRuntime.cpp ---------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "RustLanguageRuntime.h" - -#include "lldb/Core/PluginManager.h" -#include "lldb/Symbol/RustASTContext.h" -#include "lldb/Symbol/Symbol.h" -#include "lldb/Symbol/SymbolContext.h" -#include "lldb/Symbol/SymbolFile.h" -#include "lldb/Symbol/Type.h" -#include "lldb/Symbol/TypeList.h" -#include "lldb/Target/SectionLoadList.h" -#include "lldb/Target/Target.h" -#include "llvm/ADT/StringRef.h" - -using namespace lldb; -using namespace lldb_private; - -RustLanguageRuntime::RustLanguageRuntime(Process *process) - : LanguageRuntime(process) -{ -} - -LanguageRuntime * -RustLanguageRuntime::CreateInstance(Process *process, - lldb::LanguageType language) { - if (language == eLanguageTypeRust) - return new RustLanguageRuntime(process); - return nullptr; -} - -void RustLanguageRuntime::Initialize() { - PluginManager::RegisterPlugin(GetPluginNameStatic(), "Rust language runtime", - CreateInstance); -} - -void RustLanguageRuntime::Terminate() { - PluginManager::UnregisterPlugin(CreateInstance); -} - -lldb_private::ConstString RustLanguageRuntime::GetPluginNameStatic() { - static ConstString g_name("rust"); - return g_name; -} - -lldb_private::ConstString RustLanguageRuntime::GetPluginName() { - return GetPluginNameStatic(); -} - -uint32_t RustLanguageRuntime::GetPluginVersion() { - return 1; -} - -bool RustLanguageRuntime::CouldHaveDynamicValue(ValueObject &in_value) { - return in_value.GetCompilerType().IsPossibleDynamicType(nullptr, false, false); -} - -bool RustLanguageRuntime::GetDynamicTypeAndAddress( - ValueObject &in_value, lldb::DynamicValueType use_dynamic, - TypeAndOrName &class_type_or_name, Address &dynamic_address, - Value::ValueType &value_type) { - class_type_or_name.Clear(); - value_type = Value::ValueType::eValueTypeScalar; - - CompilerType type = in_value.GetCompilerType(); - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - - if (!ast) { - return false; - } - - uint64_t discr_offset, discr_byte_size; - if (ast->GetEnumDiscriminantLocation(type, discr_offset, discr_byte_size)) { - lldb::addr_t original_ptr = in_value.GetAddressOf(false); // FIXME? - if (original_ptr == LLDB_INVALID_ADDRESS) { - return false; - } - - ExecutionContext exe_ctx(in_value.GetExecutionContextRef()); - Process *process = exe_ctx.GetProcessPtr(); - if (process == nullptr) { - return false; - } - - Status error; - uint64_t discriminant = - process->ReadUnsignedIntegerFromMemory(original_ptr + discr_offset, discr_byte_size, - 0, error); - if (!error.Success()) { - return false; - } - - CompilerType variant_type = ast->FindEnumVariant(type, discriminant); - if (!variant_type) { - return false; - } - class_type_or_name = TypeAndOrName(variant_type); - // The address doesn't change. - dynamic_address.SetLoadAddress(original_ptr, exe_ctx.GetTargetPtr()); - value_type = Value::ValueType::eValueTypeLoadAddress; - - return true; - } - - return false; -} - -TypeAndOrName -RustLanguageRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name, - ValueObject &static_value) { - return type_and_or_name; -}
diff --git a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/RustLanguageRuntime.h b/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/RustLanguageRuntime.h deleted file mode 100644 index c8ff5a1..0000000 --- a/src/llvm-project/lldb/source/Plugins/LanguageRuntime/Rust/RustLanguageRuntime.h +++ /dev/null
@@ -1,78 +0,0 @@ -//===-- RustLanguageRuntime.h -----------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_RustLanguageRuntime_h_ -#define liblldb_RustLanguageRuntime_h_ - -// C Includes -// C++ Includes -#include <vector> -// Other libraries and framework includes -// Project includes -#include "lldb/Core/PluginInterface.h" -#include "lldb/Target/LanguageRuntime.h" -#include "lldb/lldb-private.h" - -namespace lldb_private { - -class RustLanguageRuntime : public LanguageRuntime { -public: - static void Initialize(); - - static void Terminate(); - - static lldb_private::LanguageRuntime * - CreateInstance(Process *process, lldb::LanguageType language); - - static lldb_private::ConstString GetPluginNameStatic(); - - lldb_private::ConstString GetPluginName() override; - - uint32_t GetPluginVersion() override; - - lldb::LanguageType GetLanguageType() const override { - return lldb::eLanguageTypeRust; - } - - bool GetObjectDescription(Stream &str, ValueObject &object) override { - return false; - } - - bool GetObjectDescription(Stream &str, Value &value, - ExecutionContextScope *exe_scope) override { - return false; - } - - lldb::BreakpointResolverSP CreateExceptionResolver(Breakpoint *bkpt, - bool catch_bp, - bool throw_bp) override { - return nullptr; - } - - TypeAndOrName FixUpDynamicType(const TypeAndOrName &type_and_or_name, - ValueObject &static_value) override; - - bool CouldHaveDynamicValue(ValueObject &in_value) override; - - bool GetDynamicTypeAndAddress(ValueObject &in_value, - lldb::DynamicValueType use_dynamic, - TypeAndOrName &class_type_or_name, - Address &address, - Value::ValueType &value_type) override; - -protected: - RustLanguageRuntime(Process *process); - -private: - DISALLOW_COPY_AND_ASSIGN(RustLanguageRuntime); -}; - -} // namespace lldb_private - -#endif // liblldb_RustLanguageRuntime_h_
diff --git a/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp b/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp index b9e49d1..e0d2c5d 100644 --- a/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp +++ b/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp
@@ -1,9 +1,8 @@ //===-- MemoryHistoryASan.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,7 +30,7 @@ MemoryHistorySP MemoryHistoryASan::CreateInstance(const ProcessSP &process_sp) { if (!process_sp.get()) - return NULL; + return nullptr; Target &target = process_sp->GetTarget(); @@ -137,8 +136,7 @@ pcs.push_back(pc); } - HistoryThread *history_thread = - new HistoryThread(*process_sp, tid, pcs, 0, false); + HistoryThread *history_thread = new HistoryThread(*process_sp, tid, pcs); ThreadSP new_thread_sp(history_thread); std::ostringstream thread_name_with_number; thread_name_with_number << thread_name << " Thread " << tid; @@ -149,8 +147,6 @@ result.push_back(new_thread_sp); } -static constexpr std::chrono::seconds g_get_stack_function_timeout(2); - HistoryThreads MemoryHistoryASan::GetHistoryThreads(lldb::addr_t address) { HistoryThreads result; @@ -178,7 +174,7 @@ options.SetTryAllThreads(true); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); - options.SetTimeout(g_get_stack_function_timeout); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetPrefix(memory_history_asan_command_prefix); options.SetAutoApplyFixIts(false); options.SetLanguage(eLanguageTypeObjC_plus_plus);
diff --git a/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.h b/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.h index c08acd0..266576b0 100644 --- a/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.h +++ b/src/llvm-project/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.h
@@ -1,9 +1,8 @@ //===-- MemoryHistoryASan.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp b/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp index 391ab75..512b5be 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp
@@ -1,9 +1,8 @@ //===-- ObjectContainerBSDArchive.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -42,18 +41,18 @@ using namespace lldb_private; ObjectContainerBSDArchive::Object::Object() - : ar_name(), ar_date(0), ar_uid(0), ar_gid(0), ar_mode(0), ar_size(0), - ar_file_offset(0), ar_file_size(0) {} + : ar_name(), modification_time(0), uid(0), gid(0), mode(0), size(0), + file_offset(0), file_size(0) {} void ObjectContainerBSDArchive::Object::Clear() { ar_name.Clear(); - ar_date = 0; - ar_uid = 0; - ar_gid = 0; - ar_mode = 0; - ar_size = 0; - ar_file_offset = 0; - ar_file_size = 0; + modification_time = 0; + uid = 0; + gid = 0; + mode = 0; + size = 0; + file_offset = 0; + file_size = 0; } lldb::offset_t @@ -103,32 +102,32 @@ } str.assign((const char *)data.GetData(&offset, 12), 12); - ar_date = strtoul(str.c_str(), &err, 10); + modification_time = strtoul(str.c_str(), &err, 10); str.assign((const char *)data.GetData(&offset, 6), 6); - ar_uid = strtoul(str.c_str(), &err, 10); + uid = strtoul(str.c_str(), &err, 10); str.assign((const char *)data.GetData(&offset, 6), 6); - ar_gid = strtoul(str.c_str(), &err, 10); + gid = strtoul(str.c_str(), &err, 10); str.assign((const char *)data.GetData(&offset, 8), 8); - ar_mode = strtoul(str.c_str(), &err, 8); + mode = strtoul(str.c_str(), &err, 8); str.assign((const char *)data.GetData(&offset, 10), 10); - ar_size = strtoul(str.c_str(), &err, 10); + size = strtoul(str.c_str(), &err, 10); str.assign((const char *)data.GetData(&offset, 2), 2); if (str == ARFMAG) { if (ar_name_len > 0) { const void *ar_name_ptr = data.GetData(&offset, ar_name_len); // Make sure there was enough data for the string value and bail if not - if (ar_name_ptr == NULL) + if (ar_name_ptr == nullptr) return LLDB_INVALID_OFFSET; str.assign((const char *)ar_name_ptr, ar_name_len); ar_name.SetCString(str.c_str()); } - ar_file_offset = offset; - ar_file_size = ar_size - ar_name_len; + file_offset = offset; + file_size = size - ar_name_len; return offset; } return LLDB_INVALID_OFFSET; @@ -138,8 +137,8 @@ const llvm::sys::TimePoint<> &time, lldb::offset_t file_offset, lldb_private::DataExtractor &data) - : m_arch(arch), m_time(time), m_file_offset(file_offset), m_objects(), - m_data(data) {} + : m_arch(arch), m_modification_time(time), m_file_offset(file_offset), + m_objects(), m_data(data) {} ObjectContainerBSDArchive::Archive::~Archive() {} @@ -158,7 +157,7 @@ m_objects.push_back(obj); // Insert all of the C strings out of order for now... m_object_name_to_index_map.Append(obj.ar_name, obj_idx); - offset += obj.ar_file_size; + offset += obj.file_size; obj.Clear(); } while (data.ValidOffset(offset)); @@ -170,28 +169,28 @@ ObjectContainerBSDArchive::Object * ObjectContainerBSDArchive::Archive::FindObject( - const ConstString &object_name, - const llvm::sys::TimePoint<> &object_mod_time) { + ConstString object_name, const llvm::sys::TimePoint<> &object_mod_time) { const ObjectNameToIndexMap::Entry *match = m_object_name_to_index_map.FindFirstValueForName(object_name); - if (match) { - if (object_mod_time != llvm::sys::TimePoint<>()) { - const uint64_t object_date = llvm::sys::toTimeT(object_mod_time); - if (m_objects[match->value].ar_date == object_date) - return &m_objects[match->value]; - const ObjectNameToIndexMap::Entry *next_match = - m_object_name_to_index_map.FindNextValueForName(match); - while (next_match) { - if (m_objects[next_match->value].ar_date == object_date) - return &m_objects[next_match->value]; - next_match = - m_object_name_to_index_map.FindNextValueForName(next_match); - } - } else { - return &m_objects[match->value]; - } + if (!match) + return nullptr; + if (object_mod_time == llvm::sys::TimePoint<>()) + return &m_objects[match->value]; + + const uint64_t object_modification_date = llvm::sys::toTimeT(object_mod_time); + if (m_objects[match->value].modification_time == object_modification_date) + return &m_objects[match->value]; + + const ObjectNameToIndexMap::Entry *next_match = + m_object_name_to_index_map.FindNextValueForName(match); + while (next_match) { + if (m_objects[next_match->value].modification_time == + object_modification_date) + return &m_objects[next_match->value]; + next_match = m_object_name_to_index_map.FindNextValueForName(next_match); } - return NULL; + + return nullptr; } ObjectContainerBSDArchive::Archive::shared_ptr @@ -321,18 +320,18 @@ Archive::shared_ptr archive_sp(Archive::FindCachedArchive( *file, module_sp->GetArchitecture(), module_sp->GetModificationTime(), file_offset)); - std::unique_ptr<ObjectContainerBSDArchive> container_ap( + std::unique_ptr<ObjectContainerBSDArchive> container_up( new ObjectContainerBSDArchive(module_sp, archive_data_sp, archive_data_offset, file, file_offset, length)); - if (container_ap.get()) { + if (container_up) { if (archive_sp) { // We already have this archive in our cache, use it - container_ap->SetArchive(archive_sp); - return container_ap.release(); - } else if (container_ap->ParseHeader()) - return container_ap.release(); + container_up->SetArchive(archive_sp); + return container_up.release(); + } else if (container_up->ParseHeader()) + return container_up.release(); } } } else { @@ -341,18 +340,18 @@ *file, module_sp->GetArchitecture(), module_sp->GetModificationTime(), file_offset)); if (archive_sp) { - std::unique_ptr<ObjectContainerBSDArchive> container_ap( + std::unique_ptr<ObjectContainerBSDArchive> container_up( new ObjectContainerBSDArchive(module_sp, data_sp, data_offset, file, file_offset, length)); - if (container_ap.get()) { + if (container_up) { // We already have this archive in our cache, use it - container_ap->SetArchive(archive_sp); - return container_ap.release(); + container_up->SetArchive(archive_sp); + return container_up.release(); } } } - return NULL; + return nullptr; } bool ObjectContainerBSDArchive::MagicBytesMatch(const DataExtractor &data) { @@ -379,7 +378,7 @@ ObjectContainerBSDArchive::~ObjectContainerBSDArchive() {} bool ObjectContainerBSDArchive::ParseHeader() { - if (m_archive_sp.get() == NULL) { + if (m_archive_sp.get() == nullptr) { if (m_data.GetByteSize() > 0) { ModuleSP module_sp(GetModule()); if (module_sp) { @@ -392,7 +391,7 @@ m_data.Clear(); } } - return m_archive_sp.get() != NULL; + return m_archive_sp.get() != nullptr; } void ObjectContainerBSDArchive::Dump(Stream *s) const { @@ -426,20 +425,17 @@ Object *object = m_archive_sp->FindObject( module_sp->GetObjectName(), module_sp->GetObjectModificationTime()); if (object) { - lldb::offset_t data_offset = object->ar_file_offset; + lldb::offset_t data_offset = object->file_offset; return ObjectFile::FindPlugin( - module_sp, file, m_offset + object->ar_file_offset, - object->ar_file_size, m_archive_sp->GetData().GetSharedDataBuffer(), - data_offset); + module_sp, file, m_offset + object->file_offset, object->file_size, + m_archive_sp->GetData().GetSharedDataBuffer(), data_offset); } } } return ObjectFileSP(); } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ObjectContainerBSDArchive::GetPluginName() { return GetPluginNameStatic(); } @@ -481,16 +477,15 @@ const Object *object = archive_sp->GetObjectAtIndex(idx); if (object) { const lldb::offset_t object_file_offset = - file_offset + object->ar_file_offset; - if (object->ar_file_offset < file_size && - file_size > object_file_offset) { + file_offset + object->file_offset; + if (object->file_offset < file_size && file_size > object_file_offset) { if (ObjectFile::GetModuleSpecifications( file, object_file_offset, file_size - object_file_offset, specs)) { ModuleSpec &spec = specs.GetModuleSpecRefAtIndex(specs.GetSize() - 1); llvm::sys::TimePoint<> object_mod_time( - std::chrono::seconds(object->ar_date)); + std::chrono::seconds(object->modification_time)); spec.GetObjectName() = object->ar_name; spec.SetObjectOffset(object_file_offset); spec.SetObjectSize(file_size - object_file_offset);
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h b/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h index 86eaee1..5d9c013 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h
@@ -1,9 +1,8 @@ //===-- ObjectContainerBSDArchive.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,9 +31,7 @@ ~ObjectContainerBSDArchive() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -57,9 +54,7 @@ static bool MagicBytesMatch(const lldb_private::DataExtractor &data); - //------------------------------------------------------------------ // Member Functions - //------------------------------------------------------------------ bool ParseHeader() override; size_t GetNumObjects() const override { @@ -72,9 +67,7 @@ lldb::ObjectFileSP GetObjectFile(const lldb_private::FileSpec *file) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -87,20 +80,29 @@ lldb::offset_t Extract(const lldb_private::DataExtractor &data, lldb::offset_t offset); + /// Object name in the archive. + lldb_private::ConstString ar_name; - lldb_private::ConstString ar_name; // name - uint32_t ar_date; // modification time - uint16_t ar_uid; // user id - uint16_t ar_gid; // group id - uint16_t ar_mode; // octal file permissions - uint32_t ar_size; // size in bytes - lldb::offset_t ar_file_offset; // file offset in bytes from the beginning of - // the file of the object data - lldb::offset_t ar_file_size; // length of the object data + /// Object modification time in the archive. + uint32_t modification_time; - typedef std::vector<Object> collection; - typedef collection::iterator iterator; - typedef collection::const_iterator const_iterator; + /// Object user id in the archive. + uint16_t uid; + + /// Object group id in the archive. + uint16_t gid; + + /// Object octal file permissions in the archive. + uint16_t mode; + + /// Object size in bytes in the archive. + uint32_t size; + + /// File offset in bytes from the beginning of the file of the object data. + lldb::offset_t file_offset; + + /// Length of the object data. + lldb::offset_t file_size; }; class Archive { @@ -132,17 +134,19 @@ const Object *GetObjectAtIndex(size_t idx) { if (idx < m_objects.size()) return &m_objects[idx]; - return NULL; + return nullptr; } size_t ParseObjects(); - Object *FindObject(const lldb_private::ConstString &object_name, + Object *FindObject(lldb_private::ConstString object_name, const llvm::sys::TimePoint<> &object_mod_time); lldb::offset_t GetFileOffset() const { return m_file_offset; } - const llvm::sys::TimePoint<> &GetModificationTime() { return m_time; } + const llvm::sys::TimePoint<> &GetModificationTime() { + return m_modification_time; + } const lldb_private::ArchSpec &GetArchitecture() const { return m_arch; } @@ -154,13 +158,11 @@ protected: typedef lldb_private::UniqueCStringMap<uint32_t> ObjectNameToIndexMap; - //---------------------------------------------------------------------- // Member Variables - //---------------------------------------------------------------------- lldb_private::ArchSpec m_arch; - llvm::sys::TimePoint<> m_time; + llvm::sys::TimePoint<> m_modification_time; lldb::offset_t m_file_offset; - Object::collection m_objects; + std::vector<Object> m_objects; ObjectNameToIndexMap m_object_name_to_index_map; lldb_private::DataExtractor m_data; ///< The data for this object container ///so we don't lose data if the .a files
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.cpp b/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.cpp index 4c48d64..839a71c 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.cpp
@@ -1,9 +1,8 @@ //===-- ObjectContainerUniversalMachO.cpp -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -50,15 +49,15 @@ DataExtractor data; data.SetData(data_sp, data_offset, length); if (ObjectContainerUniversalMachO::MagicBytesMatch(data)) { - std::unique_ptr<ObjectContainerUniversalMachO> container_ap( + std::unique_ptr<ObjectContainerUniversalMachO> container_up( new ObjectContainerUniversalMachO(module_sp, data_sp, data_offset, file, file_offset, length)); - if (container_ap->ParseHeader()) { - return container_ap.release(); + if (container_up->ParseHeader()) { + return container_up.release(); } } } - return NULL; + return nullptr; } bool ObjectContainerUniversalMachO::MagicBytesMatch(const DataExtractor &data) { @@ -203,9 +202,7 @@ return ObjectFileSP(); } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ObjectContainerUniversalMachO::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h b/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h index d6e4fe1..5130497 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h
@@ -1,9 +1,8 @@ //===-- ObjectContainerUniversalMachO.h -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ ~ObjectContainerUniversalMachO() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -49,9 +46,7 @@ static bool MagicBytesMatch(const lldb_private::DataExtractor &data); - //------------------------------------------------------------------ // Member Functions - //------------------------------------------------------------------ bool ParseHeader() override; void Dump(lldb_private::Stream *s) const override; @@ -63,9 +58,7 @@ lldb::ObjectFileSP GetObjectFile(const lldb_private::FileSpec *file) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/BreakpadRecords.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/BreakpadRecords.cpp new file mode 100644 index 0000000..d489eaf --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/BreakpadRecords.cpp
@@ -0,0 +1,411 @@ +//===-- BreakpadRecords.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 "Plugins/ObjectFile/Breakpad/BreakpadRecords.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/Support/Endian.h" +#include "llvm/Support/FormatVariadic.h" + +using namespace lldb_private; +using namespace lldb_private::breakpad; + +namespace { +enum class Token { Unknown, Module, Info, CodeID, File, Func, Public, Stack, CFI, Init }; +} + +template<typename T> +static T stringTo(llvm::StringRef Str); + +template <> Token stringTo<Token>(llvm::StringRef Str) { + return llvm::StringSwitch<Token>(Str) + .Case("MODULE", Token::Module) + .Case("INFO", Token::Info) + .Case("CODE_ID", Token::CodeID) + .Case("FILE", Token::File) + .Case("FUNC", Token::Func) + .Case("PUBLIC", Token::Public) + .Case("STACK", Token::Stack) + .Case("CFI", Token::CFI) + .Case("INIT", Token::Init) + .Default(Token::Unknown); +} + +template <> +llvm::Triple::OSType stringTo<llvm::Triple::OSType>(llvm::StringRef Str) { + using llvm::Triple; + return llvm::StringSwitch<Triple::OSType>(Str) + .Case("Linux", Triple::Linux) + .Case("mac", Triple::MacOSX) + .Case("windows", Triple::Win32) + .Default(Triple::UnknownOS); +} + +template <> +llvm::Triple::ArchType stringTo<llvm::Triple::ArchType>(llvm::StringRef Str) { + using llvm::Triple; + return llvm::StringSwitch<Triple::ArchType>(Str) + .Case("arm", Triple::arm) + .Cases("arm64", "arm64e", Triple::aarch64) + .Case("mips", Triple::mips) + .Case("ppc", Triple::ppc) + .Case("ppc64", Triple::ppc64) + .Case("s390", Triple::systemz) + .Case("sparc", Triple::sparc) + .Case("sparcv9", Triple::sparcv9) + .Case("x86", Triple::x86) + .Case("x86_64", Triple::x86_64) + .Default(Triple::UnknownArch); +} + +template<typename T> +static T consume(llvm::StringRef &Str) { + llvm::StringRef Token; + std::tie(Token, Str) = getToken(Str); + return stringTo<T>(Token); +} + +/// Return the number of hex digits needed to encode an (POD) object of a given +/// type. +template <typename T> static constexpr size_t hex_digits() { + return 2 * sizeof(T); +} + +static UUID parseModuleId(llvm::Triple::OSType os, llvm::StringRef str) { + struct data_t { + using uuid_t = uint8_t[16]; + uuid_t uuid; + llvm::support::ubig32_t age; + } data; + static_assert(sizeof(data) == 20, ""); + // The textual module id encoding should be between 33 and 40 bytes long, + // depending on the size of the age field, which is of variable length. + // The first three chunks of the id are encoded in big endian, so we need to + // byte-swap those. + if (str.size() <= hex_digits<data_t::uuid_t>() || + str.size() > hex_digits<data_t>()) + return UUID(); + if (!all_of(str, llvm::isHexDigit)) + return UUID(); + + llvm::StringRef uuid_str = str.take_front(hex_digits<data_t::uuid_t>()); + llvm::StringRef age_str = str.drop_front(hex_digits<data_t::uuid_t>()); + + llvm::copy(fromHex(uuid_str), data.uuid); + uint32_t age; + bool success = to_integer(age_str, age, 16); + assert(success); + (void)success; + data.age = age; + + // On non-windows, the age field should always be zero, so we don't include to + // match the native uuid format of these platforms. + return UUID::fromData(&data, os == llvm::Triple::Win32 ? sizeof(data) + : sizeof(data.uuid)); +} + +llvm::Optional<Record::Kind> Record::classify(llvm::StringRef Line) { + Token Tok = consume<Token>(Line); + switch (Tok) { + case Token::Module: + return Record::Module; + case Token::Info: + return Record::Info; + case Token::File: + return Record::File; + case Token::Func: + return Record::Func; + case Token::Public: + return Record::Public; + case Token::Stack: + Tok = consume<Token>(Line); + switch (Tok) { + case Token::CFI: + return Record::StackCFI; + default: + return llvm::None; + } + + case Token::Unknown: + // Optimistically assume that any unrecognised token means this is a line + // record, those don't have a special keyword and start directly with a + // hex number. CODE_ID should never be at the start of a line, but if it + // is, it can be treated the same way as a garbled line record. + return Record::Line; + + case Token::CodeID: + case Token::CFI: + case Token::Init: + // These should never appear at the start of a valid record. + return llvm::None; + } + llvm_unreachable("Fully covered switch above!"); +} + +llvm::Optional<ModuleRecord> ModuleRecord::parse(llvm::StringRef Line) { + // MODULE Linux x86_64 E5894855C35DCCCCCCCCCCCCCCCCCCCC0 a.out + if (consume<Token>(Line) != Token::Module) + return llvm::None; + + llvm::Triple::OSType OS = consume<llvm::Triple::OSType>(Line); + if (OS == llvm::Triple::UnknownOS) + return llvm::None; + + llvm::Triple::ArchType Arch = consume<llvm::Triple::ArchType>(Line); + if (Arch == llvm::Triple::UnknownArch) + return llvm::None; + + llvm::StringRef Str; + std::tie(Str, Line) = getToken(Line); + UUID ID = parseModuleId(OS, Str); + if (!ID) + return llvm::None; + + return ModuleRecord(OS, Arch, std::move(ID)); +} + +llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS, + const ModuleRecord &R) { + return OS << "MODULE " << llvm::Triple::getOSTypeName(R.OS) << " " + << llvm::Triple::getArchTypeName(R.Arch) << " " + << R.ID.GetAsString(); +} + +llvm::Optional<InfoRecord> InfoRecord::parse(llvm::StringRef Line) { + // INFO CODE_ID 554889E55DC3CCCCCCCCCCCCCCCCCCCC [a.exe] + if (consume<Token>(Line) != Token::Info) + return llvm::None; + + if (consume<Token>(Line) != Token::CodeID) + return llvm::None; + + llvm::StringRef Str; + std::tie(Str, Line) = getToken(Line); + // If we don't have any text following the code ID (e.g. on linux), we should + // use this as the UUID. Otherwise, we should revert back to the module ID. + UUID ID; + if (Line.trim().empty()) { + if (Str.empty() || ID.SetFromStringRef(Str, Str.size() / 2) != Str.size()) + return llvm::None; + } + return InfoRecord(std::move(ID)); +} + +llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS, + const InfoRecord &R) { + return OS << "INFO CODE_ID " << R.ID.GetAsString(); +} + +llvm::Optional<FileRecord> FileRecord::parse(llvm::StringRef Line) { + // FILE number name + if (consume<Token>(Line) != Token::File) + return llvm::None; + + llvm::StringRef Str; + size_t Number; + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, Number)) + return llvm::None; + + llvm::StringRef Name = Line.trim(); + if (Name.empty()) + return llvm::None; + + return FileRecord(Number, Name); +} + +llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS, + const FileRecord &R) { + return OS << "FILE " << R.Number << " " << R.Name; +} + +static bool parsePublicOrFunc(llvm::StringRef Line, bool &Multiple, + lldb::addr_t &Address, lldb::addr_t *Size, + lldb::addr_t &ParamSize, llvm::StringRef &Name) { + // PUBLIC [m] address param_size name + // or + // FUNC [m] address size param_size name + + Token Tok = Size ? Token::Func : Token::Public; + + if (consume<Token>(Line) != Tok) + return false; + + llvm::StringRef Str; + std::tie(Str, Line) = getToken(Line); + Multiple = Str == "m"; + + if (Multiple) + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, Address, 16)) + return false; + + if (Tok == Token::Func) { + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, *Size, 16)) + return false; + } + + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, ParamSize, 16)) + return false; + + Name = Line.trim(); + if (Name.empty()) + return false; + + return true; +} + +llvm::Optional<FuncRecord> FuncRecord::parse(llvm::StringRef Line) { + bool Multiple; + lldb::addr_t Address, Size, ParamSize; + llvm::StringRef Name; + + if (parsePublicOrFunc(Line, Multiple, Address, &Size, ParamSize, Name)) + return FuncRecord(Multiple, Address, Size, ParamSize, Name); + + return llvm::None; +} + +bool breakpad::operator==(const FuncRecord &L, const FuncRecord &R) { + return L.Multiple == R.Multiple && L.Address == R.Address && + L.Size == R.Size && L.ParamSize == R.ParamSize && L.Name == R.Name; +} +llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS, + const FuncRecord &R) { + return OS << llvm::formatv("FUNC {0}{1:x-} {2:x-} {3:x-} {4}", + R.Multiple ? "m " : "", R.Address, R.Size, + R.ParamSize, R.Name); +} + +llvm::Optional<LineRecord> LineRecord::parse(llvm::StringRef Line) { + lldb::addr_t Address; + llvm::StringRef Str; + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, Address, 16)) + return llvm::None; + + lldb::addr_t Size; + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, Size, 16)) + return llvm::None; + + uint32_t LineNum; + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, LineNum)) + return llvm::None; + + size_t FileNum; + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, FileNum)) + return llvm::None; + + return LineRecord(Address, Size, LineNum, FileNum); +} + +bool breakpad::operator==(const LineRecord &L, const LineRecord &R) { + return L.Address == R.Address && L.Size == R.Size && L.LineNum == R.LineNum && + L.FileNum == R.FileNum; +} +llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS, + const LineRecord &R) { + return OS << llvm::formatv("{0:x-} {1:x-} {2} {3}", R.Address, R.Size, + R.LineNum, R.FileNum); +} + +llvm::Optional<PublicRecord> PublicRecord::parse(llvm::StringRef Line) { + bool Multiple; + lldb::addr_t Address, ParamSize; + llvm::StringRef Name; + + if (parsePublicOrFunc(Line, Multiple, Address, nullptr, ParamSize, Name)) + return PublicRecord(Multiple, Address, ParamSize, Name); + + return llvm::None; +} + +bool breakpad::operator==(const PublicRecord &L, const PublicRecord &R) { + return L.Multiple == R.Multiple && L.Address == R.Address && + L.ParamSize == R.ParamSize && L.Name == R.Name; +} +llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS, + const PublicRecord &R) { + return OS << llvm::formatv("PUBLIC {0}{1:x-} {2:x-} {3}", + R.Multiple ? "m " : "", R.Address, R.ParamSize, + R.Name); +} + +llvm::Optional<StackCFIRecord> StackCFIRecord::parse(llvm::StringRef Line) { + // STACK CFI INIT address size reg1: expr1 reg2: expr2 ... + // or + // STACK CFI address reg1: expr1 reg2: expr2 ... + // No token in exprN ends with a colon. + + if (consume<Token>(Line) != Token::Stack) + return llvm::None; + if (consume<Token>(Line) != Token::CFI) + return llvm::None; + + llvm::StringRef Str; + std::tie(Str, Line) = getToken(Line); + + bool IsInitRecord = stringTo<Token>(Str) == Token::Init; + if (IsInitRecord) + std::tie(Str, Line) = getToken(Line); + + lldb::addr_t Address; + if (!to_integer(Str, Address, 16)) + return llvm::None; + + llvm::Optional<lldb::addr_t> Size; + if (IsInitRecord) { + Size.emplace(); + std::tie(Str, Line) = getToken(Line); + if (!to_integer(Str, *Size, 16)) + return llvm::None; + } + + return StackCFIRecord(Address, Size, Line.trim()); +} + +bool breakpad::operator==(const StackCFIRecord &L, const StackCFIRecord &R) { + return L.Address == R.Address && L.Size == R.Size && + L.UnwindRules == R.UnwindRules; +} + +llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS, + const StackCFIRecord &R) { + OS << "STACK CFI "; + if (R.Size) + OS << "INIT "; + OS << llvm::formatv("{0:x-} ", R.Address); + if (R.Size) + OS << llvm::formatv("{0:x-} ", *R.Size); + return OS << " " << R.UnwindRules; +} + +llvm::StringRef breakpad::toString(Record::Kind K) { + switch (K) { + case Record::Module: + return "MODULE"; + case Record::Info: + return "INFO"; + case Record::File: + return "FILE"; + case Record::Func: + return "FUNC"; + case Record::Line: + return "LINE"; + case Record::Public: + return "PUBLIC"; + case Record::StackCFI: + return "STACK CFI"; + } + llvm_unreachable("Unknown record kind!"); +}
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/BreakpadRecords.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/BreakpadRecords.h new file mode 100644 index 0000000..5d5cdb3 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/BreakpadRecords.h
@@ -0,0 +1,163 @@ +//===-- BreakpadRecords.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_PLUGINS_OBJECTFILE_BREAKPAD_BREAKPADRECORDS_H +#define LLDB_PLUGINS_OBJECTFILE_BREAKPAD_BREAKPADRECORDS_H + +#include "lldb/Utility/UUID.h" +#include "lldb/lldb-types.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Triple.h" +#include "llvm/Support/FormatProviders.h" + +namespace lldb_private { +namespace breakpad { + +class Record { +public: + enum Kind { Module, Info, File, Func, Line, Public, StackCFI }; + + /// Attempt to guess the kind of the record present in the argument without + /// doing a full parse. The returned kind will always be correct for valid + /// records, but the full parse can still fail in case of corrupted input. + static llvm::Optional<Kind> classify(llvm::StringRef Line); + +protected: + Record(Kind K) : TheKind(K) {} + + ~Record() = default; + +public: + Kind getKind() { return TheKind; } + +private: + Kind TheKind; +}; + +llvm::StringRef toString(Record::Kind K); +inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, Record::Kind K) { + OS << toString(K); + return OS; +} + +class ModuleRecord : public Record { +public: + static llvm::Optional<ModuleRecord> parse(llvm::StringRef Line); + ModuleRecord(llvm::Triple::OSType OS, llvm::Triple::ArchType Arch, UUID ID) + : Record(Module), OS(OS), Arch(Arch), ID(std::move(ID)) {} + + llvm::Triple::OSType OS; + llvm::Triple::ArchType Arch; + UUID ID; +}; + +inline bool operator==(const ModuleRecord &L, const ModuleRecord &R) { + return L.OS == R.OS && L.Arch == R.Arch && L.ID == R.ID; +} +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const ModuleRecord &R); + +class InfoRecord : public Record { +public: + static llvm::Optional<InfoRecord> parse(llvm::StringRef Line); + InfoRecord(UUID ID) : Record(Info), ID(std::move(ID)) {} + + UUID ID; +}; + +inline bool operator==(const InfoRecord &L, const InfoRecord &R) { + return L.ID == R.ID; +} +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const InfoRecord &R); + +class FileRecord : public Record { +public: + static llvm::Optional<FileRecord> parse(llvm::StringRef Line); + FileRecord(size_t Number, llvm::StringRef Name) + : Record(File), Number(Number), Name(Name) {} + + size_t Number; + llvm::StringRef Name; +}; + +inline bool operator==(const FileRecord &L, const FileRecord &R) { + return L.Number == R.Number && L.Name == R.Name; +} +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const FileRecord &R); + +class FuncRecord : public Record { +public: + static llvm::Optional<FuncRecord> parse(llvm::StringRef Line); + FuncRecord(bool Multiple, lldb::addr_t Address, lldb::addr_t Size, + lldb::addr_t ParamSize, llvm::StringRef Name) + : Record(Module), Multiple(Multiple), Address(Address), Size(Size), + ParamSize(ParamSize), Name(Name) {} + + bool Multiple; + lldb::addr_t Address; + lldb::addr_t Size; + lldb::addr_t ParamSize; + llvm::StringRef Name; +}; + +bool operator==(const FuncRecord &L, const FuncRecord &R); +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const FuncRecord &R); + +class LineRecord : public Record { +public: + static llvm::Optional<LineRecord> parse(llvm::StringRef Line); + LineRecord(lldb::addr_t Address, lldb::addr_t Size, uint32_t LineNum, + size_t FileNum) + : Record(Line), Address(Address), Size(Size), LineNum(LineNum), + FileNum(FileNum) {} + + lldb::addr_t Address; + lldb::addr_t Size; + uint32_t LineNum; + size_t FileNum; +}; + +bool operator==(const LineRecord &L, const LineRecord &R); +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const LineRecord &R); + +class PublicRecord : public Record { +public: + static llvm::Optional<PublicRecord> parse(llvm::StringRef Line); + PublicRecord(bool Multiple, lldb::addr_t Address, lldb::addr_t ParamSize, + llvm::StringRef Name) + : Record(Module), Multiple(Multiple), Address(Address), + ParamSize(ParamSize), Name(Name) {} + + bool Multiple; + lldb::addr_t Address; + lldb::addr_t ParamSize; + llvm::StringRef Name; +}; + +bool operator==(const PublicRecord &L, const PublicRecord &R); +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const PublicRecord &R); + +class StackCFIRecord : public Record { +public: + static llvm::Optional<StackCFIRecord> parse(llvm::StringRef Line); + StackCFIRecord(lldb::addr_t Address, llvm::Optional<lldb::addr_t> Size, + llvm::StringRef UnwindRules) + : Record(StackCFI), Address(Address), Size(Size), + UnwindRules(UnwindRules) {} + + lldb::addr_t Address; + llvm::Optional<lldb::addr_t> Size; + llvm::StringRef UnwindRules; +}; + +bool operator==(const StackCFIRecord &L, const StackCFIRecord &R); +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const StackCFIRecord &R); + +} // namespace breakpad +} // namespace lldb_private + +#endif // LLDB_PLUGINS_OBJECTFILE_BREAKPAD_BREAKPADRECORDS_H
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/CMakeLists.txt index 2f51b2c..0f3d9233 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/CMakeLists.txt
@@ -1,4 +1,5 @@ add_lldb_library(lldbPluginObjectFileBreakpad PLUGIN + BreakpadRecords.cpp ObjectFileBreakpad.cpp LINK_LIBS
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.cpp index 9170250..60dd9f9 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.cpp
@@ -1,18 +1,16 @@ //===-- ObjectFileBreakpad.cpp -------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h" +#include "Plugins/ObjectFile/Breakpad/BreakpadRecords.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" -#include "lldb/Utility/DataBuffer.h" -#include "llvm/ADT/StringExtras.h" using namespace lldb; using namespace lldb_private; @@ -24,164 +22,24 @@ UUID uuid; static llvm::Optional<Header> parse(llvm::StringRef text); }; - -enum class Token { Unknown, Module, Info, File, Func, Public, Stack }; } // namespace -static Token toToken(llvm::StringRef str) { - return llvm::StringSwitch<Token>(str) - .Case("MODULE", Token::Module) - .Case("INFO", Token::Info) - .Case("FILE", Token::File) - .Case("FUNC", Token::Func) - .Case("PUBLIC", Token::Public) - .Case("STACK", Token::Stack) - .Default(Token::Unknown); -} - -static llvm::StringRef toString(Token t) { - switch (t) { - case Token::Unknown: - return ""; - case Token::Module: - return "MODULE"; - case Token::Info: - return "INFO"; - case Token::File: - return "FILE"; - case Token::Func: - return "FUNC"; - case Token::Public: - return "PUBLIC"; - case Token::Stack: - return "STACK"; - } - llvm_unreachable("Unknown token!"); -} - -static llvm::Triple::OSType toOS(llvm::StringRef str) { - using llvm::Triple; - return llvm::StringSwitch<Triple::OSType>(str) - .Case("Linux", Triple::Linux) - .Case("mac", Triple::MacOSX) - .Case("windows", Triple::Win32) - .Default(Triple::UnknownOS); -} - -static llvm::Triple::ArchType toArch(llvm::StringRef str) { - using llvm::Triple; - return llvm::StringSwitch<Triple::ArchType>(str) - .Case("arm", Triple::arm) - .Case("arm64", Triple::aarch64) - .Case("mips", Triple::mips) - .Case("ppc", Triple::ppc) - .Case("ppc64", Triple::ppc64) - .Case("s390", Triple::systemz) - .Case("sparc", Triple::sparc) - .Case("sparcv9", Triple::sparcv9) - .Case("x86", Triple::x86) - .Case("x86_64", Triple::x86_64) - .Default(Triple::UnknownArch); -} - -static llvm::StringRef consume_front(llvm::StringRef &str, size_t n) { - llvm::StringRef result = str.take_front(n); - str = str.drop_front(n); - return result; -} - -static UUID parseModuleId(llvm::Triple::OSType os, llvm::StringRef str) { - struct uuid_data { - llvm::support::ulittle32_t uuid1; - llvm::support::ulittle16_t uuid2[2]; - uint8_t uuid3[8]; - llvm::support::ulittle32_t age; - } data; - static_assert(sizeof(data) == 20, ""); - // The textual module id encoding should be between 33 and 40 bytes long, - // depending on the size of the age field, which is of variable length. - // The first three chunks of the id are encoded in big endian, so we need to - // byte-swap those. - if (str.size() < 33 || str.size() > 40) - return UUID(); - uint32_t t; - if (to_integer(consume_front(str, 8), t, 16)) - data.uuid1 = t; - else - return UUID(); - for (int i = 0; i < 2; ++i) { - if (to_integer(consume_front(str, 4), t, 16)) - data.uuid2[i] = t; - else - return UUID(); - } - for (int i = 0; i < 8; ++i) { - if (!to_integer(consume_front(str, 2), data.uuid3[i], 16)) - return UUID(); - } - if (to_integer(str, t, 16)) - data.age = t; - else - return UUID(); - - // On non-windows, the age field should always be zero, so we don't include to - // match the native uuid format of these platforms. - return UUID::fromData(&data, os == llvm::Triple::Win32 ? 20 : 16); -} - llvm::Optional<Header> Header::parse(llvm::StringRef text) { - // A valid module should start with something like: - // MODULE Linux x86_64 E5894855C35DCCCCCCCCCCCCCCCCCCCC0 a.out - // optionally followed by - // INFO CODE_ID 554889E55DC3CCCCCCCCCCCCCCCCCCCC [a.exe] - llvm::StringRef token, line; + llvm::StringRef line; std::tie(line, text) = text.split('\n'); - std::tie(token, line) = getToken(line); - if (toToken(token) != Token::Module) + auto Module = ModuleRecord::parse(line); + if (!Module) return llvm::None; - std::tie(token, line) = getToken(line); llvm::Triple triple; - triple.setOS(toOS(token)); - if (triple.getOS() == llvm::Triple::UnknownOS) - return llvm::None; - - std::tie(token, line) = getToken(line); - triple.setArch(toArch(token)); - if (triple.getArch() == llvm::Triple::UnknownArch) - return llvm::None; - - llvm::StringRef module_id; - std::tie(module_id, line) = getToken(line); + triple.setArch(Module->Arch); + triple.setOS(Module->OS); std::tie(line, text) = text.split('\n'); - std::tie(token, line) = getToken(line); - if (token == "INFO") { - std::tie(token, line) = getToken(line); - if (token != "CODE_ID") - return llvm::None; - std::tie(token, line) = getToken(line); - // If we don't have any text following the code id (e.g. on linux), we - // should use the module id as UUID. Otherwise, we revert back to the module - // id. - if (line.trim().empty()) { - UUID uuid; - if (uuid.SetFromStringRef(token, token.size() / 2) != token.size()) - return llvm::None; - - return Header{ArchSpec(triple), uuid}; - } - } - - // We reach here if we don't have a INFO CODE_ID section, or we chose not to - // use it. In either case, we need to properly decode the module id, whose - // fields are encoded in big-endian. - UUID uuid = parseModuleId(triple.getOS(), module_id); - if (!uuid) - return llvm::None; - - return Header{ArchSpec(triple), uuid}; + auto Info = InfoRecord::parse(line); + UUID uuid = Info && Info->ID ? Info->ID : Module->ID; + return Header{ArchSpec(triple), std::move(uuid)}; } void ObjectFileBreakpad::Initialize() { @@ -264,50 +122,45 @@ return nullptr; } -bool ObjectFileBreakpad::GetUUID(UUID *uuid) { - *uuid = m_uuid; - return true; -} - void ObjectFileBreakpad::CreateSections(SectionList &unified_section_list) { - if (m_sections_ap) + if (m_sections_up) return; - m_sections_ap = llvm::make_unique<SectionList>(); + m_sections_up = llvm::make_unique<SectionList>(); - Token current_section = Token::Unknown; + llvm::Optional<Record::Kind> current_section; offset_t section_start; llvm::StringRef text = toStringRef(m_data.GetData()); uint32_t next_section_id = 1; auto maybe_add_section = [&](const uint8_t *end_ptr) { - if (current_section == Token::Unknown) + if (!current_section) return; // We have been called before parsing the first line. offset_t end_offset = end_ptr - m_data.GetDataStart(); auto section_sp = std::make_shared<Section>( GetModule(), this, next_section_id++, - ConstString(toString(current_section)), eSectionTypeOther, + ConstString(toString(*current_section)), eSectionTypeOther, /*file_vm_addr*/ 0, /*vm_size*/ 0, section_start, end_offset - section_start, /*log2align*/ 0, /*flags*/ 0); - m_sections_ap->AddSection(section_sp); + m_sections_up->AddSection(section_sp); unified_section_list.AddSection(section_sp); }; while (!text.empty()) { llvm::StringRef line; std::tie(line, text) = text.split('\n'); - Token token = toToken(getToken(line).first); - if (token == Token::Unknown) { - // We assume this is a line record, which logically belongs to the Func - // section. Errors will be handled when parsing the Func section. - token = Token::Func; + llvm::Optional<Record::Kind> next_section = Record::classify(line); + if (next_section == Record::Line) { + // Line records logically belong to the preceding Func record, so we put + // them in the same section. + next_section = Record::Func; } - if (token == current_section) + if (next_section == current_section) continue; // Changing sections, finish off the previous one, if there was any. maybe_add_section(line.bytes_begin()); // And start a new one. - current_section = token; + current_section = next_section; section_start = line.bytes_begin() - m_data.GetDataStart(); } // Finally, add the last section.
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h index ba2a3ad..e8885e0 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h
@@ -1,9 +1,8 @@ //===-- ObjectFileBreakpad.h ---------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,16 +11,13 @@ #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/ArchSpec.h" -#include "llvm/ADT/Triple.h" namespace lldb_private { namespace breakpad { class ObjectFileBreakpad : public ObjectFile { public: - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -47,16 +43,12 @@ lldb::offset_t length, ModuleSpecList &specs); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------------ // ObjectFile Protocol. - //------------------------------------------------------------------ bool ParseHeader() override; @@ -84,7 +76,7 @@ ArchSpec GetArchitecture() override { return m_arch; } - bool GetUUID(UUID *uuid) override; + UUID GetUUID() override { return m_uuid; } FileSpecList GetDebugSymbolFilePaths() override { return FileSpecList(); }
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp index 3d47352..aa98710 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp
@@ -1,9 +1,8 @@ //===-- ELFHeader.cpp ----------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,7 +18,6 @@ using namespace lldb; using namespace llvm::ELF; -//------------------------------------------------------------------------------ // Static utility functions. // // GetMaxU64 and GetMaxS64 wrap the similarly named methods from DataExtractor @@ -68,7 +66,6 @@ return true; } -//------------------------------------------------------------------------------ // ELFHeader ELFHeader::ELFHeader() { memset(this, 0, sizeof(ELFHeader)); } @@ -117,7 +114,7 @@ bool ELFHeader::Parse(lldb_private::DataExtractor &data, lldb::offset_t *offset) { // Read e_ident. This provides byte order and address size info. - if (data.GetU8(offset, &e_ident, EI_NIDENT) == NULL) + if (data.GetU8(offset, &e_ident, EI_NIDENT) == nullptr) return false; const unsigned byte_size = Is32Bit() ? 4 : 8; @@ -125,11 +122,11 @@ data.SetAddressByteSize(byte_size); // Read e_type and e_machine. - if (data.GetU16(offset, &e_type, 2) == NULL) + if (data.GetU16(offset, &e_type, 2) == nullptr) return false; // Read e_version. - if (data.GetU32(offset, &e_version, 1) == NULL) + if (data.GetU32(offset, &e_version, 1) == nullptr) return false; // Read e_entry, e_phoff and e_shoff. @@ -137,11 +134,11 @@ return false; // Read e_flags. - if (data.GetU32(offset, &e_flags, 1) == NULL) + if (data.GetU32(offset, &e_flags, 1) == nullptr) return false; // Read e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum and e_shstrndx. - if (data.GetU16(offset, &e_ehsize, 6) == NULL) + if (data.GetU16(offset, &e_ehsize, 6) == nullptr) return false; // Initialize e_phnum, e_shnum, and e_shstrndx with the values read from the @@ -216,7 +213,6 @@ return slot; } -//------------------------------------------------------------------------------ // ELFSectionHeader ELFSectionHeader::ELFSectionHeader() { @@ -228,7 +224,7 @@ const unsigned byte_size = data.GetAddressByteSize(); // Read sh_name and sh_type. - if (data.GetU32(offset, &sh_name, 2) == NULL) + if (data.GetU32(offset, &sh_name, 2) == nullptr) return false; // Read sh_flags. @@ -240,7 +236,7 @@ return false; // Read sh_link and sh_info. - if (data.GetU32(offset, &sh_link, 2) == NULL) + if (data.GetU32(offset, &sh_link, 2) == nullptr) return false; // Read sh_addralign and sh_entsize. @@ -250,7 +246,6 @@ return true; } -//------------------------------------------------------------------------------ // ELFSymbol ELFSymbol::ELFSymbol() { memset(this, 0, sizeof(ELFSymbol)); } @@ -327,7 +322,7 @@ const bool parsing_32 = byte_size == 4; // Read st_name. - if (data.GetU32(offset, &st_name, 1) == NULL) + if (data.GetU32(offset, &st_name, 1) == nullptr) return false; if (parsing_32) { @@ -336,29 +331,28 @@ return false; // Read st_info and st_other. - if (data.GetU8(offset, &st_info, 2) == NULL) + if (data.GetU8(offset, &st_info, 2) == nullptr) return false; // Read st_shndx. - if (data.GetU16(offset, &st_shndx, 1) == NULL) + if (data.GetU16(offset, &st_shndx, 1) == nullptr) return false; } else { // Read st_info and st_other. - if (data.GetU8(offset, &st_info, 2) == NULL) + if (data.GetU8(offset, &st_info, 2) == nullptr) return false; // Read st_shndx. - if (data.GetU16(offset, &st_shndx, 1) == NULL) + if (data.GetU16(offset, &st_shndx, 1) == nullptr) return false; // Read st_value and st_size. - if (data.GetU64(offset, &st_value, 2) == NULL) + if (data.GetU64(offset, &st_value, 2) == nullptr) return false; } return true; } -//------------------------------------------------------------------------------ // ELFProgramHeader ELFProgramHeader::ELFProgramHeader() { @@ -371,7 +365,7 @@ const bool parsing_32 = byte_size == 4; // Read p_type; - if (data.GetU32(offset, &p_type, 1) == NULL) + if (data.GetU32(offset, &p_type, 1) == nullptr) return false; if (parsing_32) { @@ -380,7 +374,7 @@ return false; // Read p_flags. - if (data.GetU32(offset, &p_flags, 1) == NULL) + if (data.GetU32(offset, &p_flags, 1) == nullptr) return false; // Read p_align. @@ -388,7 +382,7 @@ return false; } else { // Read p_flags. - if (data.GetU32(offset, &p_flags, 1) == NULL) + if (data.GetU32(offset, &p_flags, 1) == nullptr) return false; // Read p_offset, p_vaddr, p_paddr, p_filesz, p_memsz and p_align. @@ -399,7 +393,6 @@ return true; } -//------------------------------------------------------------------------------ // ELFDynamic ELFDynamic::ELFDynamic() { memset(this, 0, sizeof(ELFDynamic)); } @@ -410,7 +403,6 @@ return GetMaxS64(data, offset, &d_tag, byte_size, 2); } -//------------------------------------------------------------------------------ // ELFRel ELFRel::ELFRel() { memset(this, 0, sizeof(ELFRel)); } @@ -423,7 +415,6 @@ return GetMaxU64(data, offset, &r_offset, byte_size, 2) != false; } -//------------------------------------------------------------------------------ // ELFRela ELFRela::ELFRela() { memset(this, 0, sizeof(ELFRela)); }
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.h index faaf8be..bb228e2 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.h
@@ -1,13 +1,12 @@ //===-- ELFHeader.h ------------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // -/// @file +/// \file /// Generic structures and typedefs for ELF files. /// /// This file provides definitions for the various entities comprising an ELF @@ -32,8 +31,7 @@ namespace elf { -//------------------------------------------------------------------------------ -/// @name ELF type definitions. +/// \name ELF type definitions. /// /// Types used to represent the various components of ELF structures. All /// types are signed or unsigned integral types wide enough to hold values @@ -50,8 +48,7 @@ typedef int64_t elf_sxword; //@} -//------------------------------------------------------------------------------ -/// @class ELFHeader +/// \class ELFHeader /// Generic representation of an ELF file header. /// /// This object is used to identify the general attributes on an ELF file and @@ -81,93 +78,83 @@ ELFHeader(); - //-------------------------------------------------------------------------- /// Returns true if this is a 32 bit ELF file header. /// - /// @return + /// \return /// True if this is a 32 bit ELF file header. bool Is32Bit() const { return e_ident[llvm::ELF::EI_CLASS] == llvm::ELF::ELFCLASS32; } - //-------------------------------------------------------------------------- /// Returns true if this is a 64 bit ELF file header. /// - /// @return + /// \return /// True if this is a 64 bit ELF file header. bool Is64Bit() const { return e_ident[llvm::ELF::EI_CLASS] == llvm::ELF::ELFCLASS64; } - //-------------------------------------------------------------------------- /// The byte order of this ELF file header. /// - /// @return + /// \return /// The byte order of this ELF file as described by the header. lldb::ByteOrder GetByteOrder() const; - //-------------------------------------------------------------------------- /// The jump slot relocation type of this ELF. unsigned GetRelocationJumpSlotType() const; - //-------------------------------------------------------------------------- /// Check if there should be header extension in section header #0 /// - /// @return + /// \return /// True if parsing the ELFHeader requires reading header extension /// and false otherwise. bool HasHeaderExtension() const; - //-------------------------------------------------------------------------- /// Parse an ELFHeader entry starting at position \p offset and update the /// data extractor with the address size and byte order attributes as /// defined by the header. /// - /// @param[in,out] data + /// \param[in,out] data /// The DataExtractor to read from. Updated with the address size and /// byte order attributes appropriate to this header. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFHeader was successfully read and false /// otherwise. bool Parse(lldb_private::DataExtractor &data, lldb::offset_t *offset); - //-------------------------------------------------------------------------- /// Examines at most EI_NIDENT bytes starting from the given pointer and /// determines if the magic ELF identification exists. /// - /// @return + /// \return /// True if the given sequence of bytes identifies an ELF file. static bool MagicBytesMatch(const uint8_t *magic); - //-------------------------------------------------------------------------- /// Examines at most EI_NIDENT bytes starting from the given address and /// determines the address size of the underlying ELF file. This function /// should only be called on an pointer for which MagicBytesMatch returns /// true. /// - /// @return + /// \return /// The number of bytes forming an address in the ELF file (either 4 or /// 8), else zero if the address size could not be determined. static unsigned AddressSizeInBytes(const uint8_t *magic); private: - //-------------------------------------------------------------------------- /// Parse an ELFHeader header extension entry. This method is called by /// Parse(). /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. void ParseHeaderExtension(lldb_private::DataExtractor &data); }; -//------------------------------------------------------------------------------ -/// @class ELFSectionHeader +/// \class ELFSectionHeader /// Generic representation of an ELF section header. struct ELFSectionHeader { elf_word sh_name; ///< Section name string index. @@ -183,26 +170,24 @@ ELFSectionHeader(); - //-------------------------------------------------------------------------- /// Parse an ELFSectionHeader entry from the given DataExtracter starting at /// position \p offset. /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. The address size of the extractor /// determines if a 32 or 64 bit object should be read. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFSectionHeader was successfully read and false /// otherwise. bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); }; -//------------------------------------------------------------------------------ -/// @class ELFProgramHeader +/// \class ELFProgramHeader /// Generic representation of an ELF program header. struct ELFProgramHeader { elf_word p_type; ///< Type of program segment. @@ -220,22 +205,21 @@ /// position \p offset. The address size of the DataExtractor determines if /// a 32 or 64 bit object is to be parsed. /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. The address size of the extractor /// determines if a 32 or 64 bit object should be read. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFProgramHeader was successfully read and false /// otherwise. bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); }; -//------------------------------------------------------------------------------ -/// @class ELFSymbol +/// \class ELFSymbol /// Represents a symbol within an ELF symbol table. struct ELFSymbol { elf_addr st_value; ///< Absolute or relocatable address. @@ -270,15 +254,15 @@ /// position \p offset. The address size of the DataExtractor determines if /// a 32 or 64 bit object is to be parsed. /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. The address size of the extractor /// determines if a 32 or 64 bit object should be read. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFSymbol was successfully read and false otherwise. bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); @@ -287,8 +271,7 @@ const lldb_private::SectionList *section_list); }; -//------------------------------------------------------------------------------ -/// @class ELFDynamic +/// \class ELFDynamic /// Represents an entry in an ELF dynamic table. struct ELFDynamic { elf_sxword d_tag; ///< Type of dynamic table entry. @@ -303,22 +286,21 @@ /// position \p offset. The address size of the DataExtractor determines if /// a 32 or 64 bit object is to be parsed. /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. The address size of the extractor /// determines if a 32 or 64 bit object should be read. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFDynamic entry was successfully read and false /// otherwise. bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); }; -//------------------------------------------------------------------------------ -/// @class ELFRel +/// \class ELFRel /// Represents a relocation entry with an implicit addend. struct ELFRel { elf_addr r_offset; ///< Address of reference. @@ -330,15 +312,15 @@ /// \p offset. The address size of the DataExtractor determines if a 32 or /// 64 bit object is to be parsed. /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. The address size of the extractor /// determines if a 32 or 64 bit object should be read. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFRel entry was successfully read and false otherwise. bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); @@ -359,8 +341,7 @@ static unsigned RelocSymbol64(const ELFRel &rel) { return rel.r_info >> 32; } }; -//------------------------------------------------------------------------------ -/// @class ELFRela +/// \class ELFRela /// Represents a relocation entry with an explicit addend. struct ELFRela { elf_addr r_offset; ///< Address of reference. @@ -373,15 +354,15 @@ /// \p offset. The address size of the DataExtractor determines if a 32 or /// 64 bit object is to be parsed. /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. The address size of the extractor /// determines if a 32 or 64 bit object should be read. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFRela entry was successfully read and false otherwise. bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp index 9a6563a..d62afa3 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp
@@ -1,9 +1,8 @@ //===-- ObjectFileELF.cpp ------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,7 +16,6 @@ #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/RangeMap.h" #include "lldb/Core/Section.h" #include "lldb/Host/FileSystem.h" #include "lldb/Symbol/DWARFCallFrameInfo.h" @@ -27,6 +25,7 @@ #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/RangeMap.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/Timer.h" @@ -56,8 +55,8 @@ const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD"; const char *const LLDB_NT_OWNER_GNU = "GNU"; const char *const LLDB_NT_OWNER_NETBSD = "NetBSD"; +const char *const LLDB_NT_OWNER_NETBSDCORE = "NetBSD-CORE"; const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD"; -const char *const LLDB_NT_OWNER_CSR = "csr"; const char *const LLDB_NT_OWNER_ANDROID = "Android"; const char *const LLDB_NT_OWNER_CORE = "CORE"; const char *const LLDB_NT_OWNER_LINUX = "LINUX"; @@ -71,8 +70,10 @@ const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03; -const elf_word LLDB_NT_NETBSD_ABI_TAG = 0x01; -const elf_word LLDB_NT_NETBSD_ABI_SIZE = 4; +const elf_word LLDB_NT_NETBSD_IDENT_TAG = 1; +const elf_word LLDB_NT_NETBSD_IDENT_DESCSZ = 4; +const elf_word LLDB_NT_NETBSD_IDENT_NAMESZ = 7; +const elf_word LLDB_NT_NETBSD_PROCINFO = 1; // GNU ABI note OS constants const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00; @@ -115,7 +116,7 @@ #define NT_METAG_TLS 0x502 //===----------------------------------------------------------------------===// -/// @class ELFRelocation +/// \class ELFRelocation /// Generic wrapper for ELFRel and ELFRela. /// /// This helper class allows us to parse both ELFRel and ELFRela relocation @@ -125,7 +126,7 @@ /// Constructs an ELFRelocation entry with a personality as given by @p /// type. /// - /// @param type Either DT_REL or DT_RELA. Any other value is invalid. + /// \param type Either DT_REL or DT_RELA. Any other value is invalid. ELFRelocation(unsigned type); ~ELFRelocation(); @@ -161,7 +162,7 @@ reloc = new ELFRela(); else { assert(false && "unexpected relocation type"); - reloc = static_cast<ELFRel *>(NULL); + reloc = static_cast<ELFRel *>(nullptr); } } @@ -242,7 +243,7 @@ bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) { // Read all fields. - if (data.GetU32(offset, &n_namesz, 3) == NULL) + if (data.GetU32(offset, &n_namesz, 3) == nullptr) return false; // The name field is required to be nul-terminated, and n_namesz includes the @@ -261,7 +262,7 @@ } const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4)); - if (cstr == NULL) { + if (cstr == nullptr) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS)); if (log) log->Printf("Failed to parse note name lacking nul terminator"); @@ -272,27 +273,6 @@ return true; } -static uint32_t kalimbaVariantFromElfFlags(const elf::elf_word e_flags) { - const uint32_t dsp_rev = e_flags & 0xFF; - uint32_t kal_arch_variant = LLDB_INVALID_CPUTYPE; - switch (dsp_rev) { - // TODO(mg11) Support more variants - case 10: - kal_arch_variant = llvm::Triple::KalimbaSubArch_v3; - break; - case 14: - kal_arch_variant = llvm::Triple::KalimbaSubArch_v4; - break; - case 17: - case 20: - kal_arch_variant = llvm::Triple::KalimbaSubArch_v5; - break; - default: - break; - } - return kal_arch_variant; -} - static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) { const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH; uint32_t endian = header.e_ident[EI_DATA]; @@ -350,40 +330,13 @@ if (header.e_machine == llvm::ELF::EM_MIPS) return mipsVariantFromElfFlags(header); - return llvm::ELF::EM_CSR_KALIMBA == header.e_machine - ? kalimbaVariantFromElfFlags(header.e_flags) - : LLDB_INVALID_CPUTYPE; -} - -//! The kalimba toolchain identifies a code section as being -//! one with the SHT_PROGBITS set in the section sh_type and the top -//! bit in the 32-bit address field set. -static lldb::SectionType -kalimbaSectionType(const elf::ELFHeader &header, - const elf::ELFSectionHeader §_hdr) { - if (llvm::ELF::EM_CSR_KALIMBA != header.e_machine) { - return eSectionTypeOther; - } - - if (llvm::ELF::SHT_NOBITS == sect_hdr.sh_type) { - return eSectionTypeZeroFill; - } - - if (llvm::ELF::SHT_PROGBITS == sect_hdr.sh_type) { - const lldb::addr_t KAL_CODE_BIT = 1 << 31; - return KAL_CODE_BIT & sect_hdr.sh_addr ? eSectionTypeCode - : eSectionTypeData; - } - - return eSectionTypeOther; + return LLDB_INVALID_CPUTYPE; } // Arbitrary constant used as UUID prefix for core files. const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C); -//------------------------------------------------------------------ // Static methods. -//------------------------------------------------------------------ void ObjectFileELF::Initialize() { PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance, @@ -436,14 +389,14 @@ unsigned address_size = ELFHeader::AddressSizeInBytes(magic); if (address_size == 4 || address_size == 8) { - std::unique_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF( + std::unique_ptr<ObjectFileELF> objfile_up(new ObjectFileELF( module_sp, data_sp, data_offset, file, file_offset, length)); - ArchSpec spec = objfile_ap->GetArchitecture(); - if (spec && objfile_ap->SetModulesArchitecture(spec)) - return objfile_ap.release(); + ArchSpec spec = objfile_up->GetArchitecture(); + if (spec && objfile_up->SetModulesArchitecture(spec)) + return objfile_up.release(); } - return NULL; + return nullptr; } ObjectFile *ObjectFileELF::CreateMemoryInstance( @@ -454,15 +407,15 @@ if (ELFHeader::MagicBytesMatch(magic)) { unsigned address_size = ELFHeader::AddressSizeInBytes(magic); if (address_size == 4 || address_size == 8) { - std::unique_ptr<ObjectFileELF> objfile_ap( + std::unique_ptr<ObjectFileELF> objfile_up( new ObjectFileELF(module_sp, data_sp, process_sp, header_addr)); - ArchSpec spec = objfile_ap->GetArchitecture(); - if (spec && objfile_ap->SetModulesArchitecture(spec)) - return objfile_ap.release(); + ArchSpec spec = objfile_up->GetArchitecture(); + if (spec && objfile_up->SetModulesArchitecture(spec)) + return objfile_up.release(); } } } - return NULL; + return nullptr; } bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp, @@ -756,17 +709,13 @@ return specs.GetSize() - initial_count; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ObjectFileELF::GetPluginName() { return GetPluginNameStatic(); } uint32_t ObjectFileELF::GetPluginVersion() { return m_plugin_version; } -//------------------------------------------------------------------ // ObjectFile protocol -//------------------------------------------------------------------ ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp, DataBufferSP &data_sp, lldb::offset_t data_offset, @@ -775,7 +724,7 @@ : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset), m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0), m_program_headers(), m_section_headers(), m_dynamic_symbols(), - m_filespec_ap(), m_entry_point_address(), m_arch_spec() { + m_filespec_up(), m_entry_point_address(), m_arch_spec() { if (file) m_file = *file; ::memset(&m_header, 0, sizeof(m_header)); @@ -788,7 +737,7 @@ : ObjectFile(module_sp, process_sp, header_addr, header_data_sp), m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0), m_program_headers(), m_section_headers(), m_dynamic_symbols(), - m_filespec_ap(), m_entry_point_address(), m_arch_spec() { + m_filespec_up(), m_entry_point_address(), m_arch_spec() { ::memset(&m_header, 0, sizeof(m_header)); } @@ -897,49 +846,43 @@ return m_header.Parse(m_data, &offset); } -bool ObjectFileELF::GetUUID(lldb_private::UUID *uuid) { +UUID ObjectFileELF::GetUUID() { // Need to parse the section list to get the UUIDs, so make sure that's been // done. if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile) - return false; + return UUID(); - using u32le = llvm::support::ulittle32_t; - if (m_uuid.IsValid()) { - // We have the full build id uuid. - *uuid = m_uuid; - return true; - } else if (GetType() == ObjectFile::eTypeCoreFile) { - uint32_t core_notes_crc = 0; + if (!m_uuid) { + using u32le = llvm::support::ulittle32_t; + if (GetType() == ObjectFile::eTypeCoreFile) { + uint32_t core_notes_crc = 0; - if (!ParseProgramHeaders()) - return false; + if (!ParseProgramHeaders()) + return UUID(); - core_notes_crc = CalculateELFNotesSegmentsCRC32(m_program_headers, m_data); + core_notes_crc = + CalculateELFNotesSegmentsCRC32(m_program_headers, m_data); - if (core_notes_crc) { - // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it look - // different form .gnu_debuglink crc - followed by 4 bytes of note - // segments crc. - u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)}; - m_uuid = UUID::fromData(data, sizeof(data)); - } - } else { - if (!m_gnu_debuglink_crc) - m_gnu_debuglink_crc = - calc_gnu_debuglink_crc32(m_data.GetDataStart(), m_data.GetByteSize()); - if (m_gnu_debuglink_crc) { - // Use 4 bytes of crc from the .gnu_debuglink section. - u32le data(m_gnu_debuglink_crc); - m_uuid = UUID::fromData(&data, sizeof(data)); + if (core_notes_crc) { + // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it + // look different form .gnu_debuglink crc - followed by 4 bytes of note + // segments crc. + u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)}; + m_uuid = UUID::fromData(data, sizeof(data)); + } + } else { + if (!m_gnu_debuglink_crc) + m_gnu_debuglink_crc = calc_gnu_debuglink_crc32(m_data.GetDataStart(), + m_data.GetByteSize()); + if (m_gnu_debuglink_crc) { + // Use 4 bytes of crc from the .gnu_debuglink section. + u32le data(m_gnu_debuglink_crc); + m_uuid = UUID::fromData(&data, sizeof(data)); + } } } - if (m_uuid.IsValid()) { - *uuid = m_uuid; - return true; - } - - return false; + return m_uuid; } lldb_private::FileSpecList ObjectFileELF::GetDebugSymbolFilePaths() { @@ -957,7 +900,7 @@ uint32_t num_specs = 0; for (unsigned i = 0; i < num_modules; ++i) { - if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i))) + if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i))) num_specs++; } @@ -1060,14 +1003,12 @@ return LLDB_INVALID_ADDRESS; } -//---------------------------------------------------------------------- // ParseDependentModules -//---------------------------------------------------------------------- size_t ObjectFileELF::ParseDependentModules() { - if (m_filespec_ap.get()) - return m_filespec_ap->GetSize(); + if (m_filespec_up) + return m_filespec_up->GetSize(); - m_filespec_ap.reset(new FileSpecList()); + m_filespec_up.reset(new FileSpecList()); if (!ParseSectionHeaders()) return 0; @@ -1114,16 +1055,14 @@ const char *lib_name = dynstr_data.PeekCStr(str_index); FileSpec file_spec(lib_name); FileSystem::Instance().Resolve(file_spec); - m_filespec_ap->Append(file_spec); + m_filespec_up->Append(file_spec); } } - return m_filespec_ap->GetSize(); + return m_filespec_up->GetSize(); } -//---------------------------------------------------------------------- // GetProgramHeaderInfo -//---------------------------------------------------------------------- size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers, DataExtractor &object_data, const ELFHeader &header) { @@ -1158,9 +1097,7 @@ return program_headers.size(); } -//---------------------------------------------------------------------- // ParseProgramHeaders -//---------------------------------------------------------------------- bool ObjectFileELF::ParseProgramHeaders() { return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0; } @@ -1301,46 +1238,45 @@ // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); } - // Process NetBSD ELF notes. + // Process NetBSD ELF executables and shared libraries else if ((note.n_name == LLDB_NT_OWNER_NETBSD) && - (note.n_type == LLDB_NT_NETBSD_ABI_TAG) && - (note.n_descsz == LLDB_NT_NETBSD_ABI_SIZE)) { - // Pull out the min version info. + (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) && + (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) && + (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) { + // Pull out the version info. uint32_t version_info; if (data.GetU32(&offset, &version_info, 1) == nullptr) { error.SetErrorString("failed to read NetBSD ABI note payload"); return error; } - + // Convert the version info into a major/minor/patch number. + // #define __NetBSD_Version__ MMmmrrpp00 + // + // M = major version + // m = minor version; a minor number of 99 indicates current. + // r = 0 (since NetBSD 3.0 not used) + // p = patchlevel + const uint32_t version_major = version_info / 100000000; + const uint32_t version_minor = (version_info % 100000000) / 1000000; + const uint32_t version_patch = (version_info % 10000) / 100; + // Set the elf OS version to NetBSD. Also clear the vendor. + arch_spec.GetTriple().setOSName( + llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor, + version_patch).str()); + arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor); + } + // Process NetBSD ELF core(5) notes + else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) && + (note.n_type == LLDB_NT_NETBSD_PROCINFO)) { // Set the elf OS version to NetBSD. Also clear the vendor. arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD); arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor); - - if (log) - log->Printf( - "ObjectFileELF::%s detected NetBSD, min version constant %" PRIu32, - __FUNCTION__, version_info); } // Process OpenBSD ELF notes. else if (note.n_name == LLDB_NT_OWNER_OPENBSD) { // Set the elf OS version to OpenBSD. Also clear the vendor. arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD); arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor); - } - // Process CSR kalimba notes - else if ((note.n_type == LLDB_NT_GNU_ABI_TAG) && - (note.n_name == LLDB_NT_OWNER_CSR)) { - arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS); - arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::CSR); - - // TODO At some point the description string could be processed. - // It could provide a steer towards the kalimba variant which this ELF - // targets. - if (note.n_descsz) { - const char *cstr = - data.GetCStr(&offset, llvm::alignTo(note.n_descsz, 4)); - (void)cstr; - } } else if (note.n_name == LLDB_NT_OWNER_ANDROID) { arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); arch_spec.GetTriple().setEnvironment( @@ -1354,8 +1290,6 @@ // the contents look like this in a 64 bit ELF core file: count = // 0x000000000000000a (10) page_size = 0x0000000000001000 (4096) Index // start end file_ofs path ===== - // ------------------ ------------------ ------------------ - // ------------------------------------- [ 0] 0x0000000000400000 // 0x0000000000401000 0x0000000000000000 /tmp/a.out [ 1] // 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out [ // 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out @@ -1479,9 +1413,7 @@ } } -//---------------------------------------------------------------------- // GetSectionHeaderInfo -//---------------------------------------------------------------------- size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl §ion_headers, DataExtractor &object_data, const elf::ELFHeader &header, @@ -1714,9 +1646,7 @@ return symbol_name.substr(0, pos); } -//---------------------------------------------------------------------- // ParseSectionHeaders -//---------------------------------------------------------------------- size_t ObjectFileELF::ParseSectionHeaders() { return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid, m_gnu_debuglink_file, m_gnu_debuglink_crc, @@ -1726,12 +1656,12 @@ const ObjectFileELF::ELFSectionHeaderInfo * ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) { if (!ParseSectionHeaders()) - return NULL; + return nullptr; if (id < m_section_headers.size()) return &m_section_headers[id]; - return NULL; + return nullptr; } lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) { @@ -1744,37 +1674,40 @@ } static SectionType GetSectionTypeFromName(llvm::StringRef Name) { + if (Name.consume_front(".debug_") || Name.consume_front(".zdebug_")) { + return llvm::StringSwitch<SectionType>(Name) + .Case("abbrev", eSectionTypeDWARFDebugAbbrev) + .Case("abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo) + .Case("addr", eSectionTypeDWARFDebugAddr) + .Case("aranges", eSectionTypeDWARFDebugAranges) + .Case("cu_index", eSectionTypeDWARFDebugCuIndex) + .Case("frame", eSectionTypeDWARFDebugFrame) + .Case("info", eSectionTypeDWARFDebugInfo) + .Case("info.dwo", eSectionTypeDWARFDebugInfoDwo) + .Cases("line", "line.dwo", eSectionTypeDWARFDebugLine) + .Cases("line_str", "line_str.dwo", eSectionTypeDWARFDebugLineStr) + .Cases("loc", "loc.dwo", eSectionTypeDWARFDebugLoc) + .Cases("loclists", "loclists.dwo", eSectionTypeDWARFDebugLocLists) + .Case("macinfo", eSectionTypeDWARFDebugMacInfo) + .Cases("macro", "macro.dwo", eSectionTypeDWARFDebugMacro) + .Case("names", eSectionTypeDWARFDebugNames) + .Case("pubnames", eSectionTypeDWARFDebugPubNames) + .Case("pubtypes", eSectionTypeDWARFDebugPubTypes) + .Case("ranges", eSectionTypeDWARFDebugRanges) + .Case("rnglists", eSectionTypeDWARFDebugRngLists) + .Case("str", eSectionTypeDWARFDebugStr) + .Case("str.dwo", eSectionTypeDWARFDebugStrDwo) + .Case("str_offsets", eSectionTypeDWARFDebugStrOffsets) + .Case("str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo) + .Case("types", eSectionTypeDWARFDebugTypes) + .Case("types.dwo", eSectionTypeDWARFDebugTypesDwo) + .Default(eSectionTypeOther); + } return llvm::StringSwitch<SectionType>(Name) .Case(".ARM.exidx", eSectionTypeARMexidx) .Case(".ARM.extab", eSectionTypeARMextab) .Cases(".bss", ".tbss", eSectionTypeZeroFill) .Cases(".data", ".tdata", eSectionTypeData) - .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev) - .Case(".debug_abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo) - .Case(".debug_addr", eSectionTypeDWARFDebugAddr) - .Case(".debug_aranges", eSectionTypeDWARFDebugAranges) - .Case(".debug_cu_index", eSectionTypeDWARFDebugCuIndex) - .Case(".debug_frame", eSectionTypeDWARFDebugFrame) - .Case(".debug_info", eSectionTypeDWARFDebugInfo) - .Case(".debug_info.dwo", eSectionTypeDWARFDebugInfoDwo) - .Cases(".debug_line", ".debug_line.dwo", eSectionTypeDWARFDebugLine) - .Cases(".debug_line_str", ".debug_line_str.dwo", - eSectionTypeDWARFDebugLineStr) - .Cases(".debug_loc", ".debug_loc.dwo", eSectionTypeDWARFDebugLoc) - .Cases(".debug_loclists", ".debug_loclists.dwo", - eSectionTypeDWARFDebugLocLists) - .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo) - .Cases(".debug_macro", ".debug_macro.dwo", eSectionTypeDWARFDebugMacro) - .Case(".debug_names", eSectionTypeDWARFDebugNames) - .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames) - .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes) - .Case(".debug_ranges", eSectionTypeDWARFDebugRanges) - .Case(".debug_rnglists", eSectionTypeDWARFDebugRngLists) - .Case(".debug_str", eSectionTypeDWARFDebugStr) - .Case(".debug_str.dwo", eSectionTypeDWARFDebugStrDwo) - .Case(".debug_str_offsets", eSectionTypeDWARFDebugStrOffsets) - .Case(".debug_str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo) - .Case(".debug_types", eSectionTypeDWARFDebugTypes) .Case(".eh_frame", eSectionTypeEHFrame) .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink) .Case(".gosymtab", eSectionTypeGoSymtab) @@ -1798,14 +1731,7 @@ case SHT_DYNAMIC: return eSectionTypeELFDynamicLinkInfo; } - SectionType Type = GetSectionTypeFromName(H.section_name.GetStringRef()); - if (Type == eSectionTypeOther) { - // the kalimba toolchain assumes that ELF section names are free-form. - // It does support linkscripts which (can) give rise to various - // arbitrarily named sections being "Code" or "Data". - Type = kalimbaSectionType(m_header, H); - } - return Type; + return GetSectionTypeFromName(H.section_name.GetStringRef()); } static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) { @@ -1938,11 +1864,11 @@ } void ObjectFileELF::CreateSections(SectionList &unified_section_list) { - if (m_sections_ap) + if (m_sections_up) return; - m_sections_ap = llvm::make_unique<SectionList>(); - VMAddressProvider address_provider(CalculateType()); + m_sections_up = llvm::make_unique<SectionList>(); + VMAddressProvider address_provider(GetType()); size_t LoadID = 0; for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) { @@ -1961,7 +1887,7 @@ eSectionTypeContainer, InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset, PHdr.p_filesz, Log2Align, /*flags*/ 0); Segment->SetPermissions(GetPermissions(PHdr)); - m_sections_ap->AddSection(Segment); + m_sections_up->AddSection(Segment); address_provider.AddSegment(*InfoOr, std::move(Segment)); } @@ -2007,7 +1933,7 @@ section_sp->SetPermissions(GetPermissions(header)); section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS); - (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_ap) + (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up) .AddSection(section_sp); address_provider.AddSection(std::move(*InfoOr), std::move(section_sp)); } @@ -2015,7 +1941,7 @@ // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the // unified section list. if (GetType() != eTypeDebugInfo) - unified_section_list = *m_sections_ap; + unified_section_list = *m_sections_up; } // Find the arm/aarch64 mapping symbol character in the given symbol name. @@ -2073,8 +1999,8 @@ // custom extension and file name makes it highly unlikely that this will // collide with anything else. ConstString file_extension = m_file.GetFileNameExtension(); - bool skip_oatdata_oatexec = file_extension == ConstString(".oat") || - file_extension == ConstString(".odex"); + bool skip_oatdata_oatexec = + file_extension == ".oat" || file_extension == ".odex"; ArchSpec arch = GetArchitecture(); ModuleSP module_sp(GetModule()); @@ -2166,7 +2092,7 @@ if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) { if (symbol_section_sp) { - const ConstString §_name = symbol_section_sp->GetName(); + ConstString sect_name = symbol_section_sp->GetName(); if (sect_name == text_section_name || sect_name == init_section_name || sect_name == fini_section_name || sect_name == ctors_section_name || sect_name == dtors_section_name) { @@ -2262,11 +2188,7 @@ * class * accordingly. */ - const llvm::Triple::ArchType llvm_arch = arch.GetMachine(); - if (llvm_arch == llvm::Triple::mips || - llvm_arch == llvm::Triple::mipsel || - llvm_arch == llvm::Triple::mips64 || - llvm_arch == llvm::Triple::mips64el) { + if (arch.IsMIPS()) { if (IS_MICROMIPS(symbol.st_other)) m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA; else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) { @@ -2310,7 +2232,7 @@ if (symbol_section_sp && module_section_list && module_section_list != section_list) { - const ConstString §_name = symbol_section_sp->GetName(); + ConstString sect_name = symbol_section_sp->GetName(); auto section_it = section_name_to_section.find(sect_name.GetCString()); if (section_it == section_name_to_section.end()) section_it = @@ -2391,7 +2313,7 @@ } // Get section list for this object file. - SectionList *section_list = m_sections_ap.get(); + SectionList *section_list = m_sections_up.get(); if (!section_list) return 0; @@ -2457,7 +2379,7 @@ const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) { if (!ParseDynamicSymbols()) - return NULL; + return nullptr; DynamicSymbolCollIter I = m_dynamic_symbols.begin(); DynamicSymbolCollIter E = m_dynamic_symbols.end(); @@ -2468,7 +2390,7 @@ return symbol; } - return NULL; + return nullptr; } unsigned ObjectFileELF::PLTRelocationType() { @@ -2619,7 +2541,7 @@ if (!sym_hdr) return 0; - SectionList *section_list = m_sections_ap.get(); + SectionList *section_list = m_sections_up.get(); if (!section_list) return 0; @@ -2685,7 +2607,7 @@ if (!rel.Parse(rel_data, &offset)) break; - Symbol *symbol = NULL; + Symbol *symbol = nullptr; if (hdr->Is32Bit()) { switch (reloc_type(rel)) { @@ -2804,7 +2726,7 @@ Symtab *ObjectFileELF::GetSymtab() { ModuleSP module_sp(GetModule()); if (!module_sp) - return NULL; + return nullptr; // We always want to use the main object file so we (hopefully) only have one // cached copy of our symtab, dynamic sections, etc. @@ -2812,10 +2734,10 @@ if (module_obj_file && module_obj_file != this) return module_obj_file->GetSymtab(); - if (m_symtab_ap.get() == NULL) { + if (m_symtab_up == nullptr) { SectionList *section_list = module_sp->GetSectionList(); if (!section_list) - return NULL; + return nullptr; uint64_t symbol_id = 0; std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); @@ -2836,8 +2758,8 @@ .get(); } if (symtab) { - m_symtab_ap.reset(new Symtab(symtab->GetObjectFile())); - symbol_id += ParseSymbolTable(m_symtab_ap.get(), symbol_id, symtab); + m_symtab_up.reset(new Symtab(symtab->GetObjectFile())); + symbol_id += ParseSymbolTable(m_symtab_up.get(), symbol_id, symtab); } // DT_JMPREL @@ -2861,30 +2783,30 @@ GetSectionHeaderByIndex(reloc_id); assert(reloc_header); - if (m_symtab_ap == nullptr) - m_symtab_ap.reset(new Symtab(reloc_section->GetObjectFile())); + if (m_symtab_up == nullptr) + m_symtab_up.reset(new Symtab(reloc_section->GetObjectFile())); - ParseTrampolineSymbols(m_symtab_ap.get(), symbol_id, reloc_header, + ParseTrampolineSymbols(m_symtab_up.get(), symbol_id, reloc_header, reloc_id); } } - DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo(); - if (eh_frame) { - if (m_symtab_ap == nullptr) - m_symtab_ap.reset(new Symtab(this)); - ParseUnwindSymbols(m_symtab_ap.get(), eh_frame); + if (DWARFCallFrameInfo *eh_frame = + GetModule()->GetUnwindTable().GetEHFrameInfo()) { + if (m_symtab_up == nullptr) + m_symtab_up.reset(new Symtab(this)); + ParseUnwindSymbols(m_symtab_up.get(), eh_frame); } // If we still don't have any symtab then create an empty instance to avoid // do the section lookup next time. - if (m_symtab_ap == nullptr) - m_symtab_ap.reset(new Symtab(this)); + if (m_symtab_up == nullptr) + m_symtab_up.reset(new Symtab(this)); - m_symtab_ap->CalculateSymbolSizes(); + m_symtab_up->CalculateSymbolSizes(); } - return m_symtab_ap.get(); + return m_symtab_up.get(); } void ObjectFileELF::RelocateSection(lldb_private::Section *section) @@ -2991,7 +2913,6 @@ // // Dump the specifics of the runtime file container (such as any headers // segments, sections, etc). -//---------------------------------------------------------------------- void ObjectFileELF::Dump(Stream *s) { ModuleSP module_sp(GetModule()); if (!module_sp) { @@ -3016,20 +2937,18 @@ s->EOL(); SectionList *section_list = GetSectionList(); if (section_list) - section_list->Dump(s, NULL, true, UINT32_MAX); + section_list->Dump(s, nullptr, true, UINT32_MAX); Symtab *symtab = GetSymtab(); if (symtab) - symtab->Dump(s, NULL, eSortOrderNone); + symtab->Dump(s, nullptr, eSortOrderNone); s->EOL(); DumpDependentModules(s); s->EOL(); } -//---------------------------------------------------------------------- // DumpELFHeader // // Dump the ELF header to the specified output stream -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) { s->PutCString("ELF Header\n"); s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]); @@ -3062,11 +2981,9 @@ s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx); } -//---------------------------------------------------------------------- // DumpELFHeader_e_type // // Dump an token value for the ELF header member e_type -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) { switch (e_type) { case ET_NONE: @@ -3089,11 +3006,9 @@ } } -//---------------------------------------------------------------------- // DumpELFHeader_e_ident_EI_DATA // // Dump an token value for the ELF header member e_ident[EI_DATA] -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s, unsigned char ei_data) { switch (ei_data) { @@ -3111,11 +3026,9 @@ } } -//---------------------------------------------------------------------- // DumpELFProgramHeader // // Dump a single ELF program header to the specified output stream -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFProgramHeader(Stream *s, const ELFProgramHeader &ph) { DumpELFProgramHeader_p_type(s, ph.p_type); @@ -3128,12 +3041,10 @@ s->Printf(") %8.8" PRIx64, ph.p_align); } -//---------------------------------------------------------------------- // DumpELFProgramHeader_p_type // // Dump an token value for the ELF program header member p_type which describes // the type of the program header -// ---------------------------------------------------------------------- void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) { const int kStrWidth = 15; switch (p_type) { @@ -3152,11 +3063,9 @@ } } -//---------------------------------------------------------------------- // DumpELFProgramHeader_p_flags // // Dump an token value for the ELF program header member p_flags -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) { *s << ((p_flags & PF_X) ? "PF_X" : " ") << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ') @@ -3165,11 +3074,9 @@ << ((p_flags & PF_R) ? "PF_R" : " "); } -//---------------------------------------------------------------------- // DumpELFProgramHeaders // // Dump all of the ELF program header to the specified output stream -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFProgramHeaders(Stream *s) { if (!ParseProgramHeaders()) return; @@ -3187,11 +3094,9 @@ } } -//---------------------------------------------------------------------- // DumpELFSectionHeader // // Dump a single ELF section header to the specified output stream -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFSectionHeader(Stream *s, const ELFSectionHeaderInfo &sh) { s->Printf("%8.8x ", sh.sh_name); @@ -3204,12 +3109,10 @@ s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize); } -//---------------------------------------------------------------------- // DumpELFSectionHeader_sh_type // // Dump an token value for the ELF section header member sh_type which // describes the type of the section -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) { const int kStrWidth = 12; switch (sh_type) { @@ -3235,11 +3138,9 @@ } } -//---------------------------------------------------------------------- // DumpELFSectionHeader_sh_flags // // Dump an token value for the ELF section header member sh_flags -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, elf_xword sh_flags) { *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ") @@ -3249,11 +3150,9 @@ << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " "); } -//---------------------------------------------------------------------- // DumpELFSectionHeaders // // Dump all of the ELF section header to the specified output stream -//---------------------------------------------------------------------- void ObjectFileELF::DumpELFSectionHeaders(Stream *s) { if (!ParseSectionHeaders()) return; @@ -3283,7 +3182,7 @@ if (num_modules > 0) { s->PutCString("Dependent Modules:\n"); for (unsigned i = 0; i < num_modules; ++i) { - const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i); + const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i); s->Printf(" %s\n", spec.GetFilename().GetCString()); } } @@ -3299,7 +3198,7 @@ } if (CalculateType() == eTypeCoreFile && - m_arch_spec.TripleOSIsUnspecifiedUnknown()) { + !m_arch_spec.TripleOSWasSpecified()) { // Core files don't have section headers yet they have PT_NOTE program // headers that might shed more light on the architecture for (const elf::ELFProgramHeader &H : ProgramHeaders()) { @@ -3405,7 +3304,8 @@ return section->GetObjectFile()->ReadSectionData(section, section_data); size_t result = ObjectFile::ReadSectionData(section, section_data); - if (result == 0 || !section->Test(SHF_COMPRESSED)) + if (result == 0 || !llvm::object::Decompressor::isCompressedELFSection( + section->Get(), section->GetName().GetStringRef())) return result; auto Decompressor = llvm::object::Decompressor::create(
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h index 08fd5bdc..b63a5d1 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h
@@ -1,9 +1,8 @@ //===-- ObjectFileELF.h --------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -34,14 +33,14 @@ /// Parse an ELFNote entry from the given DataExtractor starting at position /// \p offset. /// - /// @param[in] data + /// \param[in] data /// The DataExtractor to read from. /// - /// @param[in,out] offset + /// \param[in,out] offset /// Pointer to an offset in the data. On return the offset will be /// advanced by the number of bytes read. /// - /// @return + /// \return /// True if the ELFRel entry was successfully read and false otherwise. bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); @@ -50,8 +49,7 @@ } }; -//------------------------------------------------------------------------------ -/// @class ObjectFileELF +/// \class ObjectFileELF /// Generic ELF object file reader. /// /// This class provides a generic ELF (32/64 bit) reader plugin implementing @@ -60,9 +58,7 @@ public: ~ObjectFileELF() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -90,16 +86,12 @@ static bool MagicBytesMatch(lldb::DataBufferSP &data_sp, lldb::addr_t offset, lldb::addr_t length); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - //------------------------------------------------------------------ // ObjectFile Protocol. - //------------------------------------------------------------------ bool ParseHeader() override; bool SetLoadAddress(lldb_private::Target &target, lldb::addr_t value, @@ -123,7 +115,7 @@ lldb_private::ArchSpec GetArchitecture() override; - bool GetUUID(lldb_private::UUID *uuid) override; + lldb_private::UUID GetUUID() override; lldb_private::FileSpecList GetDebugSymbolFilePaths() override; @@ -211,7 +203,7 @@ /// List of file specifications corresponding to the modules (shared /// libraries) on which this object file depends. - mutable std::unique_ptr<lldb_private::FileSpecList> m_filespec_ap; + mutable std::unique_ptr<lldb_private::FileSpecList> m_filespec_up; /// Cached value of the entry point for this module. lldb_private::Address m_entry_point_address; @@ -265,7 +257,7 @@ lldb_private::ArchSpec &arch_spec); /// Scans the dynamic section and locates all dependent modules (shared - /// libraries) populating m_filespec_ap. This method will compute the + /// libraries) populating m_filespec_up. This method will compute the /// dependent module list only once. Returns the number of dependent /// modules parsed. size_t ParseDependentModules(); @@ -275,7 +267,7 @@ /// number of dynamic symbols parsed. size_t ParseDynamicSymbols(); - /// Populates m_symtab_ap will all non-dynamic linker symbols. This method + /// Populates m_symtab_up will all non-dynamic linker symbols. This method /// will parse the symbols only once. Returns the number of symbols parsed. unsigned ParseSymbolTable(lldb_private::Symtab *symbol_table, lldb::user_id_t start_id, @@ -331,7 +323,7 @@ /// Returns the section header with the given id or NULL. const ELFSectionHeaderInfo *GetSectionHeaderByIndex(lldb::user_id_t id); - /// @name ELF header dump routines + /// \name ELF header dump routines //@{ static void DumpELFHeader(lldb_private::Stream *s, const elf::ELFHeader &header); @@ -343,7 +335,7 @@ elf::elf_half e_type); //@} - /// @name ELF program header dump routines + /// \name ELF program header dump routines //@{ void DumpELFProgramHeaders(lldb_private::Stream *s); @@ -357,7 +349,7 @@ elf::elf_word p_flags); //@} - /// @name ELF section header dump routines + /// \name ELF section header dump routines //@{ void DumpELFSectionHeaders(lldb_private::Stream *s);
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp index cfe6199..eaf973d 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp
@@ -1,9 +1,8 @@ //===-- ObjectFileJIT.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,7 +14,6 @@ #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/RangeMap.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamFile.h" #include "lldb/Host/Host.h" @@ -29,6 +27,7 @@ #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/RangeMap.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" #include "lldb/Utility/UUID.h" @@ -67,7 +66,7 @@ lldb::offset_t length) { // JIT'ed object file is backed by the ObjectFileJITDelegate, never read from // a file - return NULL; + return nullptr; } ObjectFile *ObjectFileJIT::CreateMemoryInstance(const lldb::ModuleSP &module_sp, @@ -76,7 +75,7 @@ lldb::addr_t header_addr) { // JIT'ed object file is backed by the ObjectFileJITDelegate, never read from // memory - return NULL; + return nullptr; } size_t ObjectFileJIT::GetModuleSpecifications( @@ -89,7 +88,7 @@ ObjectFileJIT::ObjectFileJIT(const lldb::ModuleSP &module_sp, const ObjectFileJITDelegateSP &delegate_sp) - : ObjectFile(module_sp, NULL, 0, 0, DataBufferSP(), 0), m_delegate_wp() { + : ObjectFile(module_sp, nullptr, 0, 0, DataBufferSP(), 0), m_delegate_wp() { if (delegate_sp) { m_delegate_wp = delegate_sp; m_data.SetByteOrder(delegate_sp->GetByteOrder()); @@ -116,18 +115,18 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_symtab_ap.get() == NULL) { - m_symtab_ap.reset(new Symtab(this)); + if (m_symtab_up == nullptr) { + m_symtab_up.reset(new Symtab(this)); std::lock_guard<std::recursive_mutex> symtab_guard( - m_symtab_ap->GetMutex()); + m_symtab_up->GetMutex()); ObjectFileJITDelegateSP delegate_sp(m_delegate_wp.lock()); if (delegate_sp) - delegate_sp->PopulateSymtab(this, *m_symtab_ap); + delegate_sp->PopulateSymtab(this, *m_symtab_up); // TODO: get symbols from delegate - m_symtab_ap->Finalize(); + m_symtab_up->Finalize(); } } - return m_symtab_ap.get(); + return m_symtab_up.get(); } bool ObjectFileJIT::IsStripped() { @@ -135,12 +134,12 @@ } void ObjectFileJIT::CreateSections(SectionList &unified_section_list) { - if (!m_sections_ap.get()) { - m_sections_ap.reset(new SectionList()); + if (!m_sections_up) { + m_sections_up.reset(new SectionList()); ObjectFileJITDelegateSP delegate_sp(m_delegate_wp.lock()); if (delegate_sp) { - delegate_sp->PopulateSectionList(this, *m_sections_ap); - unified_section_list = *m_sections_ap; + delegate_sp->PopulateSectionList(this, *m_sections_up); + unified_section_list = *m_sections_up; } } } @@ -160,16 +159,16 @@ SectionList *sections = GetSectionList(); if (sections) - sections->Dump(s, NULL, true, UINT32_MAX); + sections->Dump(s, nullptr, true, UINT32_MAX); - if (m_symtab_ap.get()) - m_symtab_ap->Dump(s, NULL, eSortOrderNone); + if (m_symtab_up) + m_symtab_up->Dump(s, nullptr, eSortOrderNone); } } -bool ObjectFileJIT::GetUUID(lldb_private::UUID *uuid) { +UUID ObjectFileJIT::GetUUID() { // TODO: maybe get from delegate, not needed for first pass - return false; + return UUID(); } uint32_t ObjectFileJIT::GetDependentModules(FileSpecList &files) { @@ -195,9 +194,7 @@ return ArchSpec(); } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ObjectFileJIT::GetPluginName() { return GetPluginNameStatic(); } @@ -249,14 +246,12 @@ if (section->GetFileSize()) { const void *src = (void *)(uintptr_t)section->GetFileOffset(); - DataBufferSP data_sp( - new lldb_private::DataBufferHeap(src, section->GetFileSize())); - if (data_sp) { - section_data.SetData(data_sp, 0, data_sp->GetByteSize()); - section_data.SetByteOrder(GetByteOrder()); - section_data.SetAddressByteSize(GetAddressByteSize()); - return section_data.GetByteSize(); - } + DataBufferSP data_sp = + std::make_shared<DataBufferHeap>(src, section->GetFileSize()); + section_data.SetData(data_sp, 0, data_sp->GetByteSize()); + section_data.SetByteOrder(GetByteOrder()); + section_data.SetAddressByteSize(GetAddressByteSize()); + return section_data.GetByteSize(); } section_data.Clear(); return 0;
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.h index 3d9e474..99241126 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.h
@@ -1,9 +1,8 @@ //===-- ObjectFileJIT.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,10 +12,8 @@ #include "lldb/Core/Address.h" #include "lldb/Symbol/ObjectFile.h" -//---------------------------------------------------------------------- // This class needs to be hidden as eventually belongs in a plugin that // will export the ObjectFile protocol -//---------------------------------------------------------------------- class ObjectFileJIT : public lldb_private::ObjectFile { public: ObjectFileJIT(const lldb::ModuleSP &module_sp, @@ -24,9 +21,7 @@ ~ObjectFileJIT() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -51,9 +46,7 @@ lldb::offset_t length, lldb_private::ModuleSpecList &specs); - //------------------------------------------------------------------ // Member Functions - //------------------------------------------------------------------ bool ParseHeader() override; bool SetLoadAddress(lldb_private::Target &target, lldb::addr_t value, @@ -75,7 +68,7 @@ lldb_private::ArchSpec GetArchitecture() override; - bool GetUUID(lldb_private::UUID *uuid) override; + lldb_private::UUID GetUUID() override; uint32_t GetDependentModules(lldb_private::FileSpecList &files) override; @@ -95,9 +88,7 @@ ObjectFile::Strata CalculateStrata() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp index 06908fe..ce928cf 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp
@@ -1,9 +1,8 @@ //===-- ObjectFileMachO.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,7 +17,6 @@ #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/RangeMap.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamFile.h" #include "lldb/Host/Host.h" @@ -36,6 +34,7 @@ #include "lldb/Utility/DataBuffer.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/RangeMap.h" #include "lldb/Utility/RegisterValue.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" @@ -60,6 +59,8 @@ #include <uuid/uuid.h> #endif +#include <memory> + #define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull using namespace lldb; using namespace lldb_private; @@ -172,7 +173,7 @@ const char *alt_name, size_t reg_byte_size, Stream &data) { const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name); - if (reg_info == NULL) + if (reg_info == nullptr) reg_info = reg_ctx->GetRegisterInfoByName(alt_name); if (reg_info) { lldb_private::RegisterValue reg_value; @@ -201,27 +202,27 @@ data.PutHex32(GPRRegSet); // Flavor data.PutHex32(GPRWordCount); - WriteRegister(reg_ctx, "rax", NULL, 8, data); - WriteRegister(reg_ctx, "rbx", NULL, 8, data); - WriteRegister(reg_ctx, "rcx", NULL, 8, data); - WriteRegister(reg_ctx, "rdx", NULL, 8, data); - WriteRegister(reg_ctx, "rdi", NULL, 8, data); - WriteRegister(reg_ctx, "rsi", NULL, 8, data); - WriteRegister(reg_ctx, "rbp", NULL, 8, data); - WriteRegister(reg_ctx, "rsp", NULL, 8, data); - WriteRegister(reg_ctx, "r8", NULL, 8, data); - WriteRegister(reg_ctx, "r9", NULL, 8, data); - WriteRegister(reg_ctx, "r10", NULL, 8, data); - WriteRegister(reg_ctx, "r11", NULL, 8, data); - WriteRegister(reg_ctx, "r12", NULL, 8, data); - WriteRegister(reg_ctx, "r13", NULL, 8, data); - WriteRegister(reg_ctx, "r14", NULL, 8, data); - WriteRegister(reg_ctx, "r15", NULL, 8, data); - WriteRegister(reg_ctx, "rip", NULL, 8, data); - WriteRegister(reg_ctx, "rflags", NULL, 8, data); - WriteRegister(reg_ctx, "cs", NULL, 8, data); - WriteRegister(reg_ctx, "fs", NULL, 8, data); - WriteRegister(reg_ctx, "gs", NULL, 8, data); + WriteRegister(reg_ctx, "rax", nullptr, 8, data); + WriteRegister(reg_ctx, "rbx", nullptr, 8, data); + WriteRegister(reg_ctx, "rcx", nullptr, 8, data); + WriteRegister(reg_ctx, "rdx", nullptr, 8, data); + WriteRegister(reg_ctx, "rdi", nullptr, 8, data); + WriteRegister(reg_ctx, "rsi", nullptr, 8, data); + WriteRegister(reg_ctx, "rbp", nullptr, 8, data); + WriteRegister(reg_ctx, "rsp", nullptr, 8, data); + WriteRegister(reg_ctx, "r8", nullptr, 8, data); + WriteRegister(reg_ctx, "r9", nullptr, 8, data); + WriteRegister(reg_ctx, "r10", nullptr, 8, data); + WriteRegister(reg_ctx, "r11", nullptr, 8, data); + WriteRegister(reg_ctx, "r12", nullptr, 8, data); + WriteRegister(reg_ctx, "r13", nullptr, 8, data); + WriteRegister(reg_ctx, "r14", nullptr, 8, data); + WriteRegister(reg_ctx, "r15", nullptr, 8, data); + WriteRegister(reg_ctx, "rip", nullptr, 8, data); + WriteRegister(reg_ctx, "rflags", nullptr, 8, data); + WriteRegister(reg_ctx, "cs", nullptr, 8, data); + WriteRegister(reg_ctx, "fs", nullptr, 8, data); + WriteRegister(reg_ctx, "gs", nullptr, 8, data); // // Write out the FPU registers // const size_t fpu_byte_size = sizeof(FPU); @@ -310,9 +311,9 @@ // Write out the EXC registers data.PutHex32(EXCRegSet); data.PutHex32(EXCWordCount); - WriteRegister(reg_ctx, "trapno", NULL, 4, data); - WriteRegister(reg_ctx, "err", NULL, 4, data); - WriteRegister(reg_ctx, "faultvaddr", NULL, 8, data); + WriteRegister(reg_ctx, "trapno", nullptr, 4, data); + WriteRegister(reg_ctx, "err", nullptr, 4, data); + WriteRegister(reg_ctx, "faultvaddr", nullptr, 8, data); return true; } return false; @@ -403,7 +404,7 @@ const char *alt_name, size_t reg_byte_size, Stream &data) { const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name); - if (reg_info == NULL) + if (reg_info == nullptr) reg_info = reg_ctx->GetRegisterInfoByName(alt_name); if (reg_info) { lldb_private::RegisterValue reg_value; @@ -432,29 +433,29 @@ data.PutHex32(GPRRegSet); // Flavor data.PutHex32(GPRWordCount); - WriteRegister(reg_ctx, "eax", NULL, 4, data); - WriteRegister(reg_ctx, "ebx", NULL, 4, data); - WriteRegister(reg_ctx, "ecx", NULL, 4, data); - WriteRegister(reg_ctx, "edx", NULL, 4, data); - WriteRegister(reg_ctx, "edi", NULL, 4, data); - WriteRegister(reg_ctx, "esi", NULL, 4, data); - WriteRegister(reg_ctx, "ebp", NULL, 4, data); - WriteRegister(reg_ctx, "esp", NULL, 4, data); - WriteRegister(reg_ctx, "ss", NULL, 4, data); - WriteRegister(reg_ctx, "eflags", NULL, 4, data); - WriteRegister(reg_ctx, "eip", NULL, 4, data); - WriteRegister(reg_ctx, "cs", NULL, 4, data); - WriteRegister(reg_ctx, "ds", NULL, 4, data); - WriteRegister(reg_ctx, "es", NULL, 4, data); - WriteRegister(reg_ctx, "fs", NULL, 4, data); - WriteRegister(reg_ctx, "gs", NULL, 4, data); + WriteRegister(reg_ctx, "eax", nullptr, 4, data); + WriteRegister(reg_ctx, "ebx", nullptr, 4, data); + WriteRegister(reg_ctx, "ecx", nullptr, 4, data); + WriteRegister(reg_ctx, "edx", nullptr, 4, data); + WriteRegister(reg_ctx, "edi", nullptr, 4, data); + WriteRegister(reg_ctx, "esi", nullptr, 4, data); + WriteRegister(reg_ctx, "ebp", nullptr, 4, data); + WriteRegister(reg_ctx, "esp", nullptr, 4, data); + WriteRegister(reg_ctx, "ss", nullptr, 4, data); + WriteRegister(reg_ctx, "eflags", nullptr, 4, data); + WriteRegister(reg_ctx, "eip", nullptr, 4, data); + WriteRegister(reg_ctx, "cs", nullptr, 4, data); + WriteRegister(reg_ctx, "ds", nullptr, 4, data); + WriteRegister(reg_ctx, "es", nullptr, 4, data); + WriteRegister(reg_ctx, "fs", nullptr, 4, data); + WriteRegister(reg_ctx, "gs", nullptr, 4, data); // Write out the EXC registers data.PutHex32(EXCRegSet); data.PutHex32(EXCWordCount); - WriteRegister(reg_ctx, "trapno", NULL, 4, data); - WriteRegister(reg_ctx, "err", NULL, 4, data); - WriteRegister(reg_ctx, "faultvaddr", NULL, 4, data); + WriteRegister(reg_ctx, "trapno", nullptr, 4, data); + WriteRegister(reg_ctx, "err", nullptr, 4, data); + WriteRegister(reg_ctx, "faultvaddr", nullptr, 4, data); return true; } return false; @@ -554,7 +555,7 @@ const char *alt_name, size_t reg_byte_size, Stream &data) { const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name); - if (reg_info == NULL) + if (reg_info == nullptr) reg_info = reg_ctx->GetRegisterInfoByName(alt_name); if (reg_info) { lldb_private::RegisterValue reg_value; @@ -583,23 +584,23 @@ data.PutHex32(GPRRegSet); // Flavor data.PutHex32(GPRWordCount); - WriteRegister(reg_ctx, "r0", NULL, 4, data); - WriteRegister(reg_ctx, "r1", NULL, 4, data); - WriteRegister(reg_ctx, "r2", NULL, 4, data); - WriteRegister(reg_ctx, "r3", NULL, 4, data); - WriteRegister(reg_ctx, "r4", NULL, 4, data); - WriteRegister(reg_ctx, "r5", NULL, 4, data); - WriteRegister(reg_ctx, "r6", NULL, 4, data); - WriteRegister(reg_ctx, "r7", NULL, 4, data); - WriteRegister(reg_ctx, "r8", NULL, 4, data); - WriteRegister(reg_ctx, "r9", NULL, 4, data); - WriteRegister(reg_ctx, "r10", NULL, 4, data); - WriteRegister(reg_ctx, "r11", NULL, 4, data); - WriteRegister(reg_ctx, "r12", NULL, 4, data); - WriteRegister(reg_ctx, "sp", NULL, 4, data); - WriteRegister(reg_ctx, "lr", NULL, 4, data); - WriteRegister(reg_ctx, "pc", NULL, 4, data); - WriteRegister(reg_ctx, "cpsr", NULL, 4, data); + WriteRegister(reg_ctx, "r0", nullptr, 4, data); + WriteRegister(reg_ctx, "r1", nullptr, 4, data); + WriteRegister(reg_ctx, "r2", nullptr, 4, data); + WriteRegister(reg_ctx, "r3", nullptr, 4, data); + WriteRegister(reg_ctx, "r4", nullptr, 4, data); + WriteRegister(reg_ctx, "r5", nullptr, 4, data); + WriteRegister(reg_ctx, "r6", nullptr, 4, data); + WriteRegister(reg_ctx, "r7", nullptr, 4, data); + WriteRegister(reg_ctx, "r8", nullptr, 4, data); + WriteRegister(reg_ctx, "r9", nullptr, 4, data); + WriteRegister(reg_ctx, "r10", nullptr, 4, data); + WriteRegister(reg_ctx, "r11", nullptr, 4, data); + WriteRegister(reg_ctx, "r12", nullptr, 4, data); + WriteRegister(reg_ctx, "sp", nullptr, 4, data); + WriteRegister(reg_ctx, "lr", nullptr, 4, data); + WriteRegister(reg_ctx, "pc", nullptr, 4, data); + WriteRegister(reg_ctx, "cpsr", nullptr, 4, data); // Write out the EXC registers // data.PutHex32 (EXCRegSet); @@ -709,7 +710,7 @@ const char *alt_name, size_t reg_byte_size, Stream &data) { const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name); - if (reg_info == NULL) + if (reg_info == nullptr) reg_info = reg_ctx->GetRegisterInfoByName(alt_name); if (reg_info) { lldb_private::RegisterValue reg_value; @@ -738,40 +739,40 @@ data.PutHex32(GPRRegSet); // Flavor data.PutHex32(GPRWordCount); - WriteRegister(reg_ctx, "x0", NULL, 8, data); - WriteRegister(reg_ctx, "x1", NULL, 8, data); - WriteRegister(reg_ctx, "x2", NULL, 8, data); - WriteRegister(reg_ctx, "x3", NULL, 8, data); - WriteRegister(reg_ctx, "x4", NULL, 8, data); - WriteRegister(reg_ctx, "x5", NULL, 8, data); - WriteRegister(reg_ctx, "x6", NULL, 8, data); - WriteRegister(reg_ctx, "x7", NULL, 8, data); - WriteRegister(reg_ctx, "x8", NULL, 8, data); - WriteRegister(reg_ctx, "x9", NULL, 8, data); - WriteRegister(reg_ctx, "x10", NULL, 8, data); - WriteRegister(reg_ctx, "x11", NULL, 8, data); - WriteRegister(reg_ctx, "x12", NULL, 8, data); - WriteRegister(reg_ctx, "x13", NULL, 8, data); - WriteRegister(reg_ctx, "x14", NULL, 8, data); - WriteRegister(reg_ctx, "x15", NULL, 8, data); - WriteRegister(reg_ctx, "x16", NULL, 8, data); - WriteRegister(reg_ctx, "x17", NULL, 8, data); - WriteRegister(reg_ctx, "x18", NULL, 8, data); - WriteRegister(reg_ctx, "x19", NULL, 8, data); - WriteRegister(reg_ctx, "x20", NULL, 8, data); - WriteRegister(reg_ctx, "x21", NULL, 8, data); - WriteRegister(reg_ctx, "x22", NULL, 8, data); - WriteRegister(reg_ctx, "x23", NULL, 8, data); - WriteRegister(reg_ctx, "x24", NULL, 8, data); - WriteRegister(reg_ctx, "x25", NULL, 8, data); - WriteRegister(reg_ctx, "x26", NULL, 8, data); - WriteRegister(reg_ctx, "x27", NULL, 8, data); - WriteRegister(reg_ctx, "x28", NULL, 8, data); - WriteRegister(reg_ctx, "fp", NULL, 8, data); - WriteRegister(reg_ctx, "lr", NULL, 8, data); - WriteRegister(reg_ctx, "sp", NULL, 8, data); - WriteRegister(reg_ctx, "pc", NULL, 8, data); - WriteRegister(reg_ctx, "cpsr", NULL, 4, data); + WriteRegister(reg_ctx, "x0", nullptr, 8, data); + WriteRegister(reg_ctx, "x1", nullptr, 8, data); + WriteRegister(reg_ctx, "x2", nullptr, 8, data); + WriteRegister(reg_ctx, "x3", nullptr, 8, data); + WriteRegister(reg_ctx, "x4", nullptr, 8, data); + WriteRegister(reg_ctx, "x5", nullptr, 8, data); + WriteRegister(reg_ctx, "x6", nullptr, 8, data); + WriteRegister(reg_ctx, "x7", nullptr, 8, data); + WriteRegister(reg_ctx, "x8", nullptr, 8, data); + WriteRegister(reg_ctx, "x9", nullptr, 8, data); + WriteRegister(reg_ctx, "x10", nullptr, 8, data); + WriteRegister(reg_ctx, "x11", nullptr, 8, data); + WriteRegister(reg_ctx, "x12", nullptr, 8, data); + WriteRegister(reg_ctx, "x13", nullptr, 8, data); + WriteRegister(reg_ctx, "x14", nullptr, 8, data); + WriteRegister(reg_ctx, "x15", nullptr, 8, data); + WriteRegister(reg_ctx, "x16", nullptr, 8, data); + WriteRegister(reg_ctx, "x17", nullptr, 8, data); + WriteRegister(reg_ctx, "x18", nullptr, 8, data); + WriteRegister(reg_ctx, "x19", nullptr, 8, data); + WriteRegister(reg_ctx, "x20", nullptr, 8, data); + WriteRegister(reg_ctx, "x21", nullptr, 8, data); + WriteRegister(reg_ctx, "x22", nullptr, 8, data); + WriteRegister(reg_ctx, "x23", nullptr, 8, data); + WriteRegister(reg_ctx, "x24", nullptr, 8, data); + WriteRegister(reg_ctx, "x25", nullptr, 8, data); + WriteRegister(reg_ctx, "x26", nullptr, 8, data); + WriteRegister(reg_ctx, "x27", nullptr, 8, data); + WriteRegister(reg_ctx, "x28", nullptr, 8, data); + WriteRegister(reg_ctx, "fp", nullptr, 8, data); + WriteRegister(reg_ctx, "lr", nullptr, 8, data); + WriteRegister(reg_ctx, "sp", nullptr, 8, data); + WriteRegister(reg_ctx, "pc", nullptr, 8, data); + WriteRegister(reg_ctx, "cpsr", nullptr, 4, data); // Write out the EXC registers // data.PutHex32 (EXCRegSet); @@ -871,24 +872,24 @@ return nullptr; data_offset = 0; } - auto objfile_ap = llvm::make_unique<ObjectFileMachO>( + auto objfile_up = llvm::make_unique<ObjectFileMachO>( module_sp, data_sp, data_offset, file, file_offset, length); - if (!objfile_ap || !objfile_ap->ParseHeader()) + if (!objfile_up || !objfile_up->ParseHeader()) return nullptr; - return objfile_ap.release(); + return objfile_up.release(); } ObjectFile *ObjectFileMachO::CreateMemoryInstance( const lldb::ModuleSP &module_sp, DataBufferSP &data_sp, const ProcessSP &process_sp, lldb::addr_t header_addr) { if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) { - std::unique_ptr<ObjectFile> objfile_ap( + std::unique_ptr<ObjectFile> objfile_up( new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr)); - if (objfile_ap.get() && objfile_ap->ParseHeader()) - return objfile_ap.release(); + if (objfile_up.get() && objfile_up->ParseHeader()) + return objfile_up.release(); } - return NULL; + return nullptr; } size_t ObjectFileMachO::GetModuleSpecifications( @@ -917,7 +918,7 @@ spec.GetArchitecture() = GetArchitecture(header, data, data_offset); if (spec.GetArchitecture().IsValid()) { - GetUUID(header, data, data_offset, spec.GetUUID()); + spec.GetUUID() = GetUUID(header, data, data_offset); specs.Append(spec); } } @@ -926,42 +927,42 @@ return specs.GetSize() - initial_count; } -const ConstString &ObjectFileMachO::GetSegmentNameTEXT() { +ConstString ObjectFileMachO::GetSegmentNameTEXT() { static ConstString g_segment_name_TEXT("__TEXT"); return g_segment_name_TEXT; } -const ConstString &ObjectFileMachO::GetSegmentNameDATA() { +ConstString ObjectFileMachO::GetSegmentNameDATA() { static ConstString g_segment_name_DATA("__DATA"); return g_segment_name_DATA; } -const ConstString &ObjectFileMachO::GetSegmentNameDATA_DIRTY() { +ConstString ObjectFileMachO::GetSegmentNameDATA_DIRTY() { static ConstString g_segment_name("__DATA_DIRTY"); return g_segment_name; } -const ConstString &ObjectFileMachO::GetSegmentNameDATA_CONST() { +ConstString ObjectFileMachO::GetSegmentNameDATA_CONST() { static ConstString g_segment_name("__DATA_CONST"); return g_segment_name; } -const ConstString &ObjectFileMachO::GetSegmentNameOBJC() { +ConstString ObjectFileMachO::GetSegmentNameOBJC() { static ConstString g_segment_name_OBJC("__OBJC"); return g_segment_name_OBJC; } -const ConstString &ObjectFileMachO::GetSegmentNameLINKEDIT() { +ConstString ObjectFileMachO::GetSegmentNameLINKEDIT() { static ConstString g_section_name_LINKEDIT("__LINKEDIT"); return g_section_name_LINKEDIT; } -const ConstString &ObjectFileMachO::GetSegmentNameDWARF() { +ConstString ObjectFileMachO::GetSegmentNameDWARF() { static ConstString g_section_name("__DWARF"); return g_section_name; } -const ConstString &ObjectFileMachO::GetSectionNameEHFrame() { +ConstString ObjectFileMachO::GetSectionNameEHFrame() { static ConstString g_section_name_eh_frame("__eh_frame"); return g_section_name_eh_frame; } @@ -1211,6 +1212,7 @@ case eSectionTypeDWARFDebugStrOffsets: case eSectionTypeDWARFDebugStrOffsetsDwo: case eSectionTypeDWARFDebugTypes: + case eSectionTypeDWARFDebugTypesDwo: case eSectionTypeDWARFAppleNames: case eSectionTypeDWARFAppleTypes: case eSectionTypeDWARFAppleNamespaces: @@ -1311,15 +1313,15 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_symtab_ap.get() == NULL) { - m_symtab_ap.reset(new Symtab(this)); + if (m_symtab_up == nullptr) { + m_symtab_up.reset(new Symtab(this)); std::lock_guard<std::recursive_mutex> symtab_guard( - m_symtab_ap->GetMutex()); + m_symtab_up->GetMutex()); ParseSymtab(); - m_symtab_ap->Finalize(); + m_symtab_up->Finalize(); } } - return m_symtab_ap.get(); + return m_symtab_up.get(); } bool ObjectFileMachO::IsStripped() { @@ -1331,14 +1333,14 @@ const lldb::offset_t load_cmd_offset = offset; load_command lc; - if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) + if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) break; if (lc.cmd == LC_DYSYMTAB) { m_dysymtab.cmd = lc.cmd; m_dysymtab.cmdsize = lc.cmdsize; if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym, (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) == - NULL) { + nullptr) { // Clear m_dysymtab if we were unable to read all items from the // load command ::memset(&m_dysymtab, 0, sizeof(m_dysymtab)); @@ -1360,7 +1362,7 @@ encryption_info_command encryption_cmd; for (uint32_t i = 0; i < m_header.ncmds; ++i) { const lldb::offset_t load_cmd_offset = offset; - if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL) + if (m_data.GetU32(&offset, &encryption_cmd, 2) == nullptr) break; // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the @@ -1610,8 +1612,7 @@ bool add_section = true; bool add_to_unified = true; ConstString const_segname( - load_cmd.segname, - std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname))); + load_cmd.segname, strnlen(load_cmd.segname, sizeof(load_cmd.segname))); SectionSP unified_section_sp( context.UnifiedList.FindSectionByName(const_segname)); @@ -1647,7 +1648,7 @@ // conflict with any of the sections. SectionSP segment_sp; if (add_section && (const_segname || is_core)) { - segment_sp.reset(new Section( + segment_sp = std::make_shared<Section>( module_sp, // Module to which this section belongs this, // Object file to which this sections belongs ++context.NextSegmentIdx @@ -1665,10 +1666,10 @@ load_cmd.filesize, // Size in bytes of this section as found // in the file 0, // Segments have no alignment information - load_cmd.flags)); // Flags for this section + load_cmd.flags); // Flags for this section segment_sp->SetIsEncrypted(segment_is_encrypted); - m_sections_ap->AddSection(segment_sp); + m_sections_up->AddSection(segment_sp); segment_sp->SetPermissions(segment_permissions); if (add_to_unified) context.UnifiedList.AddSection(segment_sp); @@ -1697,7 +1698,7 @@ context.FileAddressesChanged = true; } } - m_sections_ap->AddSection(unified_section_sp); + m_sections_up->AddSection(unified_section_sp); } struct section_64 sect64; @@ -1713,15 +1714,15 @@ for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects; ++segment_sect_idx) { if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname, - sizeof(sect64.sectname)) == NULL) + sizeof(sect64.sectname)) == nullptr) break; if (m_data.GetU8(&offset, (uint8_t *)sect64.segname, - sizeof(sect64.segname)) == NULL) + sizeof(sect64.segname)) == nullptr) break; sect64.addr = m_data.GetAddress(&offset); sect64.size = m_data.GetAddress(&offset); - if (m_data.GetU32(&offset, §64.offset, num_u32s) == NULL) + if (m_data.GetU32(&offset, §64.offset, num_u32s) == nullptr) break; // Keep a list of mach sections around in case we need to get at data that @@ -1730,8 +1731,7 @@ if (add_section) { ConstString section_name( - sect64.sectname, - std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname))); + sect64.sectname, strnlen(sect64.sectname, sizeof(sect64.sectname))); if (!const_segname) { // We have a segment with no name so we need to conjure up segments // that correspond to the section's segname if there isn't already such @@ -1787,7 +1787,7 @@ } } else { // Create a fake section for the section's named segment - segment_sp.reset(new Section( + segment_sp = std::make_shared<Section>( segment_sp, // Parent section module_sp, // Module to which this section belongs this, // Object file to which this section belongs @@ -1808,10 +1808,10 @@ // this section as // found in the file sect64.align, - load_cmd.flags)); // Flags for this section + load_cmd.flags); // Flags for this section segment_sp->SetIsFake(true); segment_sp->SetPermissions(segment_permissions); - m_sections_ap->AddSection(segment_sp); + m_sections_up->AddSection(segment_sp); if (add_to_unified) context.UnifiedList.AddSection(segment_sp); segment_sp->SetIsEncrypted(segment_is_encrypted); @@ -1831,7 +1831,7 @@ bool section_is_encrypted = false; if (!segment_is_encrypted && load_cmd.filesize != 0) section_is_encrypted = context.EncryptedRanges.FindEntryThatContains( - sect64.offset) != NULL; + sect64.offset) != nullptr; section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted); section_sp->SetPermissions(segment_permissions); @@ -1857,7 +1857,7 @@ if (curr_section_sp.get()) { if (curr_section_sp->GetByteSize() == 0) { - if (next_section_sp.get() != NULL) + if (next_section_sp.get() != nullptr) curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() - curr_section_sp->GetFileAddress()); else @@ -1878,10 +1878,10 @@ } void ObjectFileMachO::CreateSections(SectionList &unified_section_list) { - if (m_sections_ap) + if (m_sections_up) return; - m_sections_ap.reset(new SectionList()); + m_sections_up.reset(new SectionList()); lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); // bool dump_sections = false; @@ -1893,7 +1893,7 @@ struct load_command load_cmd; for (uint32_t i = 0; i < m_header.ncmds; ++i) { const lldb::offset_t load_cmd_offset = offset; - if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) + if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr) break; if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64) @@ -2022,7 +2022,7 @@ if (terminalSize != 0) { TrieEntryWithOffset e(offset); e.entry.flags = data.GetULEB128(&offset); - const char *import_name = NULL; + const char *import_name = nullptr; if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) { e.entry.address = 0; e.entry.other = data.GetULEB128(&offset); // dylib ordinal @@ -2130,7 +2130,7 @@ const lldb::offset_t cmd_offset = offset; // Read in the load command and load command size struct load_command lc; - if (m_data.GetU32(&offset, &lc, 2) == NULL) + if (m_data.GetU32(&offset, &lc, 2) == nullptr) break; // Watch for the symbol table load command switch (lc.cmd) { @@ -2139,7 +2139,7 @@ symtab_load_command.cmdsize = lc.cmdsize; // Read in the rest of the symtab load command if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) == - 0) // fill in symoff, nsyms, stroff, strsize fields + nullptr) // fill in symoff, nsyms, stroff, strsize fields return 0; if (symtab_load_command.symoff == 0) { if (log) @@ -2202,7 +2202,7 @@ function_starts_load_command.cmd = lc.cmd; function_starts_load_command.cmdsize = lc.cmdsize; if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) == - NULL) // fill in symoff, nsyms, stroff, strsize fields + nullptr) // fill in symoff, nsyms, stroff, strsize fields memset(&function_starts_load_command, 0, sizeof(function_starts_load_command)); break; @@ -2214,9 +2214,9 @@ } if (symtab_load_command.cmd) { - Symtab *symtab = m_symtab_ap.get(); + Symtab *symtab = m_symtab_up.get(); SectionList *section_list = GetSectionList(); - if (section_list == NULL) + if (section_list == nullptr) return 0; const uint32_t addr_byte_size = m_data.GetAddressByteSize(); @@ -2225,12 +2225,12 @@ const size_t nlist_byte_size = bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64); - DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size); - DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size); - DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size); - DataExtractor indirect_symbol_index_data(NULL, 0, byte_order, + DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size); + DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size); + DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size); + DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order, addr_byte_size); - DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size); + DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size); const addr_t nlist_data_byte_size = symtab_load_command.nsyms * nlist_byte_size; @@ -2427,12 +2427,12 @@ } } - const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT(); - const ConstString &g_segment_name_DATA = GetSegmentNameDATA(); - const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY(); - const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST(); - const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC(); - const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame(); + ConstString g_segment_name_TEXT = GetSegmentNameTEXT(); + ConstString g_segment_name_DATA = GetSegmentNameDATA(); + ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY(); + ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST(); + ConstString g_segment_name_OBJC = GetSegmentNameOBJC(); + ConstString g_section_name_eh_frame = GetSectionNameEHFrame(); SectionSP text_section_sp( section_list->FindSectionByName(g_segment_name_TEXT)); SectionSP data_section_sp( @@ -2551,10 +2551,10 @@ // so we know NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx; uint32_t nlist_idx = 0; - Symbol *symbol_ptr = NULL; + Symbol *symbol_ptr = nullptr; uint32_t sym_idx = 0; - Symbol *sym = NULL; + Symbol *sym = nullptr; size_t num_syms = 0; std::string memory_symbol_name; uint32_t unmapped_local_symbols_found = 0; @@ -3105,9 +3105,7 @@ type = eSymbolTypeLocal; break; - //---------------------------------------------------------------------- // INCL scopes - //---------------------------------------------------------------------- case N_BINCL: // include file beginning: name,,NO_SECT,0,sum We use // the current number of symbols in the symbol table @@ -3168,9 +3166,7 @@ type = eSymbolTypeLineEntry; break; - //---------------------------------------------------------------------- // Left and Right Braces - //---------------------------------------------------------------------- case N_LBRAC: // left bracket: 0,,NO_SECT,nesting level,address We // use the current number of symbols in the symbol @@ -3205,9 +3201,7 @@ type = eSymbolTypeHeaderFile; break; - //---------------------------------------------------------------------- // COMM scopes - //---------------------------------------------------------------------- case N_BCOMM: // begin common: name,,NO_SECT,0,0 // We use the current number of symbols in the symbol @@ -3756,7 +3750,7 @@ // If the sym array was not created while parsing the DSC unmapped // symbols, create it now. - if (sym == NULL) { + if (sym == nullptr) { sym = symtab->Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms); num_syms = symtab->GetNumSymbols(); @@ -3787,12 +3781,12 @@ nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset); SymbolType type = eSymbolTypeInvalid; - const char *symbol_name = NULL; + const char *symbol_name = nullptr; if (have_strtab_data) { symbol_name = strtab_data.PeekCStr(nlist.n_strx); - if (symbol_name == NULL) { + if (symbol_name == nullptr) { // No symbol should be NULL, even the symbols with no string values // should have an offset zero which points to an empty C-string Host::SystemLog(Host::eSystemLogError, @@ -3803,7 +3797,7 @@ continue; } if (symbol_name[0] == '\0') - symbol_name = NULL; + symbol_name = nullptr; } else { const addr_t str_addr = strtab_addr + nlist.n_strx; Status str_error; @@ -3811,7 +3805,7 @@ str_error)) symbol_name = memory_symbol_name.c_str(); } - const char *symbol_name_non_abi_mangled = NULL; + const char *symbol_name_non_abi_mangled = nullptr; SectionSP symbol_section; lldb::addr_t symbol_byte_size = 0; @@ -3964,7 +3958,7 @@ case N_SO: // source file name type = eSymbolTypeSourceFile; - if (symbol_name == NULL) { + if (symbol_name == nullptr) { add_nlist = false; if (N_SO_index != UINT32_MAX) { // Set the size of the N_SO to the terminating index of this @@ -4053,9 +4047,7 @@ type = eSymbolTypeLocal; break; - //---------------------------------------------------------------------- // INCL scopes - //---------------------------------------------------------------------- case N_BINCL: // include file beginning: name,,NO_SECT,0,sum We use the current // number of symbols in the symbol table in lieu of using nlist_idx @@ -4113,9 +4105,7 @@ type = eSymbolTypeLineEntry; break; - //---------------------------------------------------------------------- // Left and Right Braces - //---------------------------------------------------------------------- case N_LBRAC: // left bracket: 0,,NO_SECT,nesting level,address We use the // current number of symbols in the symbol table in lieu of using @@ -4147,9 +4137,7 @@ type = eSymbolTypeHeaderFile; break; - //---------------------------------------------------------------------- // COMM scopes - //---------------------------------------------------------------------- case N_BCOMM: // begin common: name,,NO_SECT,0,0 // We use the current number of symbols in the symbol table in lieu @@ -4439,7 +4427,7 @@ if (func_start_entry->addr != symbol_lookup_file_addr && func_start_entry->addr != (symbol_lookup_file_addr + 1)) { // Not the right entry, NULL it out... - func_start_entry = NULL; + func_start_entry = nullptr; } } if (func_start_entry) { @@ -4587,6 +4575,8 @@ sym[sym_idx].GetAddressRef().SetOffset(symbol_value); } sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc); + if (nlist.n_desc & N_WEAK_REF) + sym[sym_idx].SetIsWeak(true); if (symbol_byte_size > 0) sym[sym_idx].SetByteSize(symbol_byte_size); @@ -4723,7 +4713,7 @@ NListIndexToSymbolIndexMap::const_iterator index_pos = m_nlist_idx_to_sym_idx.find(stub_sym_id); - Symbol *stub_symbol = NULL; + Symbol *stub_symbol = nullptr; if (index_pos != end_index_pos) { // We have a remapping from the original nlist index to a // current symbol index, so just look this up by index @@ -4755,7 +4745,7 @@ Mangled stub_symbol_mangled_name(stub_symbol->GetMangled()); if (sym_idx >= num_syms) { sym = symtab->Resize(++num_syms); - stub_symbol = NULL; // this pointer no longer valid + stub_symbol = nullptr; // this pointer no longer valid } sym[sym_idx].SetID(synthetic_sym_id++); sym[sym_idx].GetMangled() = stub_symbol_mangled_name; @@ -4841,24 +4831,23 @@ SectionList *sections = GetSectionList(); if (sections) - sections->Dump(s, NULL, true, UINT32_MAX); + sections->Dump(s, nullptr, true, UINT32_MAX); - if (m_symtab_ap.get()) - m_symtab_ap->Dump(s, NULL, eSortOrderNone); + if (m_symtab_up) + m_symtab_up->Dump(s, nullptr, eSortOrderNone); } } -bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header, +UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header, const lldb_private::DataExtractor &data, - lldb::offset_t lc_offset, - lldb_private::UUID &uuid) { + lldb::offset_t lc_offset) { uint32_t i; struct uuid_command load_cmd; lldb::offset_t offset = lc_offset; for (i = 0; i < header.ncmds; ++i) { const lldb::offset_t cmd_offset = offset; - if (data.GetU32(&offset, &load_cmd, 2) == NULL) + if (data.GetU32(&offset, &load_cmd, 2) == nullptr) break; if (load_cmd.cmd == LC_UUID) { @@ -4873,16 +4862,15 @@ 0xbb, 0x14, 0xf0, 0x0d}; if (!memcmp(uuid_bytes, opencl_uuid, 16)) - return false; + return UUID(); - uuid = UUID::fromOptionalData(uuid_bytes, 16); - return true; + return UUID::fromOptionalData(uuid_bytes, 16); } - return false; + return UUID(); } offset = cmd_offset + load_cmd.cmdsize; } - return false; + return UUID(); } static llvm::StringRef GetOSName(uint32_t cmd) { @@ -4997,7 +4985,7 @@ lldb::offset_t offset = lc_offset; for (uint32_t i = 0; i < header.ncmds; ++i) { const lldb::offset_t cmd_offset = offset; - if (data.GetU32(&offset, &load_cmd, 2) == NULL) + if (data.GetU32(&offset, &load_cmd, 2) == nullptr) break; struct version_min_command version_min; @@ -5030,7 +5018,7 @@ offset = lc_offset; for (uint32_t i = 0; i < header.ncmds; ++i) { const lldb::offset_t cmd_offset = offset; - if (data.GetU32(&offset, &load_cmd, 2) == NULL) + if (data.GetU32(&offset, &load_cmd, 2) == nullptr) break; do { if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) { @@ -5053,7 +5041,7 @@ triple.setEnvironmentName(os_env.environment); return arch; } - } while (0); + } while (false); offset = cmd_offset + load_cmd.cmdsize; } @@ -5069,14 +5057,14 @@ return arch; } -bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) { +UUID ObjectFileMachO::GetUUID() { ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); - return GetUUID(m_header, m_data, offset, *uuid); + return GetUUID(m_header, m_data, offset); } - return false; + return UUID(); } uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) { @@ -5092,7 +5080,7 @@ uint32_t i; for (i = 0; i < m_header.ncmds; ++i) { const uint32_t cmd_offset = offset; - if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) + if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr) break; switch (load_cmd.cmd) { @@ -5226,7 +5214,7 @@ for (i = 0; i < m_header.ncmds; ++i) { const lldb::offset_t cmd_offset = offset; - if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) + if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr) break; switch (load_cmd.cmd) { @@ -5365,7 +5353,7 @@ thread_command thread_cmd; for (uint32_t i = 0; i < m_header.ncmds; ++i) { const uint32_t cmd_offset = offset; - if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL) + if (m_data.GetU32(&offset, &thread_cmd, 2) == nullptr) break; if (thread_cmd.cmd == LC_THREAD) { @@ -5392,8 +5380,8 @@ for (uint32_t i = 0; i < m_header.ncmds; ++i) { const uint32_t cmd_offset = offset; load_command lc; - if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) - break; + if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) + break; if (lc.cmd == LC_NOTE) { char data_owner[17]; @@ -5437,7 +5425,7 @@ for (uint32_t i = 0; i < m_header.ncmds; ++i) { const uint32_t cmd_offset = offset; struct ident_command ident_command; - if (m_data.GetU32(&offset, &ident_command, 2) == NULL) + if (m_data.GetU32(&offset, &ident_command, 2) == nullptr) break; if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) { char *buf = (char *) malloc (ident_command.cmdsize); @@ -5466,8 +5454,8 @@ for (uint32_t i = 0; i < m_header.ncmds; ++i) { const uint32_t cmd_offset = offset; load_command lc; - if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) - break; + if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) + break; if (lc.cmd == LC_NOTE) { char data_owner[17]; @@ -5530,19 +5518,23 @@ switch (m_header.cputype) { case llvm::MachO::CPU_TYPE_ARM64: - reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data)); + reg_ctx_sp = + std::make_shared<RegisterContextDarwin_arm64_Mach>(thread, data); break; case llvm::MachO::CPU_TYPE_ARM: - reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data)); + reg_ctx_sp = + std::make_shared<RegisterContextDarwin_arm_Mach>(thread, data); break; case llvm::MachO::CPU_TYPE_I386: - reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data)); + reg_ctx_sp = + std::make_shared<RegisterContextDarwin_i386_Mach>(thread, data); break; case llvm::MachO::CPU_TYPE_X86_64: - reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data)); + reg_ctx_sp = + std::make_shared<RegisterContextDarwin_x86_64_Mach>(thread, data); break; } } @@ -5556,8 +5548,7 @@ if (GetAddressByteSize() == 4) { // 32 bit kexts are just object files, but they do have a valid // UUID load command. - UUID uuid; - if (GetUUID(&uuid)) { + if (GetUUID()) { // this checking for the UUID load command is not enough we could // eventually look for the symbol named "OSKextGetCurrentIdentifier" as // this is required of kexts @@ -5600,8 +5591,7 @@ { // 32 bit kexts are just object files, but they do have a valid // UUID load command. - UUID uuid; - if (GetUUID(&uuid)) { + if (GetUUID()) { // this checking for the UUID load command is not enough we could // eventually look for the symbol named "OSKextGetCurrentIdentifier" as // this is required of kexts @@ -5662,13 +5652,13 @@ uint32_t i; for (i = 0; i < m_header.ncmds; ++i) { const lldb::offset_t cmd_offset = offset; - if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) + if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr) break; if (load_cmd.cmd == LC_ID_DYLIB) { if (version_cmd == 0) { version_cmd = load_cmd.cmd; - if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL) + if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == nullptr) break; version = load_cmd.dylib.current_version; } @@ -5808,7 +5798,7 @@ const lldb::offset_t load_cmd_offset = offset; version_min_command lc; - if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) + if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) break; if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX || lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS || @@ -5859,16 +5849,14 @@ return *m_min_os_version; } -uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions, - uint32_t num_versions) { - if (m_sdk_versions.empty()) { +llvm::VersionTuple ObjectFileMachO::GetSDKVersion() { + if (!m_sdk_versions.hasValue()) { lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); - bool success = false; - for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) { + for (uint32_t i = 0; i < m_header.ncmds; ++i) { const lldb::offset_t load_cmd_offset = offset; version_min_command lc; - if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) + if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) break; if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX || lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS || @@ -5880,10 +5868,8 @@ const uint32_t yy = (lc.sdk >> 8) & 0xffu; const uint32_t zz = lc.sdk & 0xffu; if (xxxx) { - m_sdk_versions.push_back(xxxx); - m_sdk_versions.push_back(yy); - m_sdk_versions.push_back(zz); - success = true; + m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz); + break; } else { GetModule()->ReportWarning( "minimum OS version load command with invalid (0) version found."); @@ -5893,13 +5879,13 @@ offset = load_cmd_offset + lc.cmdsize; } - if (!success) { + if (!m_sdk_versions.hasValue()) { offset = MachHeaderSizeFromMagic(m_header.magic); - for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) { + for (uint32_t i = 0; i < m_header.ncmds; ++i) { const lldb::offset_t load_cmd_offset = offset; version_min_command lc; - if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) + if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) break; if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) { // struct build_version_command { @@ -5922,41 +5908,19 @@ const uint32_t yy = (minos >> 8) & 0xffu; const uint32_t zz = minos & 0xffu; if (xxxx) { - m_sdk_versions.push_back(xxxx); - m_sdk_versions.push_back(yy); - m_sdk_versions.push_back(zz); - success = true; + m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz); + break; } } offset = load_cmd_offset + lc.cmdsize; } } - if (!success) { - // Push an invalid value so we don't try to find - // the version # again on the next call to this - // method. - m_sdk_versions.push_back(UINT32_MAX); - } + if (!m_sdk_versions.hasValue()) + m_sdk_versions = llvm::VersionTuple(); } - // Legitimate version numbers will have 3 entries pushed - // on to m_sdk_versions. If we only have one value, it's - // the sentinel value indicating that this object file - // does not have a valid minimum os version #. - if (m_sdk_versions.size() > 1) { - if (versions != NULL && num_versions > 0) { - for (size_t i = 0; i < num_versions; ++i) { - if (i < m_sdk_versions.size()) - versions[i] = m_sdk_versions[i]; - else - versions[i] = 0; - } - } - return m_sdk_versions.size(); - } - // Call the superclasses version that will empty out the data - return ObjectFile::GetSDKVersion(versions, num_versions); + return m_sdk_versions.getValue(); } bool ObjectFileMachO::GetIsDynamicLinkEditor() { @@ -5967,9 +5931,7 @@ return m_allow_assembly_emulation_unwind_plans; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString ObjectFileMachO::GetPluginName() { return GetPluginNameStatic(); } @@ -6129,18 +6091,6 @@ if (range_info.GetExecutable() == MemoryRegionInfo::eYes) prot |= VM_PROT_EXECUTE; - // printf ("[%3u] [0x%16.16" PRIx64 " - - // 0x%16.16" PRIx64 ") %c%c%c\n", - // range_info_idx, - // addr, - // size, - // (prot & VM_PROT_READ ) ? 'r' : - // '-', - // (prot & VM_PROT_WRITE ) ? 'w' : - // '-', - // (prot & VM_PROT_EXECUTE) ? 'x' : - // '-'); - if (prot != 0) { uint32_t cmd_type = LC_SEGMENT_64; uint32_t segment_size = sizeof(segment_command_64); @@ -6245,13 +6195,6 @@ mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize(); } - printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x " - "0x%8.8x 0x%8.8x\n", - mach_header.magic, mach_header.cputype, mach_header.cpusubtype, - mach_header.filetype, mach_header.ncmds, - mach_header.sizeofcmds, mach_header.flags, - mach_header.reserved); - // Write the mach header buffer.PutHex32(mach_header.magic); buffer.PutHex32(mach_header.cputype); @@ -6347,8 +6290,13 @@ while (bytes_left > 0 && error.Success()) { const size_t bytes_to_read = bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left; - const size_t bytes_read = process_sp->ReadMemory( + + // In a savecore setting, we don't really care about caching, + // as the data is dumped and very likely never read again, + // so we call ReadMemoryFromInferior to bypass it. + const size_t bytes_read = process_sp->ReadMemoryFromInferior( addr, bytes, bytes_to_read, memory_read_error); + if (bytes_read == bytes_to_read) { size_t bytes_written = bytes_read; error = core_file.Write(bytes, bytes_written);
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.h index 196abae..df6b914 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.h
@@ -1,9 +1,8 @@ //===-- ObjectFileMachO.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,16 +11,14 @@ #include "lldb/Core/Address.h" #include "lldb/Core/FileSpecList.h" -#include "lldb/Core/RangeMap.h" #include "lldb/Host/SafeMachO.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/RangeMap.h" #include "lldb/Utility/UUID.h" -//---------------------------------------------------------------------- // This class needs to be hidden as eventually belongs in a plugin that // will export the ObjectFile protocol -//---------------------------------------------------------------------- class ObjectFileMachO : public lldb_private::ObjectFile { public: ObjectFileMachO(const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp, @@ -34,9 +31,7 @@ ~ObjectFileMachO() override = default; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -68,9 +63,7 @@ static bool MagicBytesMatch(lldb::DataBufferSP &data_sp, lldb::addr_t offset, lldb::addr_t length); - //------------------------------------------------------------------ // Member Functions - //------------------------------------------------------------------ bool ParseHeader() override; bool SetLoadAddress(lldb_private::Target &target, lldb::addr_t value, @@ -94,7 +87,7 @@ lldb_private::ArchSpec GetArchitecture() override; - bool GetUUID(lldb_private::UUID *uuid) override; + lldb_private::UUID GetUUID() override; uint32_t GetDependentModules(lldb_private::FileSpecList &files) override; @@ -123,7 +116,7 @@ llvm::VersionTuple GetMinimumOSVersion() override; - uint32_t GetSDKVersion(uint32_t *versions, uint32_t num_versions) override; + llvm::VersionTuple GetSDKVersion() override; bool GetIsDynamicLinkEditor() override; @@ -133,19 +126,16 @@ bool AllowAssemblyEmulationUnwindPlans() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; protected: - static bool + static lldb_private::UUID GetUUID(const llvm::MachO::mach_header &header, const lldb_private::DataExtractor &data, - lldb::offset_t lc_offset, // Offset to the first load command - lldb_private::UUID &uuid); + lldb::offset_t lc_offset); // Offset to the first load command static lldb_private::ArchSpec GetArchitecture(const llvm::MachO::mach_header &header, @@ -195,20 +185,20 @@ bool SectionIsLoadable(const lldb_private::Section *section); llvm::MachO::mach_header m_header; - static const lldb_private::ConstString &GetSegmentNameTEXT(); - static const lldb_private::ConstString &GetSegmentNameDATA(); - static const lldb_private::ConstString &GetSegmentNameDATA_DIRTY(); - static const lldb_private::ConstString &GetSegmentNameDATA_CONST(); - static const lldb_private::ConstString &GetSegmentNameOBJC(); - static const lldb_private::ConstString &GetSegmentNameLINKEDIT(); - static const lldb_private::ConstString &GetSegmentNameDWARF(); - static const lldb_private::ConstString &GetSectionNameEHFrame(); + static lldb_private::ConstString GetSegmentNameTEXT(); + static lldb_private::ConstString GetSegmentNameDATA(); + static lldb_private::ConstString GetSegmentNameDATA_DIRTY(); + static lldb_private::ConstString GetSegmentNameDATA_CONST(); + static lldb_private::ConstString GetSegmentNameOBJC(); + static lldb_private::ConstString GetSegmentNameLINKEDIT(); + static lldb_private::ConstString GetSegmentNameDWARF(); + static lldb_private::ConstString GetSectionNameEHFrame(); llvm::MachO::dysymtab_command m_dysymtab; std::vector<llvm::MachO::segment_command_64> m_mach_segments; std::vector<llvm::MachO::section_64> m_mach_sections; llvm::Optional<llvm::VersionTuple> m_min_os_version; - std::vector<uint32_t> m_sdk_versions; + llvm::Optional<llvm::VersionTuple> m_sdk_versions; typedef lldb_private::RangeVector<uint32_t, uint32_t> FileRangeArray; lldb_private::Address m_entry_point_address; FileRangeArray m_thread_context_offsets;
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.cpp index d18ff61..fab3790 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.cpp
@@ -1,9 +1,8 @@ //===-- ObjectFilePECOFF.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -41,6 +40,54 @@ using namespace lldb; using namespace lldb_private; +struct CVInfoPdb70 { + // 16-byte GUID + struct _Guid { + llvm::support::ulittle32_t Data1; + llvm::support::ulittle16_t Data2; + llvm::support::ulittle16_t Data3; + uint8_t Data4[8]; + } Guid; + + llvm::support::ulittle32_t Age; +}; + +static UUID GetCoffUUID(llvm::object::COFFObjectFile *coff_obj) { + if (!coff_obj) + return UUID(); + + const llvm::codeview::DebugInfo *pdb_info = nullptr; + llvm::StringRef pdb_file; + + // This part is similar with what has done in minidump parser. + if (!coff_obj->getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) { + if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) { + using llvm::support::endian::read16be; + using llvm::support::endian::read32be; + + const uint8_t *sig = pdb_info->PDB70.Signature; + struct CVInfoPdb70 info; + info.Guid.Data1 = read32be(sig); + sig += 4; + info.Guid.Data2 = read16be(sig); + sig += 2; + info.Guid.Data3 = read16be(sig); + sig += 2; + memcpy(info.Guid.Data4, sig, 8); + + // Return 20-byte UUID if the Age is not zero + if (pdb_info->PDB70.Age) { + info.Age = read32be(&pdb_info->PDB70.Age); + return UUID::fromOptionalData(&info, sizeof(info)); + } + // Otherwise return 16-byte GUID + return UUID::fromOptionalData(&info.Guid, sizeof(info.Guid)); + } + } + + return UUID(); +} + void ObjectFilePECOFF::Initialize() { PluginManager::RegisterPlugin( GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance, @@ -84,16 +131,16 @@ return nullptr; } - auto objfile_ap = llvm::make_unique<ObjectFilePECOFF>( + auto objfile_up = llvm::make_unique<ObjectFilePECOFF>( module_sp, data_sp, data_offset, file, file_offset, length); - if (!objfile_ap || !objfile_ap->ParseHeader()) + if (!objfile_up || !objfile_up->ParseHeader()) return nullptr; // Cache coff binary. - if (!objfile_ap->CreateBinary()) + if (!objfile_up->CreateBinary()) return nullptr; - return objfile_ap.release(); + return objfile_up.release(); } ObjectFile *ObjectFilePECOFF::CreateMemoryInstance( @@ -101,10 +148,10 @@ const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) { if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp)) return nullptr; - auto objfile_ap = llvm::make_unique<ObjectFilePECOFF>( + auto objfile_up = llvm::make_unique<ObjectFilePECOFF>( module_sp, data_sp, process_sp, header_addr); - if (objfile_ap.get() && objfile_ap->ParseHeader()) { - return objfile_ap.release(); + if (objfile_up.get() && objfile_up->ParseHeader()) { + return objfile_up.release(); } return nullptr; } @@ -114,36 +161,43 @@ lldb::offset_t data_offset, lldb::offset_t file_offset, lldb::offset_t length, lldb_private::ModuleSpecList &specs) { const size_t initial_count = specs.GetSize(); + if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp)) + return initial_count; - if (ObjectFilePECOFF::MagicBytesMatch(data_sp)) { - DataExtractor data; - data.SetData(data_sp, data_offset, length); - data.SetByteOrder(eByteOrderLittle); + auto binary = llvm::object::createBinary(file.GetPath()); + if (!binary) + return initial_count; - dos_header_t dos_header; - coff_header_t coff_header; + if (!binary->getBinary()->isCOFF() && + !binary->getBinary()->isCOFFImportFile()) + return initial_count; - if (ParseDOSHeader(data, dos_header)) { - lldb::offset_t offset = dos_header.e_lfanew; - uint32_t pe_signature = data.GetU32(&offset); - if (pe_signature != IMAGE_NT_SIGNATURE) - return false; - if (ParseCOFFHeader(data, &offset, coff_header)) { - ArchSpec spec; - if (coff_header.machine == MachineAmd64) { - spec.SetTriple("x86_64-pc-windows"); - specs.Append(ModuleSpec(file, spec)); - } else if (coff_header.machine == MachineX86) { - spec.SetTriple("i386-pc-windows"); - specs.Append(ModuleSpec(file, spec)); - spec.SetTriple("i686-pc-windows"); - specs.Append(ModuleSpec(file, spec)); - } else if (coff_header.machine == MachineArmNt) { - spec.SetTriple("arm-pc-windows"); - specs.Append(ModuleSpec(file, spec)); - } - } - } + auto COFFObj = + llvm::cast<llvm::object::COFFObjectFile>(binary->getBinary()); + + ModuleSpec module_spec(file); + ArchSpec &spec = module_spec.GetArchitecture(); + lldb_private::UUID &uuid = module_spec.GetUUID(); + if (!uuid.IsValid()) + uuid = GetCoffUUID(COFFObj); + + switch (COFFObj->getMachine()) { + case MachineAmd64: + spec.SetTriple("x86_64-pc-windows"); + specs.Append(module_spec); + break; + case MachineX86: + spec.SetTriple("i386-pc-windows"); + specs.Append(module_spec); + spec.SetTriple("i686-pc-windows"); + specs.Append(module_spec); + break; + case MachineArmNt: + spec.SetTriple("arm-pc-windows"); + specs.Append(module_spec); + break; + default: + break; } return specs.GetSize() - initial_count; @@ -304,12 +358,10 @@ return 4; } -//---------------------------------------------------------------------- // NeedsEndianSwap // // Return true if an endian swap needs to occur when extracting data from this // file. -//---------------------------------------------------------------------- bool ObjectFilePECOFF::NeedsEndianSwap() const { #if defined(__LITTLE_ENDIAN__) return false; @@ -317,9 +369,7 @@ return true; #endif } -//---------------------------------------------------------------------- // ParseDOSHeader -//---------------------------------------------------------------------- bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data, dos_header_t &dos_header) { bool success = false; @@ -378,9 +428,7 @@ return success; } -//---------------------------------------------------------------------- // ParserCOFFHeader -//---------------------------------------------------------------------- bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data, lldb::offset_t *offset_ptr, coff_header_t &coff_header) { @@ -458,7 +506,6 @@ m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr); } - m_file_offset = m_coff_header_opt.image_base; m_image_base = m_coff_header_opt.image_base; } } @@ -478,22 +525,20 @@ ProcessSP process_sp(m_process_wp.lock()); DataExtractor data; if (process_sp) { - auto data_ap = llvm::make_unique<DataBufferHeap>(size, 0); + auto data_up = llvm::make_unique<DataBufferHeap>(size, 0); Status readmem_error; size_t bytes_read = - process_sp->ReadMemory(m_image_base + offset, data_ap->GetBytes(), - data_ap->GetByteSize(), readmem_error); + process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(), + data_up->GetByteSize(), readmem_error); if (bytes_read == size) { - DataBufferSP buffer_sp(data_ap.release()); + DataBufferSP buffer_sp(data_up.release()); data.SetData(buffer_sp, 0, buffer_sp->GetByteSize()); } } return data; } -//---------------------------------------------------------------------- // ParseSectionHeaders -//---------------------------------------------------------------------- bool ObjectFilePECOFF::ParseSectionHeaders( uint32_t section_header_data_offset) { const uint32_t nsects = m_coff_header.nsects; @@ -546,17 +591,15 @@ return hdr_name; } -//---------------------------------------------------------------------- // GetNListSymtab -//---------------------------------------------------------------------- Symtab *ObjectFilePECOFF::GetSymtab() { ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_symtab_ap.get() == NULL) { + if (m_symtab_up == nullptr) { SectionList *sect_list = GetSectionList(); - m_symtab_ap.reset(new Symtab(this)); - std::lock_guard<std::recursive_mutex> guard(m_symtab_ap->GetMutex()); + m_symtab_up.reset(new Symtab(this)); + std::lock_guard<std::recursive_mutex> guard(m_symtab_up->GetMutex()); const uint32_t num_syms = m_coff_header.nsyms; @@ -580,11 +623,11 @@ offset = 0; std::string symbol_name; - Symbol *symbols = m_symtab_ap->Resize(num_syms); + Symbol *symbols = m_symtab_up->Resize(num_syms); for (uint32_t i = 0; i < num_syms; ++i) { coff_symbol_t symbol; const uint32_t symbol_offset = offset; - const char *symbol_name_cstr = NULL; + const char *symbol_name_cstr = nullptr; // If the first 4 bytes of the symbol string are zero, then they // are followed by a 4-byte string table offset. Else these // 8 bytes contain the symbol name @@ -599,7 +642,7 @@ // bytes offset += sizeof(symbol.name) - 4; // Skip remaining symbol_name_cstr = symtab_data.PeekCStr(symbol_offset); - if (symbol_name_cstr == NULL) + if (symbol_name_cstr == nullptr) break; symbol_name.assign(symbol_name_cstr, sizeof(symbol.name)); } @@ -661,7 +704,7 @@ lldb::offset_t name_ordinal_offset = export_table.address_of_name_ordinals - data_start; - Symbol *symbols = m_symtab_ap->Resize(export_table.number_of_names); + Symbol *symbols = m_symtab_up->Resize(export_table.number_of_names); std::string symbol_name; @@ -688,10 +731,10 @@ symbols[i].SetDebug(true); } } - m_symtab_ap->CalculateSymbolSizes(); + m_symtab_up->CalculateSymbolSizes(); } } - return m_symtab_ap.get(); + return m_symtab_up.get(); } bool ObjectFilePECOFF::IsStripped() { @@ -700,13 +743,22 @@ } void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) { - if (m_sections_ap) + if (m_sections_up) return; - m_sections_ap.reset(new SectionList()); + m_sections_up.reset(new SectionList()); ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); + + SectionSP image_sp = std::make_shared<Section>( + module_sp, this, ~user_id_t(0), ConstString(), eSectionTypeContainer, + m_coff_header_opt.image_base, m_coff_header_opt.image_size, + /*file_offset*/ 0, /*file_size*/ 0, m_coff_header_opt.sect_alignment, + /*flags*/ 0); + m_sections_up->AddSection(image_sp); + unified_section_list.AddSection(image_sp); + const uint32_t nsects = m_sect_headers.size(); ModuleSP module_sp(GetModule()); for (uint32_t idx = 0; idx < nsects; ++idx) { @@ -809,20 +861,16 @@ section_type = eSectionTypeData; } - // Use a segment ID of the segment index shifted left by 8 so they - // never conflict with any of the sections. SectionSP section_sp(new Section( - module_sp, // Module to which this section belongs - this, // Object file to which this section belongs - idx + 1, // Section ID is the 1 based segment index shifted right by - // 8 bits as not to collide with any of the 256 section IDs - // that are possible + image_sp, // Parent section + module_sp, // Module to which this section belongs + this, // Object file to which this section belongs + idx + 1, // Section ID is the 1 based section index. const_sect_name, // Name of this section - section_type, // This section is a container of other sections. - m_coff_header_opt.image_base + - m_sect_headers[idx].vmaddr, // File VM address == addresses as - // they are found in the object file - m_sect_headers[idx].vmsize, // VM size in bytes of this section + section_type, + m_sect_headers[idx].vmaddr, // File VM address == addresses as + // they are found in the object file + m_sect_headers[idx].vmsize, // VM size in bytes of this section m_sect_headers[idx] .offset, // Offset to the data for this section in the file m_sect_headers[idx] @@ -830,15 +878,24 @@ m_coff_header_opt.sect_alignment, // Section alignment m_sect_headers[idx].flags)); // Flags for this section - // section_sp->SetIsEncrypted (segment_is_encrypted); - - unified_section_list.AddSection(section_sp); - m_sections_ap->AddSection(section_sp); + image_sp->GetChildren().AddSection(std::move(section_sp)); } } } -bool ObjectFilePECOFF::GetUUID(UUID *uuid) { return false; } +UUID ObjectFilePECOFF::GetUUID() { + if (m_uuid.IsValid()) + return m_uuid; + + if (!CreateBinary()) + return UUID(); + + auto COFFObj = + llvm::cast<llvm::object::COFFObjectFile>(m_owningbin->getBinary()); + + m_uuid = GetCoffUUID(COFFObj); + return m_uuid; +} uint32_t ObjectFilePECOFF::ParseDependentModules() { ModuleSP module_sp(GetModule()); @@ -860,8 +917,7 @@ static_cast<void *>(this), static_cast<void *>(module_sp.get()), module_sp->GetSpecificationDescription().c_str(), static_cast<void *>(m_owningbin.getPointer()), - m_owningbin ? static_cast<void *>(m_owningbin->getBinary()) - : nullptr); + static_cast<void *>(m_owningbin->getBinary())); auto COFFObj = llvm::dyn_cast<llvm::object::COFFObjectFile>(m_owningbin->getBinary()); @@ -922,16 +978,19 @@ if (!section_list) m_entry_point_address.SetOffset(file_addr); else - m_entry_point_address.ResolveAddressUsingFileSections(file_addr, section_list); + m_entry_point_address.ResolveAddressUsingFileSections(file_addr, + section_list); return m_entry_point_address; } -//---------------------------------------------------------------------- +Address ObjectFilePECOFF::GetBaseAddress() { + return Address(GetSectionList()->GetSectionAtIndex(0), 0); +} + // Dump // // Dump the specifics of the runtime file container (such as any headers // segments, sections, etc). -//---------------------------------------------------------------------- void ObjectFilePECOFF::Dump(Stream *s) { ModuleSP module_sp(GetModule()); if (module_sp) { @@ -947,10 +1006,10 @@ SectionList *sections = GetSectionList(); if (sections) - sections->Dump(s, NULL, true, UINT32_MAX); + sections->Dump(s, nullptr, true, UINT32_MAX); - if (m_symtab_ap.get()) - m_symtab_ap->Dump(s, NULL, eSortOrderNone); + if (m_symtab_up) + m_symtab_up->Dump(s, nullptr, eSortOrderNone); if (m_dos_header.e_magic) DumpDOSHeader(s, m_dos_header); @@ -968,11 +1027,9 @@ } } -//---------------------------------------------------------------------- // DumpDOSHeader // // Dump the MS-DOS header to the specified output stream -//---------------------------------------------------------------------- void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) { s->PutCString("MSDOS Header\n"); s->Printf(" e_magic = 0x%4.4x\n", header.e_magic); @@ -1002,11 +1059,9 @@ s->Printf(" e_lfanew = 0x%8.8x\n", header.e_lfanew); } -//---------------------------------------------------------------------- // DumpCOFFHeader // // Dump the COFF header to the specified output stream -//---------------------------------------------------------------------- void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) { s->PutCString("COFF Header\n"); s->Printf(" machine = 0x%4.4x\n", header.machine); @@ -1017,11 +1072,9 @@ s->Printf(" hdrsize = 0x%4.4x\n", header.hdrsize); } -//---------------------------------------------------------------------- // DumpOptCOFFHeader // // Dump the optional COFF header to the specified output stream -//---------------------------------------------------------------------- void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s, const coff_opt_header_t &header) { s->PutCString("Optional COFF Header\n"); @@ -1075,11 +1128,9 @@ header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize); } } -//---------------------------------------------------------------------- // DumpSectionHeader // // Dump a single ELF section header to the specified output stream -//---------------------------------------------------------------------- void ObjectFilePECOFF::DumpSectionHeader(Stream *s, const section_header_t &sh) { std::string name = GetSectionName(sh); @@ -1089,11 +1140,9 @@ sh.lineoff, sh.nreloc, sh.nline, sh.flags); } -//---------------------------------------------------------------------- // DumpSectionHeaders // // Dump all of the ELF section header to the specified output stream -//---------------------------------------------------------------------- void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) { s->PutCString("Section Headers\n"); @@ -1111,11 +1160,9 @@ } } -//---------------------------------------------------------------------- // DumpDependentModules // // Dump all of the dependent modules to the specified output stream -//---------------------------------------------------------------------- void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) { auto num_modules = ParseDependentModules(); if (num_modules > 0) { @@ -1175,9 +1222,7 @@ ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString ObjectFilePECOFF::GetPluginName() { return GetPluginNameStatic(); } uint32_t ObjectFilePECOFF::GetPluginVersion() { return 1; }
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h index 9fd313f..93edaa7 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h
@@ -1,9 +1,8 @@ //===-- ObjectFilePECOFF.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,7 +16,7 @@ class ObjectFilePECOFF : public lldb_private::ObjectFile { public: - typedef enum MachineType { + enum MachineType { MachineUnknown = 0x0, MachineAm33 = 0x1d3, MachineAmd64 = 0x8664, @@ -40,7 +39,7 @@ MachineSh5 = 0x1a8, MachineThumb = 0x1c2, MachineWcemIpsv2 = 0x169 - } MachineType; + }; ObjectFilePECOFF(const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp, lldb::offset_t data_offset, @@ -53,9 +52,7 @@ ~ObjectFilePECOFF() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -112,19 +109,19 @@ lldb_private::ArchSpec GetArchitecture() override; - bool GetUUID(lldb_private::UUID *uuid) override; + lldb_private::UUID GetUUID() override; uint32_t GetDependentModules(lldb_private::FileSpecList &files) override; - virtual lldb_private::Address GetEntryPointAddress() override; + lldb_private::Address GetEntryPointAddress() override; + + lldb_private::Address GetBaseAddress() override; ObjectFile::Type CalculateType() override; ObjectFile::Strata CalculateStrata() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -209,10 +206,10 @@ data_dirs; // will contain num_data_dir_entries entries } coff_opt_header_t; - typedef enum coff_data_dir_type { + enum coff_data_dir_type { coff_data_dir_export_table = 0, coff_data_dir_import_table = 1, - } coff_data_dir_type; + }; typedef struct section_header { char name[8]; @@ -289,6 +286,7 @@ llvm::Optional<lldb_private::FileSpecList> m_deps_filespec; typedef llvm::object::OwningBinary<llvm::object::Binary> OWNBINType; llvm::Optional<OWNBINType> m_owningbin; + lldb_private::UUID m_uuid; }; #endif // liblldb_ObjectFilePECOFF_h_
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.cpp b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.cpp index e77888c..d5da60b 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.cpp +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.cpp
@@ -1,9 +1,8 @@ //===-- WindowsMiniDump.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.h b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.h index 135d533..9aaed69 100644 --- a/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.h +++ b/src/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.h
@@ -1,9 +1,8 @@ //===-- WindowsMiniDump.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp b/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp index 89a0f22..c1fe0cc 100644 --- a/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp +++ b/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp
@@ -1,15 +1,15 @@ //===-- OperatingSystemPython.cpp --------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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_DISABLE_PYTHON #include "OperatingSystemPython.h" + #include "Plugins/Process/Utility/DynamicRegisterInfo.h" #include "Plugins/Process/Utility/RegisterContextDummy.h" #include "Plugins/Process/Utility/RegisterContextMemory.h" @@ -32,6 +32,8 @@ #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StructuredData.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -52,12 +54,12 @@ FileSpec python_os_plugin_spec(process->GetPythonOSPluginPath()); if (python_os_plugin_spec && FileSystem::Instance().Exists(python_os_plugin_spec)) { - std::unique_ptr<OperatingSystemPython> os_ap( + std::unique_ptr<OperatingSystemPython> os_up( new OperatingSystemPython(process, python_os_plugin_spec)); - if (os_ap.get() && os_ap->IsValid()) - return os_ap.release(); + if (os_up.get() && os_up->IsValid()) + return os_up.release(); } - return NULL; + return nullptr; } ConstString OperatingSystemPython::GetPluginNameStatic() { @@ -72,15 +74,14 @@ OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process, const FileSpec &python_module_path) - : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_ap(), - m_interpreter(NULL), m_python_object_sp() { + : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_up(), + m_interpreter(nullptr), m_python_object_sp() { if (!process) return; TargetSP target_sp = process->CalculateTarget(); if (!target_sp) return; - m_interpreter = - target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); + m_interpreter = target_sp->GetDebugger().GetScriptInterpreter(); if (m_interpreter) { std::string os_plugin_class_name( @@ -114,9 +115,9 @@ OperatingSystemPython::~OperatingSystemPython() {} DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() { - if (m_register_info_ap.get() == NULL) { + if (m_register_info_up == nullptr) { if (!m_interpreter || !m_python_object_sp) - return NULL; + return nullptr; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS)); if (log) @@ -127,19 +128,17 @@ StructuredData::DictionarySP dictionary = m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp); if (!dictionary) - return NULL; + return nullptr; - m_register_info_ap.reset(new DynamicRegisterInfo( + m_register_info_up.reset(new DynamicRegisterInfo( *dictionary, m_process->GetTarget().GetArchitecture())); - assert(m_register_info_ap->GetNumRegisters() > 0); - assert(m_register_info_ap->GetNumRegisterSets() > 0); + assert(m_register_info_up->GetNumRegisters() > 0); + assert(m_register_info_up->GetNumRegisterSets() > 0); } - return m_register_info_ap.get(); + return m_register_info_up.get(); } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString OperatingSystemPython::GetPluginName() { return GetPluginNameStatic(); } @@ -199,9 +198,9 @@ StructuredData::ObjectSP thread_dict_obj = threads_list->GetItemAtIndex(i); if (auto thread_dict = thread_dict_obj->GetAsDictionary()) { - ThreadSP thread_sp( - CreateThreadFromThreadInfo(*thread_dict, core_thread_list, - old_thread_list, core_used_map, NULL)); + ThreadSP thread_sp(CreateThreadFromThreadInfo( + *thread_dict, core_thread_list, old_thread_list, core_used_map, + nullptr)); if (thread_sp) new_thread_list.AddThread(thread_sp); } @@ -260,8 +259,8 @@ if (!thread_sp) { if (did_create_ptr) *did_create_ptr = true; - thread_sp.reset( - new ThreadMemory(*m_process, tid, name, queue, reg_data_addr)); + thread_sp = std::make_shared<ThreadMemory>(*m_process, tid, name, queue, + reg_data_addr); } if (core_number < core_thread_list.GetSize(false)) { @@ -322,8 +321,8 @@ "= 0x%" PRIx64 ", 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64 ") creating memory register context", thread->GetID(), thread->GetProtocolID(), reg_data_addr); - reg_ctx_sp.reset(new RegisterContextMemory( - *thread, 0, *GetDynamicRegisterInfo(), reg_data_addr)); + reg_ctx_sp = std::make_shared<RegisterContextMemory>( + *thread, 0, *GetDynamicRegisterInfo(), reg_data_addr); } else { // No register data address is provided, query the python plug-in to let it // make up the data as it sees fit @@ -356,8 +355,8 @@ log->Printf("OperatingSystemPython::CreateRegisterContextForThread (tid " "= 0x%" PRIx64 ") forcing a dummy register context", thread->GetID()); - reg_ctx_sp.reset(new RegisterContextDummy( - *thread, 0, target.GetArchitecture().GetAddressByteSize())); + reg_ctx_sp = std::make_shared<RegisterContextDummy>( + *thread, 0, target.GetArchitecture().GetAddressByteSize()); } return reg_ctx_sp; }
diff --git a/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h b/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h index c812464..e76227d 100644 --- a/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h +++ b/src/llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h
@@ -1,9 +1,8 @@ //===-- OperatingSystemPython.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,9 +27,7 @@ ~OperatingSystemPython() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static lldb_private::OperatingSystem * CreateInstance(lldb_private::Process *process, bool force); @@ -42,16 +39,12 @@ static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // lldb_private::PluginInterface Methods - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - //------------------------------------------------------------------ // lldb_private::OperatingSystem Methods - //------------------------------------------------------------------ bool UpdateThreadList(lldb_private::ThreadList &old_thread_list, lldb_private::ThreadList &real_thread_list, lldb_private::ThreadList &new_thread_list) override; @@ -65,9 +58,7 @@ lldb::StopInfoSP CreateThreadStopReason(lldb_private::Thread *thread) override; - //------------------------------------------------------------------ // Method for lazy creation of threads on demand - //------------------------------------------------------------------ lldb::ThreadSP CreateThread(lldb::tid_t tid, lldb::addr_t context) override; protected: @@ -84,7 +75,7 @@ DynamicRegisterInfo *GetDynamicRegisterInfo(); lldb::ValueObjectSP m_thread_list_valobj_sp; - std::unique_ptr<DynamicRegisterInfo> m_register_info_ap; + std::unique_ptr<DynamicRegisterInfo> m_register_info_up; lldb_private::ScriptInterpreter *m_interpreter; lldb_private::StructuredData::ObjectSP m_python_object_sp; };
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.cpp b/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.cpp index 0ad30a5..e99018d 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.cpp
@@ -1,9 +1,8 @@ //===-- AdbClient.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.h b/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.h index 0d2100f..035796b 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/Android/AdbClient.h
@@ -1,9 +1,8 @@ //===-- AdbClient.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp index a56ab0e..3b8c920 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp
@@ -1,9 +1,8 @@ //===-- PlatformAndroid.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -303,7 +302,7 @@ const FileSpec &dst_file_spec) { // For oat file we can try to fetch additional debug info from the device ConstString extension = module_sp->GetFileSpec().GetFileNameExtension(); - if (extension != ConstString(".oat") && extension != ConstString(".odex")) + if (extension != ".oat" && extension != ".odex") return Status( "Symbol file downloading only supported for oat and odex files");
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.h b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.h index 2e7706c..b710a7f 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroid.h
@@ -1,9 +1,8 @@ //===-- PlatformAndroid.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,9 +29,7 @@ static void Terminate(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); @@ -43,9 +40,7 @@ uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ Status ConnectRemote(Args &args) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.cpp b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.cpp index bbb0336..e36527d 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.cpp
@@ -1,9 +1,8 @@ //===-- PlatformAndroidRemoteGDBServer.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.h b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.h index 4035629..c4421a3 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/Android/PlatformAndroidRemoteGDBServer.h
@@ -1,9 +1,8 @@ //===-- PlatformAndroidRemoteGDBServer.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Platform/CMakeLists.txt index ddb7121..5f284e5 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Platform/CMakeLists.txt
@@ -14,5 +14,4 @@ add_subdirectory(POSIX) add_subdirectory(gdb-server) -add_subdirectory(Kalimba) add_subdirectory(Android)
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp b/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp index 59cce3a..946f0ea 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp
@@ -1,9 +1,8 @@ //===-- PlatformFreeBSD.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -39,7 +38,6 @@ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ PlatformSP PlatformFreeBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); @@ -120,9 +118,7 @@ PlatformPOSIX::Terminate(); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformFreeBSD::PlatformFreeBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} @@ -266,7 +262,7 @@ Status &error) { lldb::ProcessSP process_sp; if (IsHost()) { - if (target == NULL) { + if (target == nullptr) { TargetSP new_target_sp; ArchSpec emptyArchSpec; @@ -283,7 +279,7 @@ // even when debugging locally we are debugging remotely! Just like the // darwin plugin. process_sp = target->CreateProcess( - attach_info.GetListenerForProcess(debugger), "gdb-remote", NULL); + attach_info.GetListenerForProcess(debugger), "gdb-remote", nullptr); if (process_sp) error = process_sp->Attach(attach_info);
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h b/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h index 2743048..e3a3aa7 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h
@@ -1,9 +1,8 @@ //===-- PlatformFreeBSD.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ static void Terminate(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); @@ -38,9 +35,7 @@ uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetPluginDescriptionStatic(IsHost()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/CMakeLists.txt deleted file mode 100644 index 02f1827..0000000 --- a/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/CMakeLists.txt +++ /dev/null
@@ -1,8 +0,0 @@ -add_lldb_library(lldbPluginPlatformKalimba PLUGIN - PlatformKalimba.cpp - - LINK_LIBS - lldbCore - lldbHost - lldbTarget - )
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.cpp b/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.cpp deleted file mode 100644 index cc902b7..0000000 --- a/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.cpp +++ /dev/null
@@ -1,154 +0,0 @@ -//===-- PlatformKalimba.cpp ---------------------------------------*- C++ -//-*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "PlatformKalimba.h" -#include "lldb/Host/Config.h" - -#include "lldb/Core/Debugger.h" -#include "lldb/Core/Module.h" -#include "lldb/Core/ModuleList.h" -#include "lldb/Core/ModuleSpec.h" -#include "lldb/Core/PluginManager.h" -#include "lldb/Host/HostInfo.h" -#include "lldb/Target/Process.h" -#include "lldb/Target/Target.h" -#include "lldb/Utility/FileSpec.h" -#include "lldb/Utility/Status.h" -#include "lldb/Utility/StreamString.h" - -using namespace lldb; -using namespace lldb_private; - -static uint32_t g_initialize_count = 0; - -PlatformSP PlatformKalimba::CreateInstance(bool force, const ArchSpec *arch) { - bool create = force; - if (!create && arch && arch->IsValid()) { - const llvm::Triple &triple = arch->GetTriple(); - switch (triple.getVendor()) { - case llvm::Triple::CSR: - create = true; - break; - - default: - break; - } - } - if (create) - return PlatformSP(new PlatformKalimba(false)); - return PlatformSP(); -} - -lldb_private::ConstString -PlatformKalimba::GetPluginNameStatic(bool /*is_host*/) { - static ConstString g_remote_name("kalimba"); - return g_remote_name; -} - -const char *PlatformKalimba::GetPluginDescriptionStatic(bool /*is_host*/) { - return "Kalimba user platform plug-in."; -} - -lldb_private::ConstString PlatformKalimba::GetPluginName() { - return GetPluginNameStatic(false); -} - -void PlatformKalimba::Initialize() { - Platform::Initialize(); - - if (g_initialize_count++ == 0) { - PluginManager::RegisterPlugin( - PlatformKalimba::GetPluginNameStatic(false), - PlatformKalimba::GetPluginDescriptionStatic(false), - PlatformKalimba::CreateInstance); - } -} - -void PlatformKalimba::Terminate() { - if (g_initialize_count > 0) { - if (--g_initialize_count == 0) { - PluginManager::UnregisterPlugin(PlatformKalimba::CreateInstance); - } - } - - Platform::Terminate(); -} - -//------------------------------------------------------------------ -/// Default Constructor -//------------------------------------------------------------------ -PlatformKalimba::PlatformKalimba(bool is_host) - : Platform(is_host), // This is the local host platform - m_remote_platform_sp() {} - -//------------------------------------------------------------------ -/// Destructor. -/// -/// The destructor is virtual since this class is designed to be -/// inherited from by the plug-in instance. -//------------------------------------------------------------------ -PlatformKalimba::~PlatformKalimba() {} - -bool PlatformKalimba::GetSupportedArchitectureAtIndex(uint32_t idx, - ArchSpec &arch) { - if (idx == 0) { - arch = ArchSpec("kalimba3-csr-unknown"); - return true; - } - if (idx == 1) { - arch = ArchSpec("kalimba4-csr-unknown"); - return true; - } - if (idx == 2) { - arch = ArchSpec("kalimba5-csr-unknown"); - return true; - } - return false; -} - -void PlatformKalimba::GetStatus(Stream &strm) { Platform::GetStatus(strm); } - -size_t -PlatformKalimba::GetSoftwareBreakpointTrapOpcode(Target & /*target*/, - BreakpointSite * /*bp_site*/) { - // the target hardware does not support software breakpoints - return 0; -} - -Status PlatformKalimba::LaunchProcess(ProcessLaunchInfo &launch_info) { - Status error; - - if (IsHost()) { - error.SetErrorString("native execution is not possible"); - } else { - error.SetErrorString("the platform is not currently connected"); - } - return error; -} - -lldb::ProcessSP PlatformKalimba::Attach(ProcessAttachInfo &attach_info, - Debugger &debugger, Target *target, - Status &error) { - lldb::ProcessSP process_sp; - if (IsHost()) { - error.SetErrorString("native execution is not possible"); - } else { - if (m_remote_platform_sp) - process_sp = - m_remote_platform_sp->Attach(attach_info, debugger, target, error); - else - error.SetErrorString("the platform is not currently connected"); - } - return process_sp; -} - -void PlatformKalimba::CalculateTrapHandlerSymbolNames() { - // TODO Research this sometime. -}
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.h b/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.h deleted file mode 100644 index efa7845..0000000 --- a/src/llvm-project/lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.h +++ /dev/null
@@ -1,75 +0,0 @@ -//===-- PlatformKalimba.h ---------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef liblldb_PlatformKalimba_h_ -#define liblldb_PlatformKalimba_h_ - -#include "lldb/Target/Platform.h" - -namespace lldb_private { - -class PlatformKalimba : public Platform { -public: - PlatformKalimba(bool is_host); - - ~PlatformKalimba() override; - - static void Initialize(); - - static void Terminate(); - - //------------------------------------------------------------ - // lldb_private::PluginInterface functions - //------------------------------------------------------------ - static lldb::PlatformSP CreateInstance(bool force, - const lldb_private::ArchSpec *arch); - - static lldb_private::ConstString GetPluginNameStatic(bool is_host); - - static const char *GetPluginDescriptionStatic(bool is_host); - - lldb_private::ConstString GetPluginName() override; - - uint32_t GetPluginVersion() override { return 1; } - - //------------------------------------------------------------ - // lldb_private::Platform functions - //------------------------------------------------------------ - const char *GetDescription() override { - return GetPluginDescriptionStatic(IsHost()); - } - - void GetStatus(Stream &strm) override; - - bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) override; - - size_t GetSoftwareBreakpointTrapOpcode(Target &target, - BreakpointSite *bp_site) override; - - lldb_private::Status - LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) override; - - lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, - Target *target, Status &error) override; - - // Kalimba processes can not be launched by spawning and attaching. - bool CanDebugProcess() override { return false; } - - void CalculateTrapHandlerSymbolNames() override; - -protected: - lldb::PlatformSP m_remote_platform_sp; - -private: - DISALLOW_COPY_AND_ASSIGN(PlatformKalimba); -}; - -} // namespace lldb_private - -#endif // liblldb_PlatformKalimba_h_
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.cpp b/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.cpp index 7498c648..d0ad2f3 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.cpp
@@ -1,9 +1,8 @@ //===-- PlatformLinux.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -37,7 +36,6 @@ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ PlatformSP PlatformLinux::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); @@ -119,9 +117,7 @@ PlatformPOSIX::Terminate(); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformLinux::PlatformLinux(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} @@ -241,7 +237,7 @@ // Figure out what shell we're planning on using. const char *shell_name = strrchr(shell_string.c_str(), '/'); - if (shell_name == NULL) + if (shell_name == nullptr) shell_name = shell_string.c_str(); else shell_name++; @@ -264,6 +260,25 @@ } } +std::vector<std::string> +PlatformLinux::GetSystemIncludeDirectories(lldb::LanguageType lang) { + std::string sys_root = GetSDKRootDirectory().AsCString(""); + switch (lang) { + case lldb::eLanguageTypeC: + case lldb::eLanguageTypeC89: + case lldb::eLanguageTypeC99: + case lldb::eLanguageTypeC11: + case lldb::eLanguageTypeC_plus_plus: + case lldb::eLanguageTypeC_plus_plus_03: + case lldb::eLanguageTypeC_plus_plus_11: + case lldb::eLanguageTypeC_plus_plus_14: + case lldb::eLanguageTypeObjC_plus_plus: + return {sys_root + "/usr/include/"}; + default: + return {}; + } +} + // For local debugging, Linux will override the debug logic to use llgs-launch // rather than lldb-launch, llgs-attach. This differs from current lldb- // launch, debugserver-attach approach on MacOSX. @@ -357,7 +372,7 @@ // Handle the hijacking of process events. if (listener_sp) { const StateType state = process_sp->WaitForProcessToStop( - llvm::None, NULL, false, listener_sp); + llvm::None, nullptr, false, listener_sp); LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state); } @@ -388,14 +403,7 @@ unsigned prot, unsigned flags, addr_t fd, addr_t offset) { uint64_t flags_platform = 0; - uint64_t map_anon = MAP_ANON; - - // To get correct flags for MIPS Architecture - if (arch.GetTriple().getArch() == llvm::Triple::mips64 || - arch.GetTriple().getArch() == llvm::Triple::mips64el || - arch.GetTriple().getArch() == llvm::Triple::mips || - arch.GetTriple().getArch() == llvm::Triple::mipsel) - map_anon = 0x800; + uint64_t map_anon = arch.IsMIPS() ? 0x800 : MAP_ANON; if (flags & eMmapFlagsPrivate) flags_platform |= MAP_PRIVATE;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.h b/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.h index 50d721f..a843558 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/Linux/PlatformLinux.h
@@ -1,9 +1,8 @@ //===-- PlatformLinux.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ static void Terminate(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); @@ -38,9 +35,7 @@ uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetPluginDescriptionStatic(IsHost()); } @@ -53,6 +48,9 @@ bool CanDebugProcess() override; + std::vector<std::string> + GetSystemIncludeDirectories(lldb::LanguageType lang) override; + lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, Status &error) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.cpp index a2f74a5..12a63f0 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.cpp
@@ -1,9 +1,8 @@ //===-- PlatformAppleSimulator.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,26 +28,20 @@ #define UNSUPPORTED_ERROR ("Apple simulators aren't supported on this platform") #endif -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformAppleSimulator::Initialize() { PlatformDarwin::Initialize(); } void PlatformAppleSimulator::Terminate() { PlatformDarwin::Terminate(); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformAppleSimulator::PlatformAppleSimulator() : PlatformDarwin(true), m_core_sim_path_mutex(), m_core_simulator_framework_path(), m_device() {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformAppleSimulator::~PlatformAppleSimulator() {} lldb_private::Status PlatformAppleSimulator::LaunchProcess(
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.h index daae376..ec5f157 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.h
@@ -1,9 +1,8 @@ //===-- PlatformAppleSimulator.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,16 +19,12 @@ class PlatformAppleSimulator : public PlatformDarwin { public: - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static void Initialize(); static void Terminate(); - //------------------------------------------------------------ // Class Methods - //------------------------------------------------------------ PlatformAppleSimulator(); virtual ~PlatformAppleSimulator();
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.cpp index 62bd3c3..6fc9d38 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.cpp
@@ -1,9 +1,8 @@ //===-- PlatformAppleTVSimulator.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,11 +15,11 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" @@ -29,14 +28,14 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ +namespace lldb_private { +class Process; +} + // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformAppleTVSimulator::Initialize() { PlatformDarwin::Initialize(); @@ -144,18 +143,14 @@ return "Apple TV simulator platform plug-in."; } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformAppleTVSimulator::PlatformAppleTVSimulator() : PlatformDarwin(true), m_sdk_dir_mutex(), m_sdk_directory() {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformAppleTVSimulator::~PlatformAppleTVSimulator() {} void PlatformAppleTVSimulator::GetStatus(Stream &strm) {
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.h index 9a4da58..0005eab 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.h
@@ -1,9 +1,8 @@ //===-- PlatformAppleTVSimulator.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ class PlatformAppleTVSimulator : public PlatformDarwin { public: - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -28,25 +25,19 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // Class Methods - //------------------------------------------------------------ PlatformAppleTVSimulator(); virtual ~PlatformAppleTVSimulator(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ lldb_private::Status ResolveExecutable( const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const lldb_private::FileSpecList *module_search_paths_ptr) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.cpp index ec112cc..7f271a0 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.cpp
@@ -1,9 +1,8 @@ //===-- PlatformAppleWatchSimulator.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,24 +16,24 @@ #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" -#include "lldb/Target/Target.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ +namespace lldb_private { +class Process; +} + // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformAppleWatchSimulator::Initialize() { PlatformDarwin::Initialize(); @@ -144,18 +143,14 @@ return "Apple Watch simulator platform plug-in."; } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformAppleWatchSimulator::PlatformAppleWatchSimulator() : PlatformDarwin(true), m_sdk_directory() {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformAppleWatchSimulator::~PlatformAppleWatchSimulator() {} void PlatformAppleWatchSimulator::GetStatus(Stream &strm) {
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.h index c240a09..d8ffa05 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.h
@@ -1,9 +1,8 @@ //===-- PlatformAppleWatchSimulator.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ class PlatformAppleWatchSimulator : public PlatformDarwin { public: - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -28,25 +25,19 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // Class Methods - //------------------------------------------------------------ PlatformAppleWatchSimulator(); virtual ~PlatformAppleWatchSimulator(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ lldb_private::Status ResolveExecutable( const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const lldb_private::FileSpecList *module_search_paths_ptr) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp index 3868d97..9559871 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp
@@ -1,9 +1,8 @@ //===-- PlatformDarwin.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,6 +11,7 @@ #include <string.h> #include <algorithm> +#include <memory> #include <mutex> #include "lldb/Breakpoint/BreakpointLocation.h" @@ -21,9 +21,9 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Host/Symbols.h" #include "lldb/Host/XML.h" #include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/SymbolVendor.h" @@ -31,6 +31,7 @@ #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Timer.h" #include "llvm/ADT/STLExtras.h" @@ -45,19 +46,15 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformDarwin::PlatformDarwin(bool is_host) : PlatformPOSIX(is_host), // This is the local host platform m_developer_directory() {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformDarwin::~PlatformDarwin() {} FileSpecList PlatformDarwin::LocateExecutableScriptingResources( @@ -71,8 +68,6 @@ // precisely that. Ideally, we should have a per-platform list of // extensions (".exe", ".app", ".dSYM", ".framework") which should be // stripped while leaving "this.binary.file" as-is. - ScriptInterpreter *script_interpreter = - target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); FileSpec module_spec = module.GetFileSpec(); @@ -84,7 +79,10 @@ ObjectFile *objfile = symfile->GetObjectFile(); if (objfile) { FileSpec symfile_spec(objfile->GetFileSpec()); - if (symfile_spec && FileSystem::Instance().Exists(symfile_spec)) { + if (symfile_spec && + strcasestr (symfile_spec.GetPath().c_str(), + ".dSYM/Contents/Resources/DWARF") != nullptr && + FileSystem::Instance().Exists(symfile_spec)) { while (module_spec.GetFilename()) { std::string module_basename( module_spec.GetFilename().GetCString()); @@ -106,6 +104,8 @@ ' ', '_'); std::replace(module_basename.begin(), module_basename.end(), '-', '_'); + ScriptInterpreter *script_interpreter = + target->GetDebugger().GetScriptInterpreter(); if (script_interpreter && script_interpreter->IsReservedWord( module_basename.c_str())) { @@ -263,7 +263,7 @@ module_spec.GetFileSpec().GetFilename().AsCString()); ModuleSpec local_spec(module_cache_spec, module_spec.GetArchitecture()); - module_sp.reset(new Module(local_spec)); + module_sp = std::make_shared<Module>(local_spec); module_sp->SetPlatformFileSpec(module_spec.GetFileSpec()); return Status(); } @@ -301,7 +301,7 @@ } ModuleSpec local_spec(module_cache_spec, module_spec.GetArchitecture()); - module_sp.reset(new Module(local_spec)); + module_sp = std::make_shared<Module>(local_spec); module_sp->SetPlatformFileSpec(module_spec.GetFileSpec()); Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) @@ -329,7 +329,7 @@ module_spec.GetFileSpec().GetDirectory().AsCString(), module_spec.GetFileSpec().GetFilename().AsCString()); ModuleSpec local_spec(module_cache_spec, module_spec.GetArchitecture()); - module_sp.reset(new Module(local_spec)); + module_sp = std::make_shared<Module>(local_spec); module_sp->SetPlatformFileSpec(module_spec.GetFileSpec()); return Status(); } else @@ -374,7 +374,7 @@ new_module_spec.GetFileSpec() = bundle_directory; if (Host::ResolveExecutableInBundle(new_module_spec.GetFileSpec())) { Status new_error(Platform::GetSharedModule( - new_module_spec, process, module_sp, NULL, old_module_sp_ptr, + new_module_spec, process, module_sp, nullptr, old_module_sp_ptr, did_create_ptr)); if (module_sp) @@ -401,7 +401,7 @@ ModuleSpec new_module_spec(module_spec); new_module_spec.GetFileSpec() = new_file_spec; Status new_error(Platform::GetSharedModule( - new_module_spec, process, module_sp, NULL, + new_module_spec, process, module_sp, nullptr, old_module_sp_ptr, did_create_ptr)); if (module_sp) { @@ -1171,7 +1171,7 @@ std::string command_output; Status error = Host::RunShellCommand("/usr/bin/xcode-select --print-path", - NULL, // current working directory + nullptr, // current working directory &exit_status, &signo, &command_output, std::chrono::seconds(2), // short timeout false); // don't run in a shell @@ -1212,7 +1212,7 @@ assert(m_developer_directory.empty() == false); if (m_developer_directory[0]) return m_developer_directory.c_str(); - return NULL; + return nullptr; } BreakpointSP PlatformDarwin::SetThreadCreationBreakpoint(Target &target) { @@ -1233,7 +1233,7 @@ bool internal = true; bool hardware = false; LazyBool skip_prologue = eLazyBoolNo; - bp_sp = target.CreateBreakpoint(&bp_modules, NULL, g_bp_names, + bp_sp = target.CreateBreakpoint(&bp_modules, nullptr, g_bp_names, llvm::array_lengthof(g_bp_names), eFunctionNameTypeFull, eLanguageTypeUnknown, 0, skip_prologue, internal, hardware); @@ -1250,7 +1250,7 @@ std::string shell_string = shell.GetPath(); const char *shell_name = strrchr(shell_string.c_str(), '/'); - if (shell_name == NULL) + if (shell_name == nullptr) shell_name = shell_string.c_str(); else shell_name++; @@ -1341,7 +1341,7 @@ const char *command = "/usr/bin/xcode-select -p"; lldb_private::Status error = Host::RunShellCommand( command, // shell command to run - NULL, // current working directory + nullptr, // current working directory &status, // Put the exit status of the process in here &signo, // Put the signal that caused the process to exit in here &output, // Get the output from the command and place it in this @@ -1700,12 +1700,12 @@ // "UIFoundation" and "UIFoundation.framework" -- most likely the latter // will be the one we find there. - FileSpec platform_pull_apart(platform_file); + FileSpec platform_pull_upart(platform_file); std::vector<std::string> path_parts; path_parts.push_back( - platform_pull_apart.GetLastPathComponent().AsCString()); - while (platform_pull_apart.RemoveLastPathComponent()) { - ConstString part = platform_pull_apart.GetLastPathComponent(); + platform_pull_upart.GetLastPathComponent().AsCString()); + while (platform_pull_upart.RemoveLastPathComponent()) { + ConstString part = platform_pull_upart.GetLastPathComponent(); path_parts.push_back(part.AsCString()); } const size_t path_parts_size = path_parts.size(); @@ -1742,7 +1742,7 @@ ModuleSpec new_module_spec(module_spec); new_module_spec.GetFileSpec() = path_to_try; Status new_error(Platform::GetSharedModule( - new_module_spec, process, module_sp, NULL, old_module_sp_ptr, + new_module_spec, process, module_sp, nullptr, old_module_sp_ptr, did_create_ptr)); if (module_sp) {
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.h index f2dd9b1..ccf6853 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.h
@@ -1,9 +1,8 @@ //===-- PlatformDarwin.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,9 +25,7 @@ ~PlatformDarwin() override; - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ lldb_private::Status ResolveSymbolFile(lldb_private::Target &target, const lldb_private::ModuleSpec &sym_spec,
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp index 4c6d945..cb453b5 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp
@@ -1,10 +1,9 @@ //===-- PlatformDarwinKernel.cpp -----------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,19 +35,17 @@ #include <CoreFoundation/CoreFoundation.h> +#include <memory> + #include "Host/macosx/cfcpp/CFCBundle.h" using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformDarwinKernel::Initialize() { PlatformDarwin::Initialize(); @@ -179,9 +176,7 @@ return "Darwin Kernel platform plug-in."; } -//------------------------------------------------------------------ /// Code to handle the PlatformDarwinKernel settings -//------------------------------------------------------------------ static constexpr PropertyDefinition g_properties[] = { {"search-locally-for-kexts", OptionValue::eTypeBoolean, true, true, NULL, @@ -201,7 +196,7 @@ } PlatformDarwinKernelProperties() : Properties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); } @@ -213,9 +208,9 @@ NULL, idx, g_properties[idx].default_uint_value != 0); } - FileSpecList &GetKextDirectories() const { + FileSpecList GetKextDirectories() const { const uint32_t idx = ePropertyKextDirectories; - OptionValueFileSpecList *option_value = + const OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList( NULL, false, idx); assert(option_value); @@ -229,7 +224,7 @@ static const PlatformDarwinKernelPropertiesSP &GetGlobalProperties() { static PlatformDarwinKernelPropertiesSP g_settings_sp; if (!g_settings_sp) - g_settings_sp.reset(new PlatformDarwinKernelProperties()); + g_settings_sp = std::make_shared<PlatformDarwinKernelProperties>(); return g_settings_sp; } @@ -245,9 +240,7 @@ } } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformDarwinKernel::PlatformDarwinKernel( lldb_private::LazyBool is_ios_debug_session) : PlatformDarwin(false), // This is a remote platform @@ -264,12 +257,10 @@ } } -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformDarwinKernel::~PlatformDarwinKernel() {} void PlatformDarwinKernel::GetStatus(Stream &strm) {
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.h index 201c3df..31c13d2 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.h
@@ -1,9 +1,8 @@ //===-- PlatformDarwinKernel.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,9 +22,7 @@ class PlatformDarwinKernel : public PlatformDarwin { public: - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -39,25 +36,19 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // Class Methods - //------------------------------------------------------------ PlatformDarwinKernel(lldb_private::LazyBool is_ios_debug_session); virtual ~PlatformDarwinKernel(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetDescriptionStatic(); } void GetStatus(lldb_private::Stream &strm) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.cpp index 4117231..51908fa 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.cpp
@@ -1,9 +1,8 @@ //===-- PlatformMacOSX.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -147,17 +146,13 @@ return "Remote Mac OS X user platform plug-in."; } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformMacOSX::PlatformMacOSX(bool is_host) : PlatformDarwin(is_host) {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformMacOSX::~PlatformMacOSX() {} ConstString PlatformMacOSX::GetSDKDirectory(lldb_private::Target &target) { @@ -168,8 +163,8 @@ std::string xcode_contents_path; std::string default_xcode_sdk; FileSpec fspec; - uint32_t versions[2]; - if (objfile->GetSDKVersion(versions, sizeof(versions))) { + llvm::VersionTuple version = objfile->GetSDKVersion(); + if (!version.empty()) { fspec = HostInfo::GetShlibDir(); if (fspec) { std::string path; @@ -188,7 +183,7 @@ const char *command = "xcrun -sdk macosx --show-sdk-path"; lldb_private::Status error = RunShellCommand( command, // shell command to run - NULL, // current working directory + nullptr, // current working directory &status, // Put the exit status of the process in here &signo, // Put the signal that caused the process to exit in // here @@ -213,8 +208,8 @@ StreamString sdk_path; sdk_path.Printf("%sDeveloper/Platforms/MacOSX.platform/Developer/" "SDKs/MacOSX%u.%u.sdk", - xcode_contents_path.c_str(), versions[0], - versions[1]); + xcode_contents_path.c_str(), version.getMajor(), + version.getMinor().getValue()); fspec.SetFile(sdk_path.GetString(), FileSpec::Style::native); if (FileSystem::Instance().Exists(fspec)) return ConstString(sdk_path.GetString()); @@ -314,7 +309,7 @@ if (module_spec.GetArchitecture().GetCore() == ArchSpec::eCore_x86_64_x86_64h) { ObjectFile *objfile = module_sp->GetObjectFile(); - if (objfile == NULL) { + if (objfile == nullptr) { // We didn't find an x86_64h slice, fall back to a x86_64 slice ModuleSpec module_spec_x86_64(module_spec); module_spec_x86_64.GetArchitecture() = ArchSpec("x86_64-apple-macosx");
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.h index d08029a..5e942f0 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.h
@@ -1,9 +1,8 @@ //===-- PlatformMacOSX.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,9 +17,7 @@ ~PlatformMacOSX() override; - //------------------------------------------------------------ // Class functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -32,9 +29,7 @@ static const char *GetDescriptionStatic(bool is_host); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(IsHost()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.cpp index fd804d0..8b45a86 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.cpp
@@ -1,9 +1,8 @@ //===-- PlatformRemoteAppleBridge.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,20 +27,14 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformRemoteAppleBridge::PlatformRemoteAppleBridge() : PlatformRemoteDarwinDevice () {} -//------------------------------------------------------------------ // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformRemoteAppleBridge::Initialize() { PlatformDarwin::Initialize();
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.h index 48f06ee..3ecd20f 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.h
@@ -1,9 +1,8 @@ //===-- PlatformRemoteAppleBridge.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ ~PlatformRemoteAppleBridge() override = default; - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -38,18 +35,14 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetDescriptionStatic(); } @@ -58,9 +51,7 @@ protected: - //------------------------------------------------------------ // lldb_private::PlatformRemoteDarwinDevice functions - //------------------------------------------------------------ void GetDeviceSupportDirectoryNames (std::vector<std::string> &dirnames) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.cpp index 593e888..5b50acd 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.cpp
@@ -1,9 +1,8 @@ //===-- PlatformRemoteAppleTV.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,20 +28,14 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformRemoteAppleTV::PlatformRemoteAppleTV() : PlatformRemoteDarwinDevice () {} -//------------------------------------------------------------------ // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformRemoteAppleTV::Initialize() { PlatformDarwin::Initialize();
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.h index d8860a9..ce2e164 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.h
@@ -1,9 +1,8 @@ //===-- PlatformRemoteAppleTV.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ ~PlatformRemoteAppleTV() override = default; - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -38,18 +35,14 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetDescriptionStatic(); } @@ -58,9 +51,7 @@ protected: - //------------------------------------------------------------ // lldb_private::PlatformRemoteDarwinDevice functions - //------------------------------------------------------------ void GetDeviceSupportDirectoryNames (std::vector<std::string> &dirnames) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.cpp index 59e6e19..5dec3a0 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.cpp
@@ -1,9 +1,8 @@ //===-- PlatformRemoteAppleWatch.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,14 +28,10 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformRemoteAppleWatch::Initialize() { PlatformDarwin::Initialize(); @@ -150,9 +145,7 @@ return "Remote Apple Watch platform plug-in."; } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformRemoteAppleWatch::PlatformRemoteAppleWatch() : PlatformRemoteDarwinDevice() {}
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.h index ed1cbea..6cd470d 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.h
@@ -1,9 +1,8 @@ //===-- PlatformRemoteAppleWatch.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ ~PlatformRemoteAppleWatch() override = default; - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -39,33 +36,25 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetDescriptionStatic(); } - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ bool GetSupportedArchitectureAtIndex(uint32_t idx, lldb_private::ArchSpec &arch) override; protected: - //------------------------------------------------------------ // lldb_private::PlatformRemoteDarwinDevice functions - //------------------------------------------------------------ void GetDeviceSupportDirectoryNames (std::vector<std::string> &dirnames) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.cpp index 511bfc2..439ca8f 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.cpp
@@ -1,9 +1,8 @@ //===-- PlatformRemoteDarwinDevice.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,9 +34,7 @@ build.SetString(build_str); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformRemoteDarwinDevice::PlatformRemoteDarwinDevice() : PlatformDarwin(false), // This is a remote platform m_sdk_directory_infos(), m_device_support_directory(), @@ -45,12 +42,10 @@ m_last_module_sdk_idx(UINT32_MAX), m_connected_module_sdk_idx(UINT32_MAX) {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformRemoteDarwinDevice::~PlatformRemoteDarwinDevice() {} void PlatformRemoteDarwinDevice::GetStatus(Stream &strm) { @@ -86,7 +81,7 @@ if (resolved_module_spec.GetArchitecture().IsValid() || resolved_module_spec.GetUUID().IsValid()) { error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp, - NULL, NULL, NULL); + nullptr, nullptr, nullptr); if (exe_module_sp && exe_module_sp->GetObjectFile()) return error; @@ -100,7 +95,7 @@ idx, resolved_module_spec.GetArchitecture()); ++idx) { error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp, - NULL, NULL, NULL); + nullptr, nullptr, nullptr); // Did we find an executable using one of the if (error.Success()) { if (exe_module_sp && exe_module_sp->GetObjectFile()) @@ -313,12 +308,12 @@ return &m_sdk_directory_infos[i]; } } - return NULL; + return nullptr; } const PlatformRemoteDarwinDevice::SDKDirectoryInfo * PlatformRemoteDarwinDevice::GetSDKDirectoryForLatestOSVersion() { - const PlatformRemoteDarwinDevice::SDKDirectoryInfo *result = NULL; + const PlatformRemoteDarwinDevice::SDKDirectoryInfo *result = nullptr; if (UpdateSDKDirectoryInfosIfNeeded()) { auto max = std::max_element( m_sdk_directory_infos.begin(), m_sdk_directory_infos.end(), @@ -349,7 +344,7 @@ assert(m_device_support_directory.empty() == false); if (m_device_support_directory[0]) return m_device_support_directory.c_str(); - return NULL; + return nullptr; } const char *PlatformRemoteDarwinDevice::GetDeviceSupportDirectoryForOSVersion() { @@ -359,7 +354,7 @@ if (m_device_support_directory_for_os_version.empty()) { const PlatformRemoteDarwinDevice::SDKDirectoryInfo *sdk_dir_info = GetSDKDirectoryForCurrentOSVersion(); - if (sdk_dir_info == NULL) + if (sdk_dir_info == nullptr) sdk_dir_info = GetSDKDirectoryForLatestOSVersion(); if (sdk_dir_info) { char path[PATH_MAX]; @@ -379,7 +374,7 @@ assert(m_device_support_directory_for_os_version.empty() == false); if (m_device_support_directory_for_os_version[0]) return m_device_support_directory_for_os_version.c_str(); - return NULL; + return nullptr; } uint32_t PlatformRemoteDarwinDevice::FindFileInAllSDKs(const char *platform_file_path, @@ -528,7 +523,7 @@ if (GetFileInSDK(platform_file_path, connected_sdk_idx, platform_module_spec.GetFileSpec())) { module_sp.reset(); - error = ResolveExecutable(platform_module_spec, module_sp, NULL); + error = ResolveExecutable(platform_module_spec, module_sp, nullptr); if (module_sp) { m_last_module_sdk_idx = connected_sdk_idx; error.Clear(); @@ -545,7 +540,7 @@ if (GetFileInSDK(platform_file_path, m_last_module_sdk_idx, platform_module_spec.GetFileSpec())) { module_sp.reset(); - error = ResolveExecutable(platform_module_spec, module_sp, NULL); + error = ResolveExecutable(platform_module_spec, module_sp, nullptr); if (module_sp) { error.Clear(); return error; @@ -567,7 +562,7 @@ if (GetFileInSDK(platform_file_path, current_sdk_idx, platform_module_spec.GetFileSpec())) { module_sp.reset(); - error = ResolveExecutable(platform_module_spec, module_sp, NULL); + error = ResolveExecutable(platform_module_spec, module_sp, nullptr); if (module_sp) { m_last_module_sdk_idx = current_sdk_idx; error.Clear(); @@ -588,7 +583,7 @@ platform_module_spec.GetFileSpec())) { // printf ("sdk[%u]: '%s'\n", sdk_idx, local_file.GetPath().c_str()); - error = ResolveExecutable(platform_module_spec, module_sp, NULL); + error = ResolveExecutable(platform_module_spec, module_sp, nullptr); if (module_sp) { // Remember the index of the last SDK that we found a file in in case // the wrong SDK was selected. @@ -653,7 +648,7 @@ uint32_t PlatformRemoteDarwinDevice::GetSDKIndexBySDKDirectoryInfo( const SDKDirectoryInfo *sdk_info) { - if (sdk_info == NULL) { + if (sdk_info == nullptr) { return UINT32_MAX; }
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.h index d32179d..5e0b7d9 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteDarwinDevice.h
@@ -1,9 +1,8 @@ //===-- PlatformRemoteDarwinDevice.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,9 +22,7 @@ ~PlatformRemoteDarwinDevice() override; - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ lldb_private::Status ResolveExecutable( const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const lldb_private::FileSpecList *module_search_paths_ptr) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp index b69d7ea..9e916d8 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp
@@ -1,9 +1,8 @@ //===-- PlatformRemoteiOS.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,14 +25,10 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformRemoteiOS::Initialize() { PlatformDarwin::Initialize(); @@ -137,9 +132,7 @@ return "Remote iOS platform plug-in."; } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformRemoteiOS::PlatformRemoteiOS() : PlatformRemoteDarwinDevice() {}
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.h index 7e45dc3..a0eb523 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.h
@@ -1,9 +1,8 @@ //===-- PlatformRemoteiOS.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,9 +22,7 @@ ~PlatformRemoteiOS() override = default; - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -37,15 +34,11 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetDescriptionStatic(); } - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } @@ -57,9 +50,7 @@ protected: - //------------------------------------------------------------ // lldb_private::PlatformRemoteDarwinDevice functions - //------------------------------------------------------------ void GetDeviceSupportDirectoryNames (std::vector<std::string> &dirnames) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.cpp b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.cpp index b1d5960..e455edd 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.cpp
@@ -1,10 +1,9 @@ //===-- PlatformiOSSimulator.cpp -----------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,11 +16,11 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" @@ -30,14 +29,14 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ +namespace lldb_private { +class Process; +} + // Static Variables -//------------------------------------------------------------------ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ // Static Functions -//------------------------------------------------------------------ void PlatformiOSSimulator::Initialize() { PlatformAppleSimulator::Initialize(); @@ -148,19 +147,15 @@ return "iOS simulator platform plug-in."; } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformiOSSimulator::PlatformiOSSimulator() : PlatformAppleSimulator(), m_sdk_dir_mutex(), m_sdk_directory(), m_build_update() {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformiOSSimulator::~PlatformiOSSimulator() {} void PlatformiOSSimulator::GetStatus(Stream &strm) {
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.h index 4ac43a4..d766929 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.h
@@ -1,9 +1,8 @@ //===-- PlatformiOSSimulator.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,9 +20,7 @@ ~PlatformiOSSimulator() override; - //------------------------------------------------------------ // Class Functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -35,18 +32,14 @@ static const char *GetDescriptionStatic(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ lldb_private::ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ lldb_private::Status ResolveExecutable( const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const lldb_private::FileSpecList *module_search_paths_ptr) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.h b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.h index bec35aa..0a75371 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.h
@@ -1,10 +1,9 @@ //===-- PlatformiOSSimulatorCoreSimulatorSupport.h ----------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,7 +19,7 @@ #else typedef void *id; #endif -#include "lldb/Target/ProcessLaunchInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Status.h"
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.mm b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.mm index a601e27..ed18a1c 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.mm +++ b/src/llvm-project/lldb/source/Plugins/Platform/MacOSX/objcxx/PlatformiOSSimulatorCoreSimulatorSupport.mm
@@ -1,10 +1,9 @@ //===-- PlatformiOSSimulatorCoreSimulatorSupport.cpp ---------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,7 +16,7 @@ #include <Foundation/Foundation.h> // Project includes #include "lldb/Host/PseudoTerminal.h" -#include "lldb/Target/FileAction.h" +#include "lldb/Host/FileAction.h" #include "llvm/ADT/StringRef.h"
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp b/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp index aadcf96..63245d1 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp
@@ -1,9 +1,8 @@ //===-- PlatformNetBSD.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -37,7 +36,6 @@ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ PlatformSP PlatformNetBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); @@ -112,9 +110,7 @@ PlatformPOSIX::Terminate(); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformNetBSD::PlatformNetBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} @@ -210,7 +206,7 @@ // Figure out what shell we're planning on using. const char *shell_name = strrchr(shell_string.c_str(), '/'); - if (shell_name == NULL) + if (shell_name == nullptr) shell_name = shell_string.c_str(); else shell_name++; @@ -326,7 +322,7 @@ // Handle the hijacking of process events. if (listener_sp) { const StateType state = process_sp->WaitForProcessToStop( - llvm::None, NULL, false, listener_sp); + llvm::None, nullptr, false, listener_sp); LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state); }
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h b/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h index 28a5d67..0584d92 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h
@@ -1,9 +1,8 @@ //===-- PlatformNetBSD.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ static void Terminate(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); @@ -38,9 +35,7 @@ uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetPluginDescriptionStatic(IsHost()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp b/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp index 7358acb..9dfb884 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp
@@ -1,9 +1,8 @@ //===-- PlatformOpenBSD.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -37,7 +36,6 @@ static uint32_t g_initialize_count = 0; -//------------------------------------------------------------------ PlatformSP PlatformOpenBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); @@ -118,9 +116,7 @@ PlatformPOSIX::Terminate(); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformOpenBSD::PlatformOpenBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {}
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.h b/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.h index cb5e9bf..3cb724f 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.h
@@ -1,9 +1,8 @@ //===-- PlatformOpenBSD.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ static void Terminate(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); @@ -38,9 +35,7 @@ uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ const char *GetDescription() override { return GetPluginDescriptionStatic(IsHost()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp b/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp index bfa1376..d105575 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp
@@ -1,15 +1,13 @@ //===-- PlatformPOSIX.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "PlatformPOSIX.h" - #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" @@ -23,11 +21,11 @@ #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/DynamicLoader.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" -#include "lldb/Target/ProcessLaunchInfo.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/CleanUp.h" #include "lldb/Utility/DataBufferHeap.h" @@ -38,34 +36,19 @@ using namespace lldb; using namespace lldb_private; -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformPOSIX::PlatformPOSIX(bool is_host) - : Platform(is_host), // This is the local host platform + : RemoteAwarePlatform(is_host), // This is the local host platform m_option_group_platform_rsync(new OptionGroupPlatformRSync()), m_option_group_platform_ssh(new OptionGroupPlatformSSH()), - m_option_group_platform_caching(new OptionGroupPlatformCaching()), - m_remote_platform_sp() {} + m_option_group_platform_caching(new OptionGroupPlatformCaching()) {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformPOSIX::~PlatformPOSIX() {} -bool PlatformPOSIX::GetModuleSpec(const FileSpec &module_file_spec, - const ArchSpec &arch, - ModuleSpec &module_spec) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetModuleSpec(module_file_spec, arch, - module_spec); - - return Platform::GetModuleSpec(module_file_spec, arch, module_spec); -} - lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions( lldb_private::CommandInterpreter &interpreter) { auto iter = m_options.find(&interpreter), end = m_options.end(); @@ -81,36 +64,6 @@ return m_options.at(&interpreter).get(); } -bool PlatformPOSIX::IsConnected() const { - if (IsHost()) - return true; - else if (m_remote_platform_sp) - return m_remote_platform_sp->IsConnected(); - return false; -} - -lldb_private::Status PlatformPOSIX::RunShellCommand( - const char *command, // Shouldn't be NULL - const FileSpec & - working_dir, // Pass empty FileSpec to use the current working directory - int *status_ptr, // Pass NULL if you don't want the process exit status - int *signo_ptr, // Pass NULL if you don't want the signal that caused the - // process to exit - std::string - *command_output, // Pass NULL if you don't want the command output - const Timeout<std::micro> &timeout) { - if (IsHost()) - return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr, - command_output, timeout); - else { - if (m_remote_platform_sp) - return m_remote_platform_sp->RunShellCommand( - command, working_dir, status_ptr, signo_ptr, command_output, timeout); - else - return Status("unable to run a remote command without a platform"); - } -} - Status PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec, lldb::ModuleSP &exe_module_sp, @@ -253,105 +206,6 @@ return error; } -Status PlatformPOSIX::GetFileWithUUID(const FileSpec &platform_file, - const UUID *uuid_ptr, - FileSpec &local_file) { - if (IsRemote() && m_remote_platform_sp) - return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr, - local_file); - - // Default to the local case - local_file = platform_file; - return Status(); -} - -bool PlatformPOSIX::GetProcessInfo(lldb::pid_t pid, - ProcessInstanceInfo &process_info) { - if (IsHost()) - return Platform::GetProcessInfo(pid, process_info); - if (m_remote_platform_sp) - return m_remote_platform_sp->GetProcessInfo(pid, process_info); - return false; -} - -uint32_t -PlatformPOSIX::FindProcesses(const ProcessInstanceInfoMatch &match_info, - ProcessInstanceInfoList &process_infos) { - if (IsHost()) - return Platform::FindProcesses(match_info, process_infos); - if (m_remote_platform_sp) - return - m_remote_platform_sp->FindProcesses(match_info, process_infos); - return 0; -} - -Status PlatformPOSIX::MakeDirectory(const FileSpec &file_spec, - uint32_t file_permissions) { - if (m_remote_platform_sp) - return m_remote_platform_sp->MakeDirectory(file_spec, file_permissions); - else - return Platform::MakeDirectory(file_spec, file_permissions); -} - -Status PlatformPOSIX::GetFilePermissions(const FileSpec &file_spec, - uint32_t &file_permissions) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetFilePermissions(file_spec, - file_permissions); - else - return Platform::GetFilePermissions(file_spec, file_permissions); -} - -Status PlatformPOSIX::SetFilePermissions(const FileSpec &file_spec, - uint32_t file_permissions) { - if (m_remote_platform_sp) - return m_remote_platform_sp->SetFilePermissions(file_spec, - file_permissions); - else - return Platform::SetFilePermissions(file_spec, file_permissions); -} - -lldb::user_id_t PlatformPOSIX::OpenFile(const FileSpec &file_spec, - uint32_t flags, uint32_t mode, - Status &error) { - if (IsHost()) - return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error); - else if (m_remote_platform_sp) - return m_remote_platform_sp->OpenFile(file_spec, flags, mode, error); - else - return Platform::OpenFile(file_spec, flags, mode, error); -} - -bool PlatformPOSIX::CloseFile(lldb::user_id_t fd, Status &error) { - if (IsHost()) - return FileCache::GetInstance().CloseFile(fd, error); - else if (m_remote_platform_sp) - return m_remote_platform_sp->CloseFile(fd, error); - else - return Platform::CloseFile(fd, error); -} - -uint64_t PlatformPOSIX::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, Status &error) { - if (IsHost()) - return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error); - else if (m_remote_platform_sp) - return m_remote_platform_sp->ReadFile(fd, offset, dst, dst_len, error); - else - return Platform::ReadFile(fd, offset, dst, dst_len, error); -} - -uint64_t PlatformPOSIX::WriteFile(lldb::user_id_t fd, uint64_t offset, - const void *src, uint64_t src_len, - Status &error) { - if (IsHost()) - return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error); - else if (m_remote_platform_sp) - return m_remote_platform_sp->WriteFile(fd, offset, src, src_len, error); - else - return Platform::WriteFile(fd, offset, src, src_len, error); -} - static uint32_t chown_file(Platform *platform, const char *path, uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX) { @@ -369,8 +223,8 @@ command.Printf(":%d", gid); command.Printf("%s", path); int status; - platform->RunShellCommand(command.GetData(), NULL, &status, NULL, NULL, - std::chrono::seconds(10)); + platform->RunShellCommand(command.GetData(), nullptr, &status, nullptr, + nullptr, std::chrono::seconds(10)); return status; } @@ -394,7 +248,7 @@ StreamString command; command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str()); int status; - RunShellCommand(command.GetData(), NULL, &status, NULL, NULL, + RunShellCommand(command.GetData(), nullptr, &status, nullptr, nullptr, std::chrono::seconds(10)); if (status != 0) return Status("unable to perform copy"); @@ -425,8 +279,8 @@ if (log) log->Printf("[PutFile] Running command: %s\n", command.GetData()); int retcode; - Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL, - std::chrono::minutes(1)); + Host::RunShellCommand(command.GetData(), nullptr, &retcode, nullptr, + nullptr, std::chrono::minutes(1)); if (retcode == 0) { // Don't chown a local file for a remote system // if (chown_file(this,dst_path.c_str(),uid,gid) != 0) @@ -440,45 +294,6 @@ return Platform::PutFile(source, destination, uid, gid); } -lldb::user_id_t PlatformPOSIX::GetFileSize(const FileSpec &file_spec) { - if (IsHost()) { - uint64_t Size; - if (llvm::sys::fs::file_size(file_spec.GetPath(), Size)) - return 0; - return Size; - } else if (m_remote_platform_sp) - return m_remote_platform_sp->GetFileSize(file_spec); - else - return Platform::GetFileSize(file_spec); -} - -Status PlatformPOSIX::CreateSymlink(const FileSpec &src, const FileSpec &dst) { - if (IsHost()) - return FileSystem::Instance().Symlink(src, dst); - else if (m_remote_platform_sp) - return m_remote_platform_sp->CreateSymlink(src, dst); - else - return Platform::CreateSymlink(src, dst); -} - -bool PlatformPOSIX::GetFileExists(const FileSpec &file_spec) { - if (IsHost()) - return FileSystem::Instance().Exists(file_spec); - else if (m_remote_platform_sp) - return m_remote_platform_sp->GetFileExists(file_spec); - else - return Platform::GetFileExists(file_spec); -} - -Status PlatformPOSIX::Unlink(const FileSpec &file_spec) { - if (IsHost()) - return llvm::sys::fs::remove(file_spec.GetPath()); - else if (m_remote_platform_sp) - return m_remote_platform_sp->Unlink(file_spec); - else - return Platform::Unlink(file_spec); -} - lldb_private::Status PlatformPOSIX::GetFile( const lldb_private::FileSpec &source, // remote file path const lldb_private::FileSpec &destination) // local file path @@ -500,7 +315,7 @@ StreamString cp_command; cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str()); int status; - RunShellCommand(cp_command.GetData(), NULL, &status, NULL, NULL, + RunShellCommand(cp_command.GetData(), nullptr, &status, nullptr, nullptr, std::chrono::seconds(10)); if (status != 0) return Status("unable to perform copy"); @@ -522,8 +337,8 @@ if (log) log->Printf("[GetFile] Running command: %s\n", command.GetData()); int retcode; - Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL, - std::chrono::minutes(1)); + Host::RunShellCommand(command.GetData(), nullptr, &retcode, nullptr, + nullptr, std::chrono::minutes(1)); if (retcode == 0) return Status(); // If we are here, rsync has failed - let's try the slow way before @@ -622,103 +437,12 @@ return ""; } -bool PlatformPOSIX::CalculateMD5(const FileSpec &file_spec, uint64_t &low, - uint64_t &high) { - if (IsHost()) - return Platform::CalculateMD5(file_spec, low, high); - if (m_remote_platform_sp) - return m_remote_platform_sp->CalculateMD5(file_spec, low, high); - return false; -} - const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() { if (IsRemote() && m_remote_platform_sp) return m_remote_platform_sp->GetRemoteUnixSignals(); return Platform::GetRemoteUnixSignals(); } -FileSpec PlatformPOSIX::GetRemoteWorkingDirectory() { - if (IsRemote() && m_remote_platform_sp) - return m_remote_platform_sp->GetRemoteWorkingDirectory(); - else - return Platform::GetRemoteWorkingDirectory(); -} - -bool PlatformPOSIX::SetRemoteWorkingDirectory(const FileSpec &working_dir) { - if (IsRemote() && m_remote_platform_sp) - return m_remote_platform_sp->SetRemoteWorkingDirectory(working_dir); - else - return Platform::SetRemoteWorkingDirectory(working_dir); -} - -bool PlatformPOSIX::GetRemoteOSVersion() { - if (m_remote_platform_sp) { - m_os_version = m_remote_platform_sp->GetOSVersion(); - return !m_os_version.empty(); - } - return false; -} - -bool PlatformPOSIX::GetRemoteOSBuildString(std::string &s) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetRemoteOSBuildString(s); - s.clear(); - return false; -} - -Environment PlatformPOSIX::GetEnvironment() { - if (IsRemote()) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetEnvironment(); - return Environment(); - } - return Host::GetEnvironment(); -} - -bool PlatformPOSIX::GetRemoteOSKernelDescription(std::string &s) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetRemoteOSKernelDescription(s); - s.clear(); - return false; -} - -// Remote Platform subclasses need to override this function -ArchSpec PlatformPOSIX::GetRemoteSystemArchitecture() { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetRemoteSystemArchitecture(); - return ArchSpec(); -} - -const char *PlatformPOSIX::GetHostname() { - if (IsHost()) - return Platform::GetHostname(); - - if (m_remote_platform_sp) - return m_remote_platform_sp->GetHostname(); - return NULL; -} - -const char *PlatformPOSIX::GetUserName(uint32_t uid) { - // Check the cache in Platform in case we have already looked this uid up - const char *user_name = Platform::GetUserName(uid); - if (user_name) - return user_name; - - if (IsRemote() && m_remote_platform_sp) - return m_remote_platform_sp->GetUserName(uid); - return NULL; -} - -const char *PlatformPOSIX::GetGroupName(uint32_t gid) { - const char *group_name = Platform::GetGroupName(gid); - if (group_name) - return group_name; - - if (IsRemote() && m_remote_platform_sp) - return m_remote_platform_sp->GetGroupName(gid); - return NULL; -} - Status PlatformPOSIX::ConnectRemote(Args &args) { Status error; if (IsHost()) { @@ -778,30 +502,6 @@ return error; } -Status PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) { - Status error; - - if (IsHost()) { - error = Platform::LaunchProcess(launch_info); - } else { - if (m_remote_platform_sp) - error = m_remote_platform_sp->LaunchProcess(launch_info); - else - error.SetErrorString("the platform is not currently connected"); - } - return error; -} - -lldb_private::Status PlatformPOSIX::KillProcess(const lldb::pid_t pid) { - if (IsHost()) - return Platform::KillProcess(pid); - - if (m_remote_platform_sp) - return m_remote_platform_sp->KillProcess(pid); - - return Status("the platform is not currently connected"); -} - lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, Status &error) { @@ -809,11 +509,11 @@ Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (IsHost()) { - if (target == NULL) { + if (target == nullptr) { TargetSP new_target_sp; error = debugger.GetTargetList().CreateTarget( - debugger, "", "", eLoadDependentsNo, NULL, new_target_sp); + debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp); target = new_target_sp.get(); if (log) log->Printf("PlatformPOSIX::%s created new target", __FUNCTION__); @@ -837,7 +537,7 @@ process_sp = target->CreateProcess(attach_info.GetListenerForProcess(debugger), - attach_info.GetProcessPluginName(), NULL); + attach_info.GetProcessPluginName(), nullptr); if (process_sp) { ListenerSP listener_sp = attach_info.GetHijackListener(); @@ -917,7 +617,7 @@ expr_options.SetLanguage(eLanguageTypeC_plus_plus); expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so // don't do the work to trap them. - expr_options.SetTimeout(std::chrono::seconds(2)); + expr_options.SetTimeout(process->GetUtilityExpressionTimeout()); Status expr_error; ExpressionResults result = @@ -1242,7 +942,7 @@ options.SetUnwindOnError(true); options.SetTrapExceptions(false); // dlopen can't throw exceptions, so // don't do the work to trap them. - options.SetTimeout(std::chrono::seconds(2)); + options.SetTimeout(process->GetUtilityExpressionTimeout()); options.SetIsForUtilityExpr(true); Value return_value; @@ -1335,19 +1035,6 @@ return Status(); } -lldb::ProcessSP PlatformPOSIX::ConnectProcess(llvm::StringRef connect_url, - llvm::StringRef plugin_name, - lldb_private::Debugger &debugger, - lldb_private::Target *target, - lldb_private::Status &error) { - if (m_remote_platform_sp) - return m_remote_platform_sp->ConnectProcess(connect_url, plugin_name, - debugger, target, error); - - return Platform::ConnectProcess(connect_url, plugin_name, debugger, target, - error); -} - llvm::StringRef PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) { return R"(
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h b/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h index 97333ef..5858f99 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h
@@ -1,9 +1,8 @@ //===-- PlatformPOSIX.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,123 +13,34 @@ #include <memory> #include "lldb/Interpreter/Options.h" -#include "lldb/Target/Platform.h" +#include "lldb/Target/RemoteAwarePlatform.h" -class PlatformPOSIX : public lldb_private::Platform { +class PlatformPOSIX : public lldb_private::RemoteAwarePlatform { public: PlatformPOSIX(bool is_host); ~PlatformPOSIX() override; - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ - - bool GetModuleSpec(const lldb_private::FileSpec &module_file_spec, - const lldb_private::ArchSpec &arch, - lldb_private::ModuleSpec &module_spec) override; lldb_private::OptionGroupOptions * GetConnectionOptions(lldb_private::CommandInterpreter &interpreter) override; - const char *GetHostname() override; - - const char *GetUserName(uint32_t uid) override; - - const char *GetGroupName(uint32_t gid) override; - lldb_private::Status PutFile(const lldb_private::FileSpec &source, const lldb_private::FileSpec &destination, uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX) override; - lldb::user_id_t OpenFile(const lldb_private::FileSpec &file_spec, - uint32_t flags, uint32_t mode, - lldb_private::Status &error) override; - - bool CloseFile(lldb::user_id_t fd, lldb_private::Status &error) override; - - uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, lldb_private::Status &error) override; - - uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, - uint64_t src_len, lldb_private::Status &error) override; - - lldb::user_id_t GetFileSize(const lldb_private::FileSpec &file_spec) override; - - lldb_private::Status - CreateSymlink(const lldb_private::FileSpec &src, - const lldb_private::FileSpec &dst) override; - lldb_private::Status GetFile(const lldb_private::FileSpec &source, const lldb_private::FileSpec &destination) override; - lldb_private::FileSpec GetRemoteWorkingDirectory() override; - - bool - SetRemoteWorkingDirectory(const lldb_private::FileSpec &working_dir) override; - - bool GetRemoteOSVersion() override; - - bool GetRemoteOSBuildString(std::string &s) override; - - bool GetRemoteOSKernelDescription(std::string &s) override; - - lldb_private::ArchSpec GetRemoteSystemArchitecture() override; - const lldb::UnixSignalsSP &GetRemoteUnixSignals() override; - lldb_private::Environment GetEnvironment() override; - - bool IsConnected() const override; - - lldb_private::Status RunShellCommand( - const char *command, // Shouldn't be nullptr - const lldb_private::FileSpec &working_dir, // Pass empty FileSpec to use - // the current working - // directory - int *status_ptr, // Pass nullptr if you don't want the process exit status - int *signo_ptr, // Pass nullptr if you don't want the signal that caused - // the process to exit - std::string - *command_output, // Pass nullptr if you don't want the command output - const lldb_private::Timeout<std::micro> &timeout) override; - lldb_private::Status ResolveExecutable( const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const lldb_private::FileSpecList *module_search_paths_ptr) override; - lldb_private::Status - GetFileWithUUID(const lldb_private::FileSpec &platform_file, - const lldb_private::UUID *uuid, - lldb_private::FileSpec &local_file) override; - - bool GetProcessInfo(lldb::pid_t pid, lldb_private::ProcessInstanceInfo &proc_info) override; - - uint32_t FindProcesses(const lldb_private::ProcessInstanceInfoMatch &match_info, - lldb_private::ProcessInstanceInfoList &process_infos) override; - - lldb_private::Status MakeDirectory(const lldb_private::FileSpec &file_spec, - uint32_t mode) override; - - lldb_private::Status - GetFilePermissions(const lldb_private::FileSpec &file_spec, - uint32_t &file_permissions) override; - - lldb_private::Status - SetFilePermissions(const lldb_private::FileSpec &file_spec, - uint32_t file_permissions) override; - - bool GetFileExists(const lldb_private::FileSpec &file_spec) override; - - lldb_private::Status Unlink(const lldb_private::FileSpec &file_spec) override; - - lldb_private::Status - LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) override; - - lldb_private::Status KillProcess(const lldb::pid_t pid) override; - lldb::ProcessSP Attach(lldb_private::ProcessAttachInfo &attach_info, lldb_private::Debugger &debugger, lldb_private::Target *target, // Can be nullptr, if @@ -150,9 +60,6 @@ std::string GetPlatformSpecificConnectionInformation() override; - bool CalculateMD5(const lldb_private::FileSpec &file_spec, uint64_t &low, - uint64_t &high) override; - void CalculateTrapHandlerSymbolNames() override; lldb_private::Status ConnectRemote(lldb_private::Args &args) override; @@ -168,12 +75,6 @@ lldb_private::Status UnloadImage(lldb_private::Process *process, uint32_t image_token) override; - lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, - llvm::StringRef plugin_name, - lldb_private::Debugger &debugger, - lldb_private::Target *target, - lldb_private::Status &error) override; - size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, lldb_private::Status &error) override; @@ -190,8 +91,6 @@ std::map<lldb_private::CommandInterpreter *, std::unique_ptr<lldb_private::OptionGroupOptions>> m_options; - lldb::PlatformSP m_remote_platform_sp; // Allow multiple ways to connect to a - // remote POSIX-compliant OS lldb_private::Status EvaluateLibdlExpression(lldb_private::Process *process, const char *expr_cstr,
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp b/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp index 685d49a..c18939f 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp
@@ -1,9 +1,8 @@ //===-- PlatformWindows.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -126,8 +125,6 @@ if (g_initialize_count++ == 0) { #if defined(_WIN32) - WSADATA dummy; - WSAStartup(MAKEWORD(2, 2), &dummy); // Force a host flag to true for the default platform object. PlatformSP default_platform_sp(new PlatformWindows(true)); default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture()); @@ -140,12 +137,9 @@ } } -void PlatformWindows::Terminate(void) { +void PlatformWindows::Terminate() { if (g_initialize_count > 0) { if (--g_initialize_count == 0) { -#ifdef _WIN32 - WSACleanup(); -#endif PluginManager::UnregisterPlugin(PlatformWindows::CreateInstance); } } @@ -153,29 +147,15 @@ Platform::Terminate(); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ -PlatformWindows::PlatformWindows(bool is_host) : Platform(is_host) {} +PlatformWindows::PlatformWindows(bool is_host) : RemoteAwarePlatform(is_host) {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformWindows::~PlatformWindows() = default; -bool PlatformWindows::GetModuleSpec(const FileSpec &module_file_spec, - const ArchSpec &arch, - ModuleSpec &module_spec) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetModuleSpec(module_file_spec, arch, - module_spec); - - return Platform::GetModuleSpec(module_file_spec, arch, module_spec); -} - Status PlatformWindows::ResolveExecutable( const ModuleSpec &ms, lldb::ModuleSP &exe_module_sp, const FileSpecList *module_search_paths_ptr) { @@ -208,8 +188,9 @@ } } else { if (m_remote_platform_sp) { - error = GetCachedExecutable(resolved_module_spec, exe_module_sp, nullptr, - *m_remote_platform_sp); + error = + GetCachedExecutable(resolved_module_spec, exe_module_sp, + module_search_paths_ptr, *m_remote_platform_sp); } else { // We may connect to a process and use the provided executable (Don't use // local $PATH). @@ -244,7 +225,8 @@ idx, resolved_module_spec.GetArchitecture()); ++idx) { error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp, - nullptr, nullptr, nullptr); + module_search_paths_ptr, nullptr, + nullptr); // Did we find an executable using one of the if (error.Success()) { if (exe_module_sp && exe_module_sp->GetObjectFile()) @@ -278,52 +260,6 @@ return error; } -bool PlatformWindows::GetRemoteOSVersion() { - if (m_remote_platform_sp) { - m_os_version = m_remote_platform_sp->GetOSVersion(); - return !m_os_version.empty(); - } - return false; -} - -bool PlatformWindows::GetRemoteOSBuildString(std::string &s) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetRemoteOSBuildString(s); - s.clear(); - return false; -} - -bool PlatformWindows::GetRemoteOSKernelDescription(std::string &s) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetRemoteOSKernelDescription(s); - s.clear(); - return false; -} - -// Remote Platform subclasses need to override this function -ArchSpec PlatformWindows::GetRemoteSystemArchitecture() { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetRemoteSystemArchitecture(); - return ArchSpec(); -} - -const char *PlatformWindows::GetHostname() { - if (IsHost()) - return Platform::GetHostname(); - - if (m_remote_platform_sp) - return m_remote_platform_sp->GetHostname(); - return nullptr; -} - -bool PlatformWindows::IsConnected() const { - if (IsHost()) - return true; - else if (m_remote_platform_sp) - return m_remote_platform_sp->IsConnected(); - return false; -} - Status PlatformWindows::ConnectRemote(Args &args) { Status error; if (IsHost()) { @@ -370,46 +306,6 @@ return error; } -bool PlatformWindows::GetProcessInfo(lldb::pid_t pid, - ProcessInstanceInfo &process_info) { - bool success = false; - if (IsHost()) { - success = Platform::GetProcessInfo(pid, process_info); - } else if (m_remote_platform_sp) { - success = m_remote_platform_sp->GetProcessInfo(pid, process_info); - } - return success; -} - -uint32_t -PlatformWindows::FindProcesses(const ProcessInstanceInfoMatch &match_info, - ProcessInstanceInfoList &process_infos) { - uint32_t match_count = 0; - if (IsHost()) { - // Let the base class figure out the host details - match_count = Platform::FindProcesses(match_info, process_infos); - } else { - // If we are remote, we can only return results if we are connected - if (m_remote_platform_sp) - match_count = - m_remote_platform_sp->FindProcesses(match_info, process_infos); - } - return match_count; -} - -Status PlatformWindows::LaunchProcess(ProcessLaunchInfo &launch_info) { - Status error; - if (IsHost()) { - error = Platform::LaunchProcess(launch_info); - } else { - if (m_remote_platform_sp) - error = m_remote_platform_sp->LaunchProcess(launch_info); - else - error.SetErrorString("the platform is not currently connected"); - } - return error; -} - ProcessSP PlatformWindows::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, Status &error) { @@ -432,6 +328,14 @@ // plugin, and PlatformWindows::DebugProcess is just a pass-through to get to // the process plugin. + if (IsRemote()) { + if (m_remote_platform_sp) + return m_remote_platform_sp->DebugProcess(launch_info, debugger, target, + error); + else + error.SetErrorString("the platform is not currently connected"); + } + if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) { // This is a process attach. Don't need to launch anything. ProcessAttachInfo attach_info(launch_info); @@ -489,69 +393,6 @@ return process_sp; } -const char *PlatformWindows::GetUserName(uint32_t uid) { - // Check the cache in Platform in case we have already looked this uid up - const char *user_name = Platform::GetUserName(uid); - if (user_name) - return user_name; - - if (IsRemote() && m_remote_platform_sp) - return m_remote_platform_sp->GetUserName(uid); - return nullptr; -} - -const char *PlatformWindows::GetGroupName(uint32_t gid) { - const char *group_name = Platform::GetGroupName(gid); - if (group_name) - return group_name; - - if (IsRemote() && m_remote_platform_sp) - return m_remote_platform_sp->GetGroupName(gid); - return nullptr; -} - -Status PlatformWindows::GetFileWithUUID(const FileSpec &platform_file, - const UUID *uuid_ptr, - FileSpec &local_file) { - if (IsRemote()) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr, - local_file); - } - - // Default to the local case - local_file = platform_file; - return Status(); -} - -Status PlatformWindows::GetSharedModule( - const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, ModuleSP *old_module_sp_ptr, - bool *did_create_ptr) { - Status error; - module_sp.reset(); - - if (IsRemote()) { - // If we have a remote platform always, let it try and locate the shared - // module first. - if (m_remote_platform_sp) { - error = m_remote_platform_sp->GetSharedModule( - module_spec, process, module_sp, module_search_paths_ptr, - old_module_sp_ptr, did_create_ptr); - } - } - - if (!module_sp) { - // Fall back to the local platform and find the file locally - error = Platform::GetSharedModule(module_spec, process, module_sp, - module_search_paths_ptr, - old_module_sp_ptr, did_create_ptr); - } - if (module_sp) - module_sp->SetPlatformFileSpec(module_spec.GetFileSpec()); - return error; -} - bool PlatformWindows::GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) { static SupportedArchList architectures; @@ -567,22 +408,12 @@ #ifdef _WIN32 llvm::VersionTuple version = HostInfo::GetOSVersion(); - strm << "Host: Windows " << version.getAsString() << '\n'; + strm << " Host: Windows " << version.getAsString() << '\n'; #endif } bool PlatformWindows::CanDebugProcess() { return true; } -Environment PlatformWindows::GetEnvironment() { - if (IsRemote()) { - if (m_remote_platform_sp) - return m_remote_platform_sp->GetEnvironment(); - return Environment(); - } - - return Host::GetEnvironment(); -} - ConstString PlatformWindows::GetFullNameForDylib(ConstString basename) { if (basename.IsEmpty()) return basename;
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.h b/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.h index f7f5504..5740001 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/Windows/PlatformWindows.h
@@ -1,20 +1,19 @@ //===-- PlatformWindows.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 liblldb_PlatformWindows_h_ #define liblldb_PlatformWindows_h_ -#include "lldb/Target/Platform.h" +#include "lldb/Target/RemoteAwarePlatform.h" namespace lldb_private { -class PlatformWindows : public Platform { +class PlatformWindows : public RemoteAwarePlatform { public: PlatformWindows(bool is_host); @@ -24,9 +23,7 @@ static void Terminate(); - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch); @@ -38,13 +35,7 @@ uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ - bool GetModuleSpec(const lldb_private::FileSpec &module_file_spec, - const lldb_private::ArchSpec &arch, - lldb_private::ModuleSpec &module_spec) override; - Status ResolveExecutable(const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, @@ -54,37 +45,10 @@ return GetPluginDescriptionStatic(IsHost()); } - bool GetRemoteOSVersion() override; - - bool GetRemoteOSBuildString(std::string &s) override; - - bool GetRemoteOSKernelDescription(std::string &s) override; - - // Remote Platform subclasses need to override this function - lldb_private::ArchSpec GetRemoteSystemArchitecture() override; - - bool IsConnected() const override; - lldb_private::Status ConnectRemote(lldb_private::Args &args) override; lldb_private::Status DisconnectRemote() override; - const char *GetHostname() override; - - const char *GetUserName(uint32_t uid) override; - - const char *GetGroupName(uint32_t gid) override; - - bool GetProcessInfo(lldb::pid_t pid, - lldb_private::ProcessInstanceInfo &proc_info) override; - - uint32_t - FindProcesses(const lldb_private::ProcessInstanceInfoMatch &match_info, - lldb_private::ProcessInstanceInfoList &process_infos) override; - - lldb_private::Status - LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) override; - lldb::ProcessSP DebugProcess(lldb_private::ProcessLaunchInfo &launch_info, lldb_private::Debugger &debugger, lldb_private::Target *target, @@ -95,18 +59,6 @@ lldb_private::Target *target, lldb_private::Status &error) override; - lldb_private::Status - GetFileWithUUID(const lldb_private::FileSpec &platform_file, - const lldb_private::UUID *uuid, - lldb_private::FileSpec &local_file) override; - - lldb_private::Status - GetSharedModule(const lldb_private::ModuleSpec &module_spec, - lldb_private::Process *process, lldb::ModuleSP &module_sp, - const lldb_private::FileSpecList *module_search_paths_ptr, - lldb::ModuleSP *old_module_sp_ptr, - bool *did_create_ptr) override; - bool GetSupportedArchitectureAtIndex(uint32_t idx, lldb_private::ArchSpec &arch) override; @@ -114,16 +66,11 @@ bool CanDebugProcess() override; - Environment GetEnvironment() override; - // FIXME not sure what the _sigtramp equivalent would be on this platform void CalculateTrapHandlerSymbolNames() override {} ConstString GetFullNameForDylib(ConstString basename) override; -protected: - lldb::PlatformSP m_remote_platform_sp; - private: DISALLOW_COPY_AND_ASSIGN(PlatformWindows); };
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp b/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp index f6ace70..9c52b59 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp +++ b/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp
@@ -1,9 +1,8 @@ //===-- PlatformRemoteGDBServer.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,6 +24,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/UriParser.h" @@ -109,7 +109,8 @@ if (resolved_module_spec.GetArchitecture().IsValid() || resolved_module_spec.GetUUID().IsValid()) { error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp, - module_search_paths_ptr, NULL, NULL); + module_search_paths_ptr, nullptr, + nullptr); if (exe_module_sp && exe_module_sp->GetObjectFile()) return error; @@ -123,7 +124,8 @@ idx, resolved_module_spec.GetArchitecture()); ++idx) { error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp, - module_search_paths_ptr, NULL, NULL); + module_search_paths_ptr, nullptr, + nullptr); // Did we find an executable using one of the if (error.Success()) { if (exe_module_sp && exe_module_sp->GetObjectFile()) @@ -195,19 +197,15 @@ return Status(); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ PlatformRemoteGDBServer::PlatformRemoteGDBServer() : Platform(false), // This is a remote platform m_gdb_client() {} -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ PlatformRemoteGDBServer::~PlatformRemoteGDBServer() {} bool PlatformRemoteGDBServer::GetSupportedArchitectureAtIndex(uint32_t idx, @@ -337,33 +335,24 @@ const char *PlatformRemoteGDBServer::GetHostname() { m_gdb_client.GetHostname(m_name); if (m_name.empty()) - return NULL; + return nullptr; return m_name.c_str(); } -const char *PlatformRemoteGDBServer::GetUserName(uint32_t uid) { - // Try and get a cache user name first - const char *cached_user_name = Platform::GetUserName(uid); - if (cached_user_name) - return cached_user_name; +llvm::Optional<std::string> +PlatformRemoteGDBServer::DoGetUserName(UserIDResolver::id_t uid) { std::string name; if (m_gdb_client.GetUserName(uid, name)) - return SetCachedUserName(uid, name.c_str(), name.size()); - - SetUserNameNotFound(uid); // Negative cache so we don't keep sending packets - return NULL; + return std::move(name); + return llvm::None; } -const char *PlatformRemoteGDBServer::GetGroupName(uint32_t gid) { - const char *cached_group_name = Platform::GetGroupName(gid); - if (cached_group_name) - return cached_group_name; +llvm::Optional<std::string> +PlatformRemoteGDBServer::DoGetGroupName(UserIDResolver::id_t gid) { std::string name; if (m_gdb_client.GetGroupName(gid, name)) - return SetCachedGroupName(gid, name.c_str(), name.size()); - - SetGroupNameNotFound(gid); // Negative cache so we don't keep sending packets - return NULL; + return std::move(name); + return llvm::None; } uint32_t PlatformRemoteGDBServer::FindProcesses( @@ -482,11 +471,11 @@ error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'", GetHostname()); } else { - if (target == NULL) { + if (target == nullptr) { TargetSP new_target_sp; error = debugger.GetTargetList().CreateTarget( - debugger, "", "", eLoadDependentsNo, NULL, new_target_sp); + debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp); target = new_target_sp.get(); } else error.Clear(); @@ -497,7 +486,7 @@ // The darwin always currently uses the GDB remote debugger plug-in // so even when debugging locally we are debugging remotely! process_sp = target->CreateProcess(launch_info.GetListener(), - "gdb-remote", NULL); + "gdb-remote", nullptr); if (process_sp) { error = process_sp->ConnectRemote(nullptr, connect_url.c_str()); @@ -568,11 +557,11 @@ error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'", GetHostname()); } else { - if (target == NULL) { + if (target == nullptr) { TargetSP new_target_sp; error = debugger.GetTargetList().CreateTarget( - debugger, "", "", eLoadDependentsNo, NULL, new_target_sp); + debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp); target = new_target_sp.get(); } else error.Clear(); @@ -582,8 +571,9 @@ // The darwin always currently uses the GDB remote debugger plug-in // so even when debugging locally we are debugging remotely! - process_sp = target->CreateProcess( - attach_info.GetListenerForProcess(debugger), "gdb-remote", NULL); + process_sp = + target->CreateProcess(attach_info.GetListenerForProcess(debugger), + "gdb-remote", nullptr); if (process_sp) { error = process_sp->ConnectRemote(nullptr, connect_url.c_str()); if (error.Success()) {
diff --git a/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h b/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h index 7abb334..c774daa 100644 --- a/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h +++ b/src/llvm-project/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h
@@ -1,10 +1,9 @@ //===-- PlatformRemoteGDBServer.h ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,7 +19,7 @@ namespace lldb_private { namespace platform_gdb_server { -class PlatformRemoteGDBServer : public Platform { +class PlatformRemoteGDBServer : public Platform, private UserIDResolver { public: static void Initialize(); @@ -34,18 +33,14 @@ PlatformRemoteGDBServer(); - virtual ~PlatformRemoteGDBServer(); + ~PlatformRemoteGDBServer() override; - //------------------------------------------------------------ // lldb_private::PluginInterface functions - //------------------------------------------------------------ ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } - //------------------------------------------------------------ // lldb_private::Platform functions - //------------------------------------------------------------ Status ResolveExecutable(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr) override; @@ -101,9 +96,7 @@ // name if connected. const char *GetHostname() override; - const char *GetUserName(uint32_t uid) override; - - const char *GetGroupName(uint32_t gid) override; + UserIDResolver &GetUserIDResolver() override { return *this; } bool IsConnected() const override; @@ -196,6 +189,9 @@ const std::string &platform_hostname, uint16_t port, const char *socket_name); + llvm::Optional<std::string> DoGetUserName(UserIDResolver::id_t uid) override; + llvm::Optional<std::string> DoGetGroupName(UserIDResolver::id_t uid) override; + DISALLOW_COPY_AND_ASSIGN(PlatformRemoteGDBServer); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.cpp b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.cpp index 7b080e6..3cdd2fa 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.cpp
@@ -1,9 +1,8 @@ //===-- CFBundle.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // @@ -14,37 +13,27 @@ #include "CFBundle.h" #include "CFString.h" -//---------------------------------------------------------------------- // CFBundle constructor -//---------------------------------------------------------------------- CFBundle::CFBundle(const char *path) : CFReleaser<CFBundleRef>(), m_bundle_url() { if (path && path[0]) SetPath(path); } -//---------------------------------------------------------------------- // CFBundle copy constructor -//---------------------------------------------------------------------- CFBundle::CFBundle(const CFBundle &rhs) : CFReleaser<CFBundleRef>(rhs), m_bundle_url(rhs.m_bundle_url) {} -//---------------------------------------------------------------------- // CFBundle copy constructor -//---------------------------------------------------------------------- CFBundle &CFBundle::operator=(const CFBundle &rhs) { *this = rhs; return *this; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFBundle::~CFBundle() {} -//---------------------------------------------------------------------- // Set the path for a bundle by supplying a -//---------------------------------------------------------------------- bool CFBundle::SetPath(const char *path) { CFAllocatorRef alloc = kCFAllocatorDefault; // Release our old bundle and ULR
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.h index 09957af..f49dc30 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFBundle.h
@@ -1,9 +1,8 @@ //===-- CFBundle.h ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // @@ -18,9 +17,7 @@ class CFBundle : public CFReleaser<CFBundleRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFBundle(const char *path = NULL); CFBundle(const CFBundle &rhs); CFBundle &operator=(const CFBundle &rhs);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.cpp b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.cpp index b87afe9..4dcc05c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.cpp
@@ -1,9 +1,8 @@ //===-- CFString.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // @@ -15,19 +14,13 @@ #include <glob.h> #include <string> -//---------------------------------------------------------------------- // CFString constructor -//---------------------------------------------------------------------- CFString::CFString(CFStringRef s) : CFReleaser<CFStringRef>(s) {} -//---------------------------------------------------------------------- // CFString copy constructor -//---------------------------------------------------------------------- CFString::CFString(const CFString &rhs) : CFReleaser<CFStringRef>(rhs) {} -//---------------------------------------------------------------------- // CFString copy constructor -//---------------------------------------------------------------------- CFString &CFString::operator=(const CFString &rhs) { if (this != &rhs) *this = rhs; @@ -42,9 +35,7 @@ } } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CFString::~CFString() {} const char *CFString::GetFileSystemRepresentation(std::string &s) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.h index 18d60a5..d1bd568 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFString.h
@@ -1,9 +1,8 @@ //===-- CFString.h ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // @@ -19,9 +18,7 @@ class CFString : public CFReleaser<CFStringRef> { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ CFString(CFStringRef cf_str = NULL); CFString(const char *s, CFStringEncoding encoding = kCFStringEncodingUTF8); CFString(const CFString &rhs);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFUtils.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFUtils.h index a904cd0..b567524 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFUtils.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/CFUtils.h
@@ -1,9 +1,8 @@ //===-- CFUtils.h -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // @@ -18,11 +17,9 @@ #ifdef __cplusplus -//---------------------------------------------------------------------- // Templatized CF helper class that can own any CF pointer and will // call CFRelease() on any valid pointer it owns unless that pointer is // explicitly released using the release() member function. -//---------------------------------------------------------------------- template <class T> class CFReleaser { public: // Type names for the avlue
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp b/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp index 9565972..3ec410f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp
@@ -1,9 +1,8 @@ //===-- DarwinProcessLauncher.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -149,17 +148,13 @@ memset(fork_error, 0, sizeof(fork_error)); *pid = static_cast<::pid_t>(pty.Fork(fork_error, sizeof(fork_error))); if (*pid < 0) { - //-------------------------------------------------------------- // Status during fork. - //-------------------------------------------------------------- *pid = static_cast<::pid_t>(LLDB_INVALID_PROCESS_ID); error.SetErrorStringWithFormat("%s(): fork failed: %s", __FUNCTION__, fork_error); return error; } else if (pid == 0) { - //-------------------------------------------------------------- // Child process - //-------------------------------------------------------------- // Debug this process. ::ptrace(PT_TRACE_ME, 0, 0, 0); @@ -187,9 +182,7 @@ // call and if the exec fails it will exit the child process below. ::exit(127); } else { - //-------------------------------------------------------------- // Parent process - //-------------------------------------------------------------- // Let the child have its own process group. We need to execute this call // in both the child and parent to avoid a race condition between the two // processes.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h index a0e8ce5..0e65b56 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h
@@ -1,9 +1,8 @@ //===-- DarwinProcessLauncher.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,15 +27,15 @@ // ============================================================================= /// Launches a process for debugging. /// -/// @param[inout] launch_info +/// \param[inout] launch_info /// Specifies details about the process to launch (e.g. path, architecture, /// etc.). On output, includes the launched ProcessID (pid). /// -/// @param[out] pty_master_fd +/// \param[out] pty_master_fd /// Returns the master side of the pseudo-terminal used to communicate /// with stdin/stdout from the launched process. May be nullptr. /// -/// @param[out] launch_flavor +/// \param[out] launch_flavor /// Contains the launch flavor used when launching the process. // ============================================================================= Status
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/LaunchFlavor.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/LaunchFlavor.h index 7b16171..cfd76d1 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/LaunchFlavor.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/LaunchFlavor.h
@@ -1,9 +1,8 @@ //===-- LaunchFlavor.h ---------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.cpp b/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.cpp index 353f2df..70ad673 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.cpp
@@ -1,9 +1,8 @@ //===-- MachException.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// //
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.h index 2da6a36..18e4917 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/MachException.h
@@ -1,9 +1,8 @@ //===-- MachException.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// //
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp index 70d9a52..fe7de27 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp
@@ -1,9 +1,8 @@ //===-- NativeProcessDarwin.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -38,9 +37,7 @@ using namespace lldb_private::process_darwin; using namespace lldb_private::darwin_process_launcher; -// ----------------------------------------------------------------------------- // Hidden Impl -// ----------------------------------------------------------------------------- namespace { struct hack_task_dyld_info { @@ -49,9 +46,7 @@ }; } -// ----------------------------------------------------------------------------- // Public Static Methods -// ----------------------------------------------------------------------------- Status NativeProcessProtocol::Launch( ProcessLaunchInfo &launch_info, @@ -154,9 +149,7 @@ return error; } -// ----------------------------------------------------------------------------- // ctor/dtor -// ----------------------------------------------------------------------------- NativeProcessDarwin::NativeProcessDarwin(lldb::pid_t pid, int pty_master_fd) : NativeProcessProtocol(pid), m_task(TASK_NULL), m_did_exec(false), @@ -171,23 +164,13 @@ NativeProcessDarwin::~NativeProcessDarwin() {} -// ----------------------------------------------------------------------------- // Instance methods -// ----------------------------------------------------------------------------- Status NativeProcessDarwin::FinalizeLaunch(LaunchFlavor launch_flavor, MainLoop &main_loop) { Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); -#if 0 - m_path = path; - size_t i; - char const *arg; - for (i=0; (arg = argv[i]) != NULL; i++) - m_args.push_back(arg); -#endif - error = StartExceptionThread(); if (!error.Success()) { if (log) @@ -1548,9 +1531,7 @@ return error; } -// ----------------------------------------------------------------- // NativeProcessProtocol protected interface -// ----------------------------------------------------------------- Status NativeProcessDarwin::GetSoftwareBreakpointTrapOpcode( size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h index 9abdd53..6741d4d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h
@@ -1,9 +1,8 @@ //===-- NativeProcessDarwin.h --------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -41,7 +40,7 @@ namespace process_darwin { -/// @class NativeProcessDarwin +/// \class NativeProcessDarwin /// Manages communication with the inferior (debugee) process. /// /// Upon construction, this class prepares and launches an inferior process @@ -60,9 +59,7 @@ public: ~NativeProcessDarwin() override; - // ----------------------------------------------------------------- // NativeProcessProtocol Interface - // ----------------------------------------------------------------- Status Resume(const ResumeActionList &resume_actions) override; Status Halt() override; @@ -113,9 +110,7 @@ task_t GetTask() const { return m_task; } - // ----------------------------------------------------------------- // Interface used by NativeRegisterContext-derived classes. - // ----------------------------------------------------------------- static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr, void *data = nullptr, size_t data_size = 0, long *result = nullptr); @@ -123,18 +118,14 @@ bool SupportHardwareSingleStepping() const; protected: - // ----------------------------------------------------------------- // NativeProcessProtocol protected interface - // ----------------------------------------------------------------- Status GetSoftwareBreakpointTrapOpcode(size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) override; private: - // ----------------------------------------------------------------- /// Mach task-related Member Variables - // ----------------------------------------------------------------- // The task port for the inferior process. mutable task_t m_task; @@ -146,9 +137,7 @@ // The CPU type of this process. mutable cpu_type_t m_cpu_type; - // ----------------------------------------------------------------- /// Exception/Signal Handling Member Variables - // ----------------------------------------------------------------- // Exception port on which we will receive child exceptions mach_port_t m_exception_port; @@ -176,15 +165,11 @@ // interrupt signal (if this is non-zero). int m_auto_resume_signo; - // ----------------------------------------------------------------- /// Thread-related Member Variables - // ----------------------------------------------------------------- NativeThreadListDarwin m_thread_list; ResumeActionList m_thread_actions; - // ----------------------------------------------------------------- /// Process Lifetime Member Variable - // ----------------------------------------------------------------- // The pipe over which the waitpid thread and the main loop will // communicate. @@ -196,12 +181,9 @@ // waitpid reader callback handle. MainLoop::ReadHandleUP m_waitpid_reader_handle; - // ----------------------------------------------------------------- // Private Instance Methods - // ----------------------------------------------------------------- NativeProcessDarwin(lldb::pid_t pid, int pty_master_fd); - // ----------------------------------------------------------------- /// Finalize the launch. /// /// This method associates the NativeProcessDarwin instance with the host @@ -209,19 +191,18 @@ /// listener to the inferior exception port, ptracing the process, and the /// like. /// - /// @param[in] launch_flavor + /// \param[in] launch_flavor /// The launch flavor that was used to launch the process. /// - /// @param[in] main_loop + /// \param[in] main_loop /// The main loop that will run the process monitor. Work /// that needs to be done (e.g. reading files) gets registered /// here along with callbacks to process the work. /// - /// @return + /// \return /// Any error that occurred during the aforementioned /// operations. Failure here will force termination of the /// launched process and debugging session. - // ----------------------------------------------------------------- Status FinalizeLaunch(LaunchFlavor launch_flavor, MainLoop &main_loop); Status SaveExceptionPortInfo(); @@ -318,7 +299,7 @@ Status FixupBreakpointPCAsNeeded(NativeThreadDarwin &thread); /// Writes a siginfo_t structure corresponding to the given thread - /// ID to the memory region pointed to by @p siginfo. + /// ID to the memory region pointed to by \p siginfo. Status GetSignalInfo(lldb::tid_t tid, void *siginfo); /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp index 521c6d5..bcd6d8c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp
@@ -1,9 +1,8 @@ //===-- NativeThreadDarwin.cpp -------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -139,7 +138,7 @@ // Allow the arch specific protocol to process (MachException::Data &)exc // first before possible reassignment of m_stop_exception with exc. See // also MachThread::GetStopException(). - bool handled = m_arch_ap->NotifyException(exc); + bool handled = m_arch_up->NotifyException(exc); if (m_stop_exception.IsValid()) { @@ -176,7 +175,7 @@ } else { - if (m_arch_ap->StepNotComplete()) + if (m_arch_up->StepNotComplete()) { step_more = true; return false; @@ -218,7 +217,7 @@ // When this method gets called, the process state is still in the state it // was in while running so we can act accordingly. - m_arch_ap->ThreadDidStop(); + m_arch_up->ThreadDidStop(); // We may have suspended this thread so the primary thread could step
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h index f66f8fe..616a9a7b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h
@@ -1,9 +1,8 @@ //===-- NativeThreadDarwin.h ---------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -46,9 +45,7 @@ lldb::tid_t unique_thread_id = 0, ::thread_t mach_thread_port = 0); - // ----------------------------------------------------------------- // NativeThreadProtocol Interface - // ----------------------------------------------------------------- std::string GetName() override; lldb::StateType GetState() override; @@ -63,21 +60,17 @@ Status RemoveWatchpoint(lldb::addr_t addr) override; - // ----------------------------------------------------------------- // New methods that are fine for others to call. - // ----------------------------------------------------------------- void Dump(Stream &stream) const; private: - // ----------------------------------------------------------------- // Interface for friend classes - // ----------------------------------------------------------------- - /// Resumes the thread. If @p signo is anything but + /// Resumes the thread. If \p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread. Status Resume(uint32_t signo); - /// Single steps the thread. If @p signo is anything but + /// Single steps the thread. If \p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread. Status SingleStep(uint32_t signo); @@ -119,20 +112,16 @@ Status RequestStop(); - // ------------------------------------------------------------------------- /// Return the mach thread port number for this thread. /// - /// @return + /// \return /// The mach port number for this thread. Returns NULL_THREAD /// when the thread is invalid. - // ------------------------------------------------------------------------- thread_t GetMachPortNumber() const { return m_mach_thread_port; } static bool MachPortNumberIsValid(::thread_t thread); - // --------------------------------------------------------------------- // Private interface - // --------------------------------------------------------------------- bool GetIdentifierInfo(); void MaybeLogStateChange(lldb::StateType new_state); @@ -145,9 +134,7 @@ inline void MaybeCleanupSingleStepWorkaround(); - // ----------------------------------------------------------------- // Member Variables - // ----------------------------------------------------------------- // The mach thread port for the thread. ::thread_t m_mach_thread_port;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp index 4ff662e..89de92a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp
@@ -1,10 +1,9 @@ //===-- NativeThreadListDarwin.cpp ------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // @@ -549,7 +548,6 @@ return (uint32_t)m_threads.size(); } -//---------------------------------------------------------------------- // Check each thread in our thread list to see if we should notify our client // of the current halt in execution. // @@ -559,7 +557,6 @@ // RETURNS // true if we should stop and notify our clients // false if we should resume our child process and skip notification -//---------------------------------------------------------------------- bool NativeThreadListDarwin::ShouldStop(bool &step_more) { std::lock_guard<std::recursive_mutex> locker(m_threads_mutex); for (auto thread_sp : m_threads) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h index 7b59afb..9ab0a7c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h
@@ -1,10 +1,9 @@ //===-- NativeThreadListDarwin.h --------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// //
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.cpp index fce0be2..7498355 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.cpp
@@ -1,9 +1,8 @@ //===-- FreeBSDThread.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -52,7 +51,7 @@ using namespace lldb_private; FreeBSDThread::FreeBSDThread(Process &process, lldb::tid_t tid) - : Thread(process, tid), m_frame_ap(), m_breakpoint(), + : Thread(process, tid), m_frame_up(), m_breakpoint(), m_thread_name_valid(false), m_thread_name(), m_posix_thread(nullptr) { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); LLDB_LOGV(log, "tid = {0}", tid); @@ -277,10 +276,10 @@ } Unwind *FreeBSDThread::GetUnwinder() { - if (!m_unwinder_ap) - m_unwinder_ap.reset(new UnwindLLDB(*this)); + if (!m_unwinder_up) + m_unwinder_up.reset(new UnwindLLDB(*this)); - return m_unwinder_ap.get(); + return m_unwinder_up.get(); } void FreeBSDThread::DidStop() {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.h index a8559fe..6d3c253 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/FreeBSDThread.h
@@ -1,9 +1,8 @@ //===-- FreeBSDThread.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,14 +19,11 @@ class ProcessMonitor; class POSIXBreakpointProtocol; -//------------------------------------------------------------------------------ // @class FreeBSDThread // Abstraction of a FreeBSD thread. class FreeBSDThread : public lldb_private::Thread { public: - //------------------------------------------------------------------ // Constructors and destructors - //------------------------------------------------------------------ FreeBSDThread(lldb_private::Process &process, lldb::tid_t tid); virtual ~FreeBSDThread(); @@ -51,7 +47,6 @@ lldb::addr_t GetThreadPointer() override; - //-------------------------------------------------------------------------- // These functions provide a mapping from the register offset // back to the register index or name for use in debugging or log // output. @@ -62,14 +57,12 @@ const char *GetRegisterNameFromOffset(unsigned offset); - //-------------------------------------------------------------------------- // These methods form a specialized interface to POSIX threads. // bool Resume(); void Notify(const ProcessMessage &message); - //-------------------------------------------------------------------------- // These methods provide an interface to watchpoints // bool EnableHardwareWatchpoint(lldb_private::Watchpoint *wp); @@ -87,7 +80,7 @@ return m_posix_thread; } - std::unique_ptr<lldb_private::StackFrame> m_frame_ap; + std::unique_ptr<lldb_private::StackFrame> m_frame_up; lldb::BreakpointSiteSP m_breakpoint; @@ -111,7 +104,6 @@ lldb_private::Unwind *GetUnwinder() override; - //-------------------------------------------------------------------------- // FreeBSDThread internal API. // POSIXThread override
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.cpp index 9c75c26..71f0129 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.cpp
@@ -1,9 +1,8 @@ //===-- POSIXStopInfo.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.h index ff36931..88fb7f3 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/POSIXStopInfo.h
@@ -1,9 +1,8 @@ //===-- POSIXStopInfo.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,7 +15,7 @@ #include <string> //===----------------------------------------------------------------------===// -/// @class POSIXStopInfo +/// \class POSIXStopInfo /// Simple base class for all POSIX-specific StopInfo objects. /// class POSIXStopInfo : public lldb_private::StopInfo { @@ -26,7 +25,7 @@ }; //===----------------------------------------------------------------------===// -/// @class POSIXLimboStopInfo +/// \class POSIXLimboStopInfo /// Represents the stop state of a process ready to exit. /// class POSIXLimboStopInfo : public POSIXStopInfo { @@ -45,7 +44,7 @@ }; //===----------------------------------------------------------------------===// -/// @class POSIXNewThreadStopInfo +/// \class POSIXNewThreadStopInfo /// Represents the stop state of process when a new thread is spawned. ///
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp index a13d4bc..7707945 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp
@@ -1,10 +1,9 @@ //===-- ProcessFreeBSD.cpp ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -65,7 +64,6 @@ } } -//------------------------------------------------------------------------------ // Static functions. lldb::ProcessSP @@ -97,7 +95,6 @@ return "Process plugin for FreeBSD"; } -//------------------------------------------------------------------------------ // ProcessInterface protocol. lldb_private::ConstString ProcessFreeBSD::GetPluginName() { @@ -251,7 +248,6 @@ m_message_queue.push(message); } -//------------------------------------------------------------------------------ // Constructors and destructors. ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp, @@ -270,7 +266,6 @@ ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; } -//------------------------------------------------------------------------------ // Process protocol. void ProcessFreeBSD::Finalize() { Process::Finalize(); @@ -836,7 +831,6 @@ return status; } -//------------------------------------------------------------------------------ // Utility functions. bool ProcessFreeBSD::HasExited() { @@ -882,7 +876,7 @@ return is_running; } -const DataBufferSP ProcessFreeBSD::GetAuxvData() { +lldb_private::DataExtractor ProcessFreeBSD::GetAuxvData() { // If we're the local platform, we can ask the host for auxv data. PlatformSP platform_sp = GetTarget().GetPlatform(); assert(platform_sp && platform_sp->IsHost()); @@ -896,7 +890,7 @@ buf_sp.reset(); } - return buf_sp; + return DataExtractor(buf_sp, GetByteOrder(), GetAddressByteSize()); } struct EmulatorBaton { @@ -1026,21 +1020,17 @@ bool ProcessFreeBSD::SupportHardwareSingleStepping() const { lldb_private::ArchSpec arch = GetTarget().GetArchitecture(); - if (arch.GetMachine() == llvm::Triple::arm || - arch.GetMachine() == llvm::Triple::mips64 || - arch.GetMachine() == llvm::Triple::mips64el || - arch.GetMachine() == llvm::Triple::mips || - arch.GetMachine() == llvm::Triple::mipsel) + if (arch.GetMachine() == llvm::Triple::arm || arch.IsMIPS()) return false; return true; } Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) { - std::unique_ptr<EmulateInstruction> emulator_ap( + std::unique_ptr<EmulateInstruction> emulator_up( EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(), eInstructionTypePCModifying, nullptr)); - if (emulator_ap == nullptr) + if (emulator_up == nullptr) return Status("Instruction emulator not found!"); FreeBSDThread *thread = static_cast<FreeBSDThread *>( @@ -1051,17 +1041,17 @@ lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext(); EmulatorBaton baton(this, register_context_sp.get()); - emulator_ap->SetBaton(&baton); - emulator_ap->SetReadMemCallback(&ReadMemoryCallback); - emulator_ap->SetReadRegCallback(&ReadRegisterCallback); - emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); - emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); + emulator_up->SetBaton(&baton); + emulator_up->SetReadMemCallback(&ReadMemoryCallback); + emulator_up->SetReadRegCallback(&ReadRegisterCallback); + emulator_up->SetWriteMemCallback(&WriteMemoryCallback); + emulator_up->SetWriteRegCallback(&WriteRegisterCallback); - if (!emulator_ap->ReadInstruction()) + if (!emulator_up->ReadInstruction()) return Status("Read instruction failed!"); bool emulation_result = - emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); + emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo( eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); auto pc_it = @@ -1078,7 +1068,7 @@ // PC modifying instruction should be successful. The failure most // likely caused by a not supported instruction which don't modify PC. next_pc = - register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize(); + register_context_sp->GetPC() + emulator_up->GetOpcode().GetByteSize(); } else { // The instruction emulation failed after it modified the PC. It is an // unknown error where we can't continue because the next instruction is
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h index 7ed2a56..536da0c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h
@@ -1,10 +1,9 @@ //===-- ProcessFreeBSD.h ------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ class ProcessFreeBSD : public lldb_private::Process { public: - //------------------------------------------------------------------ // Static functions. - //------------------------------------------------------------------ static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const lldb_private::FileSpec *crash_file_path); @@ -39,9 +36,7 @@ static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // Constructors and destructors - //------------------------------------------------------------------ ProcessFreeBSD(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, lldb::UnixSignalsSP &unix_signals_sp); @@ -49,17 +44,13 @@ virtual lldb_private::Status WillResume() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ virtual lldb_private::ConstString GetPluginName() override; virtual uint32_t GetPluginVersion() override; public: - //------------------------------------------------------------------ // Process protocol. - //------------------------------------------------------------------ void Finalize() override; bool CanDebug(lldb::TargetSP target_sp, @@ -136,9 +127,8 @@ size_t PutSTDIN(const char *buf, size_t len, lldb_private::Status &error) override; - const lldb::DataBufferSP GetAuxvData() override; + lldb_private::DataExtractor GetAuxvData() override; - //-------------------------------------------------------------------------- // ProcessFreeBSD internal API. /// Registers the given message with this process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp index 617ae30..4b9225d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp
@@ -1,9 +1,8 @@ //===-- ProcessMonitor.cpp ------------------------------------ -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -141,7 +140,6 @@ PtraceWrapper((req), (pid), (addr), (data)) #endif -//------------------------------------------------------------------------------ // Static implementations of ProcessMonitor::ReadMemory and // ProcessMonitor::WriteMemory. This enables mutual recursion between these // functions without needed to go thru the thread funnel. @@ -168,7 +166,7 @@ pi_desc.piod_op = PIOD_WRITE_D; pi_desc.piod_offs = (void *)vm_addr; - pi_desc.piod_addr = (void *)buf; + pi_desc.piod_addr = const_cast<void *>(buf); pi_desc.piod_len = size; if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0) { @@ -196,8 +194,7 @@ return true; } -//------------------------------------------------------------------------------ -/// @class Operation +/// \class Operation /// Represents a ProcessMonitor operation. /// /// Under FreeBSD, it is not possible to ptrace() from any other thread but @@ -214,8 +211,7 @@ virtual void Execute(ProcessMonitor *monitor) = 0; }; -//------------------------------------------------------------------------------ -/// @class ReadOperation +/// \class ReadOperation /// Implements ProcessMonitor::ReadMemory. class ReadOperation : public Operation { public: @@ -240,8 +236,7 @@ m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error); } -//------------------------------------------------------------------------------ -/// @class WriteOperation +/// \class WriteOperation /// Implements ProcessMonitor::WriteMemory. class WriteOperation : public Operation { public: @@ -266,8 +261,7 @@ m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error); } -//------------------------------------------------------------------------------ -/// @class ReadRegOperation +/// \class ReadRegOperation /// Implements ProcessMonitor::ReadRegisterValue. class ReadRegOperation : public Operation { public: @@ -306,8 +300,7 @@ } } -//------------------------------------------------------------------------------ -/// @class WriteRegOperation +/// \class WriteRegOperation /// Implements ProcessMonitor::WriteRegisterValue. class WriteRegOperation : public Operation { public: @@ -339,8 +332,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class ReadDebugRegOperation +/// \class ReadDebugRegOperation /// Implements ProcessMonitor::ReadDebugRegisterValue. class ReadDebugRegOperation : public Operation { public: @@ -374,8 +366,7 @@ } } -//------------------------------------------------------------------------------ -/// @class WriteDebugRegOperation +/// \class WriteDebugRegOperation /// Implements ProcessMonitor::WriteDebugRegisterValue. class WriteDebugRegOperation : public Operation { public: @@ -407,8 +398,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class ReadGPROperation +/// \class ReadGPROperation /// Implements ProcessMonitor::ReadGPR. class ReadGPROperation : public Operation { public: @@ -434,8 +424,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class ReadFPROperation +/// \class ReadFPROperation /// Implements ProcessMonitor::ReadFPR. class ReadFPROperation : public Operation { public: @@ -457,8 +446,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class WriteGPROperation +/// \class WriteGPROperation /// Implements ProcessMonitor::WriteGPR. class WriteGPROperation : public Operation { public: @@ -480,8 +468,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class WriteFPROperation +/// \class WriteFPROperation /// Implements ProcessMonitor::WriteFPR. class WriteFPROperation : public Operation { public: @@ -503,8 +490,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class ResumeOperation +/// \class ResumeOperation /// Implements ProcessMonitor::Resume. class ResumeOperation : public Operation { public: @@ -534,8 +520,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class SingleStepOperation +/// \class SingleStepOperation /// Implements ProcessMonitor::SingleStep. class SingleStepOperation : public Operation { public: @@ -562,8 +547,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class LwpInfoOperation +/// \class LwpInfoOperation /// Implements ProcessMonitor::GetLwpInfo. class LwpInfoOperation : public Operation { public: @@ -591,8 +575,7 @@ } } -//------------------------------------------------------------------------------ -/// @class ThreadSuspendOperation +/// \class ThreadSuspendOperation /// Implements ProcessMonitor::ThreadSuspend. class ThreadSuspendOperation : public Operation { public: @@ -611,8 +594,7 @@ m_result = !PTRACE(m_suspend ? PT_SUSPEND : PT_RESUME, m_tid, NULL, 0); } -//------------------------------------------------------------------------------ -/// @class EventMessageOperation +/// \class EventMessageOperation /// Implements ProcessMonitor::GetEventMessage. class EventMessageOperation : public Operation { public: @@ -641,8 +623,7 @@ } } -//------------------------------------------------------------------------------ -/// @class KillOperation +/// \class KillOperation /// Implements ProcessMonitor::Kill. class KillOperation : public Operation { public: @@ -663,8 +644,7 @@ m_result = true; } -//------------------------------------------------------------------------------ -/// @class DetachOperation +/// \class DetachOperation /// Implements ProcessMonitor::Detach. class DetachOperation : public Operation { public: @@ -709,7 +689,6 @@ ProcessMonitor::AttachArgs::~AttachArgs() {} -//------------------------------------------------------------------------------ /// The basic design of the ProcessMonitor is built around two threads. /// /// One thread (@see SignalThread) simply blocks on a call to waitpid() @@ -729,7 +708,7 @@ const lldb_private::ProcessLaunchInfo & /* launch_info */, lldb_private::Status &error) : m_process(static_cast<ProcessFreeBSD *>(process)), - m_pid(LLDB_INVALID_PROCESS_ID), m_terminal_fd(-1), m_operation(0) { + m_operation_thread(nullptr), m_monitor_thread(nullptr), m_pid(LLDB_INVALID_PROCESS_ID), m_terminal_fd(-1), m_operation(0) { using namespace std::placeholders; std::unique_ptr<LaunchArgs> args( @@ -759,7 +738,7 @@ m_monitor_thread = Host::StartMonitoringChildProcess( std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4), GetPID(), true); - if (!m_monitor_thread.IsJoinable()) { + if (!m_monitor_thread->IsJoinable()) { error.SetErrorToGenericError(); error.SetErrorString("Process launch failed."); return; @@ -768,8 +747,8 @@ ProcessMonitor::ProcessMonitor(ProcessFreeBSD *process, lldb::pid_t pid, lldb_private::Status &error) - : m_process(static_cast<ProcessFreeBSD *>(process)), m_pid(pid), - m_terminal_fd(-1), m_operation(0) { + : m_process(static_cast<ProcessFreeBSD *>(process)), + m_operation_thread(nullptr), m_monitor_thread(nullptr), m_pid(pid), m_terminal_fd(-1), m_operation(0) { using namespace std::placeholders; sem_init(&m_operation_pending, 0, 0); @@ -797,7 +776,7 @@ m_monitor_thread = Host::StartMonitoringChildProcess( std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4), GetPID(), true); - if (!m_monitor_thread.IsJoinable()) { + if (!m_monitor_thread->IsJoinable()) { error.SetErrorToGenericError(); error.SetErrorString("Process attach failed."); return; @@ -806,16 +785,17 @@ ProcessMonitor::~ProcessMonitor() { StopMonitor(); } -//------------------------------------------------------------------------------ // Thread setup and tear down. void ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Status &error) { static const char *g_thread_name = "lldb.process.freebsd.operation"; - if (m_operation_thread.IsJoinable()) + if (m_operation_thread->IsJoinable()) return; m_operation_thread = - ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error); + ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args); + if (!m_operation_thread) + error = m_operation_thread.takeError(); } void *ProcessMonitor::LaunchOpThread(void *arg) { @@ -977,11 +957,14 @@ lldb_private::Status &error) { static const char *g_thread_name = "lldb.process.freebsd.operation"; - if (m_operation_thread.IsJoinable()) + if (m_operation_thread->IsJoinable()) return; m_operation_thread = - ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error); + ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args); + + if (!m_operation_thread) + error = m_operation_thread.takeError(); } void *ProcessMonitor::AttachOpThread(void *arg) { @@ -1388,7 +1371,8 @@ bool ProcessMonitor::DupDescriptor(const FileSpec &file_spec, int fd, int flags) { - int target_fd = open(file_spec.GetCString(), flags, 0666); + int target_fd = llvm::sys::RetryAfterSignal(-1, open, + file_spec.GetCString(), flags, 0666); if (target_fd == -1) return false; @@ -1400,10 +1384,10 @@ } void ProcessMonitor::StopMonitoringChildProcess() { - if (m_monitor_thread.IsJoinable()) { - m_monitor_thread.Cancel(); - m_monitor_thread.Join(nullptr); - m_monitor_thread.Reset(); + if (m_monitor_thread->IsJoinable()) { + m_monitor_thread->Cancel(); + m_monitor_thread->Join(nullptr); + m_monitor_thread->Reset(); } } @@ -1438,10 +1422,10 @@ bool ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid) { return true; } void ProcessMonitor::StopOpThread() { - if (!m_operation_thread.IsJoinable()) + if (!m_operation_thread->IsJoinable()) return; - m_operation_thread.Cancel(); - m_operation_thread.Join(nullptr); - m_operation_thread.Reset(); + m_operation_thread->Cancel(); + m_operation_thread->Join(nullptr); + m_operation_thread->Reset(); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h index ca7c4e0..2adcc44 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h
@@ -1,9 +1,8 @@ //===-- ProcessMonitor.h -------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,7 +27,7 @@ class ProcessFreeBSD; class Operation; -/// @class ProcessMonitor +/// \class ProcessMonitor /// Manages communication with the inferior (debugee) process. /// /// Upon construction, this class prepares and launches an inferior process @@ -77,14 +76,14 @@ /// -1. int GetTerminalFD() const { return m_terminal_fd; } - /// Reads @p size bytes from address @vm_adder in the inferior process + /// Reads \p size bytes from address @vm_adder in the inferior process /// address space. /// /// This method is provided to implement Process::DoReadMemory. size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, lldb_private::Status &error); - /// Writes @p size bytes from address @p vm_adder in the inferior process + /// Writes \p size bytes from address \p vm_adder in the inferior process /// address space. /// /// This method is provided to implement Process::DoWriteMemory. @@ -152,7 +151,7 @@ size_t GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids); /// Writes a ptrace_lwpinfo structure corresponding to the given thread ID - /// to the memory region pointed to by @p lwpinfo. + /// to the memory region pointed to by \p lwpinfo. bool GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &error_no); /// Suspends or unsuspends a thread prior to process resume or step. @@ -163,11 +162,11 @@ /// message. bool GetEventMessage(lldb::tid_t tid, unsigned long *message); - /// Resumes the process. If @p signo is anything but + /// Resumes the process. If \p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the process. bool Resume(lldb::tid_t unused, uint32_t signo); - /// Single steps the process. If @p signo is anything but + /// Single steps the process. If \p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the process. bool SingleStep(lldb::tid_t unused, uint32_t signo); @@ -184,8 +183,8 @@ private: ProcessFreeBSD *m_process; - lldb_private::HostThread m_operation_thread; - lldb_private::HostThread m_monitor_thread; + llvm::Expected<lldb_private::HostThread> m_operation_thread; + llvm::Expected<lldb_private::HostThread> m_monitor_thread; lldb::pid_t m_pid; int m_terminal_fd; @@ -209,7 +208,7 @@ lldb_private::Status m_error; // Set if process operation failed. }; - /// @class LauchArgs + /// \class LauchArgs /// /// Simple structure to pass data to the thread responsible for launching a /// child process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIX.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIX.h index 32973ab..cf52a06 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIX.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIX.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,8 +13,7 @@ #include "lldb/Target/RegisterContext.h" #include "lldb/Utility/ArchSpec.h" -//------------------------------------------------------------------------------ -/// @class POSIXBreakpointProtocol +/// \class POSIXBreakpointProtocol /// /// Extends RegisterClass with a few virtual operations useful on POSIX. class POSIXBreakpointProtocol { @@ -28,7 +26,7 @@ /// implementation simply returns true for architectures which do not /// require any update. /// - /// @return + /// \return /// True if the operation succeeded and false otherwise. virtual bool UpdateAfterBreakpoint() = 0;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp index 0642a30..f0c4526 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_arm.cpp -----------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -156,7 +155,7 @@ DataBufferSP &data_sp) { bool success = false; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR() && ReadFPR()) { + if (ReadGPR() && ReadFPR()) { uint8_t *dst = data_sp->GetBytes(); success = dst != 0;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.h index 6aa71c2..b376967 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_arm.h --------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp index b35ee18..147f4b5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_arm64.cpp -----------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -165,7 +164,7 @@ lldb::DataBufferSP &data_sp) { bool success = false; data_sp.reset(new lldb_private::DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR() && ReadFPR()) { + if (ReadGPR() && ReadFPR()) { uint8_t *dst = data_sp->GetBytes(); success = dst != 0;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.h index 8591c83..d54d34e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_arm64.h --------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp index 17df44c..db9b5a6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_mips64.cpp -----------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -161,7 +160,7 @@ DataBufferSP &data_sp) { bool success = false; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR() && ReadFPR()) { + if (ReadGPR() && ReadFPR()) { uint8_t *dst = data_sp->GetBytes(); success = dst != 0;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.h index 6f57b0d..a482cd3 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_mips64.h -------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp index a8d7596..7769473 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_powerpc.cpp ----------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -171,7 +170,7 @@ DataBufferSP &data_sp) { bool success = false; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR() && ReadFPR()) { + if (ReadGPR() && ReadFPR()) { uint8_t *dst = data_sp->GetBytes(); success = dst != 0;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.h index 188ddea..17b649f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.h
@@ -1,10 +1,9 @@ //===-- RegisterContextPOSIXProcessMonitor_powerpc.h -------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp index 68fd5ac..3046d97 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_x86.cpp --------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -345,7 +344,7 @@ DataBufferSP &data_sp) { bool success = false; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR() && ReadFPR()) { + if (ReadGPR() && ReadFPR()) { uint8_t *dst = data_sp->GetBytes(); success = dst != 0;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.h b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.h index 8c654f9..c9dc02a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.h +++ b/src/llvm-project/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXProcessMonitor_x86.h ----------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp index 8c6c953..c1da6f3 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp
@@ -1,9 +1,8 @@ //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,6 +23,7 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostProcess.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Host/PseudoTerminal.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Host/common/NativeRegisterContext.h" @@ -32,7 +32,6 @@ #include "lldb/Host/posix/ProcessLauncherPosixFork.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Process.h" -#include "lldb/Target/ProcessLaunchInfo.h" #include "lldb/Target/Target.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/RegisterValue.h" @@ -207,9 +206,7 @@ return error; } -// ----------------------------------------------------------------------------- // Public Static Methods -// ----------------------------------------------------------------------------- llvm::Expected<std::unique_ptr<NativeProcessProtocol>> NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info, @@ -285,15 +282,13 @@ pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or)); } -// ----------------------------------------------------------------------------- // Public Instance Methods -// ----------------------------------------------------------------------------- NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd, NativeDelegate &delegate, const ArchSpec &arch, MainLoop &mainloop, llvm::ArrayRef<::pid_t> tids) - : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) { + : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) { if (m_terminal_fd != -1) { Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); assert(status.Success()); @@ -413,9 +408,9 @@ // Handle when the thread exits. if (exited) { LLDB_LOG(log, - "got exit signal({0}) , tid = {1} ({2} main thread), process " + "got exit status({0}) , tid = {1} ({2} main thread), process " "state = {3}", - signal, pid, is_main_thread ? "is" : "is not", GetState()); + status, pid, is_main_thread ? "is" : "is not", GetState()); // This is a thread that exited. Ensure we're not tracking it anymore. StopTrackingThread(pid); @@ -496,9 +491,9 @@ const bool thread_found = StopTrackingThread(pid); LLDB_LOG(log, - "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, " + "GetSignalInfo failed: {0}, tid = {1}, status = {2}, " "status = {3}, main_thread = {4}, thread_found: {5}", - info_err, pid, signal, status, is_main_thread, thread_found); + info_err, pid, status, status, is_main_thread, thread_found); if (is_main_thread) { // Notify the delegate - our process is not available but appears to @@ -604,12 +599,9 @@ // which only copies the main thread. LLDB_LOG(log, "exec received, stop tracking all but main thread"); - for (auto i = m_threads.begin(); i != m_threads.end();) { - if ((*i)->GetID() == GetID()) - i = m_threads.erase(i); - else - ++i; - } + llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) { + return t->GetID() != GetID(); + }); assert(m_threads.size() == 1); auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get()); @@ -949,25 +941,25 @@ Status error; NativeRegisterContext& register_context = thread.GetRegisterContext(); - std::unique_ptr<EmulateInstruction> emulator_ap( + std::unique_ptr<EmulateInstruction> emulator_up( EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr)); - if (emulator_ap == nullptr) + if (emulator_up == nullptr) return Status("Instruction emulator not found!"); EmulatorBaton baton(*this, register_context); - emulator_ap->SetBaton(&baton); - emulator_ap->SetReadMemCallback(&ReadMemoryCallback); - emulator_ap->SetReadRegCallback(&ReadRegisterCallback); - emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); - emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); + emulator_up->SetBaton(&baton); + emulator_up->SetReadMemCallback(&ReadMemoryCallback); + emulator_up->SetReadRegCallback(&ReadRegisterCallback); + emulator_up->SetWriteMemCallback(&WriteMemoryCallback); + emulator_up->SetWriteRegCallback(&WriteRegisterCallback); - if (!emulator_ap->ReadInstruction()) + if (!emulator_up->ReadInstruction()) return Status("Read instruction failed!"); bool emulation_result = - emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); + emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo( eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); @@ -995,7 +987,7 @@ // the size of the current opcode because the emulation of all // PC modifying instruction should be successful. The failure most // likely caused by a not supported instruction which don't modify PC. - next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize(); + next_pc = register_context.GetPC() + emulator_up->GetOpcode().GetByteSize(); next_flags = ReadFlags(register_context); } else { // The instruction emulation failed after it modified the PC. It is an @@ -1012,11 +1004,7 @@ // Arm mode error = SetSoftwareBreakpoint(next_pc, 4); } - } else if (m_arch.GetMachine() == llvm::Triple::mips64 || - m_arch.GetMachine() == llvm::Triple::mips64el || - m_arch.GetMachine() == llvm::Triple::mips || - m_arch.GetMachine() == llvm::Triple::mipsel || - m_arch.GetMachine() == llvm::Triple::ppc64le) + } else if (m_arch.IsMIPS() || m_arch.GetTriple().isPPC64()) error = SetSoftwareBreakpoint(next_pc, 4); else { // No size hint is given for the next breakpoint @@ -1036,11 +1024,7 @@ } bool NativeProcessLinux::SupportHardwareSingleStepping() const { - if (m_arch.GetMachine() == llvm::Triple::arm || - m_arch.GetMachine() == llvm::Triple::mips64 || - m_arch.GetMachine() == llvm::Triple::mips64el || - m_arch.GetMachine() == llvm::Triple::mips || - m_arch.GetMachine() == llvm::Triple::mipsel) + if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS()) return false; return true; } @@ -1402,11 +1386,6 @@ return Status("not implemented"); } -lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() { - // punt on this for now - return LLDB_INVALID_ADDRESS; -} - size_t NativeProcessLinux::UpdateThreads() { // The NativeProcessLinux monitoring threads are always up to date with // respect to thread state and they keep the thread list populated properly.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h index 69f2b52..1366f0b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h
@@ -1,9 +1,8 @@ //===-- NativeProcessLinux.h ---------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,22 +21,22 @@ #include "lldb/lldb-types.h" #include "NativeThreadLinux.h" +#include "Plugins/Process/POSIX/NativeProcessELF.h" #include "ProcessorTrace.h" -#include "lldb/Host/common/NativeProcessProtocol.h" namespace lldb_private { class Status; class Scalar; namespace process_linux { -/// @class NativeProcessLinux +/// \class NativeProcessLinux /// Manages communication with the inferior (debugee) process. /// /// Upon construction, this class prepares and launches an inferior process /// for debugging. /// /// Changes in the inferior process state are broadcasted. -class NativeProcessLinux : public NativeProcessProtocol { +class NativeProcessLinux : public NativeProcessELF { public: class Factory : public NativeProcessProtocol::Factory { public: @@ -50,9 +49,7 @@ MainLoop &mainloop) const override; }; - // --------------------------------------------------------------------- // NativeProcessProtocol Interface - // --------------------------------------------------------------------- Status Resume(const ResumeActionList &resume_actions) override; Status Halt() override; @@ -79,8 +76,6 @@ Status DeallocateMemory(lldb::addr_t addr) override; - lldb::addr_t GetSharedLibraryInfoAddress() override; - size_t UpdateThreads() override; const ArchSpec &GetArchitecture() const override { return m_arch; } @@ -121,9 +116,7 @@ Status GetTraceConfig(lldb::user_id_t traceid, TraceOptions &config) override; - // --------------------------------------------------------------------- // Interface used by NativeRegisterContext-derived classes. - // --------------------------------------------------------------------- static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr, void *data = nullptr, size_t data_size = 0, long *result = nullptr); @@ -147,9 +140,7 @@ // the relevan breakpoint std::map<lldb::tid_t, lldb::addr_t> m_threads_stepping_with_breakpoint; - // --------------------------------------------------------------------- // Private Instance Methods - // --------------------------------------------------------------------- NativeProcessLinux(::pid_t pid, int terminal_fd, NativeDelegate &delegate, const ArchSpec &arch, MainLoop &mainloop, llvm::ArrayRef<::pid_t> tids); @@ -183,7 +174,7 @@ NativeThreadLinux &AddThread(lldb::tid_t thread_id); /// Writes a siginfo_t structure corresponding to the given thread ID to the - /// memory region pointed to by @p siginfo. + /// memory region pointed to by \p siginfo. Status GetSignalInfo(lldb::tid_t tid, void *siginfo); /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.cpp index 79f635c..2f2ade0 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.h index 2cea497..10f47ee 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.cpp index 09d3a12..d720619 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_arm.cpp --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -277,10 +276,6 @@ Status error; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (!data_sp) - return Status("failed to allocate DataBufferHeap instance of size %" PRIu64, - (uint64_t)REG_CONTEXT_SIZE); - error = ReadGPR(); if (error.Fail()) return error; @@ -290,13 +285,6 @@ return error; uint8_t *dst = data_sp->GetBytes(); - if (dst == nullptr) { - error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64 - " returned a null pointer", - (uint64_t)REG_CONTEXT_SIZE); - return error; - } - ::memcpy(dst, &m_gpr_arm, GetGPRSize()); dst += GetGPRSize(); ::memcpy(dst, &m_fpr, sizeof(m_fpr));
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.h index d0b0685..d64bcdc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_arm.h ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -41,9 +40,7 @@ Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) override; - //------------------------------------------------------------------ // Hardware breakpoints/watchpoint management functions - //------------------------------------------------------------------ uint32_t NumSupportedHardwareBreakpoints() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.cpp index 9a392ed..9bb9e6b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_arm64.cpp --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -278,10 +277,6 @@ Status error; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (!data_sp) - return Status("failed to allocate DataBufferHeap instance of size %" PRIu64, - REG_CONTEXT_SIZE); - error = ReadGPR(); if (error.Fail()) return error; @@ -291,13 +286,6 @@ return error; uint8_t *dst = data_sp->GetBytes(); - if (dst == nullptr) { - error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64 - " returned a null pointer", - REG_CONTEXT_SIZE); - return error; - } - ::memcpy(dst, &m_gpr_arm64, GetGPRSize()); dst += GetGPRSize(); ::memcpy(dst, &m_fpr, sizeof(m_fpr));
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.h index c859d42..005843e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm64.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_arm64.h ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -41,9 +40,7 @@ Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) override; - //------------------------------------------------------------------ // Hardware breakpoints/watchpoint management functions - //------------------------------------------------------------------ uint32_t NumSupportedHardwareBreakpoints() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.cpp index d641056..6e4fe59 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_mips64.cpp ---------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -88,9 +87,7 @@ (GetRegisterInfoInterface().GetGPRSize() + sizeof(FPR_linux_mips) + \ sizeof(MSA_linux_mips)) -// ---------------------------------------------------------------------------- // NativeRegisterContextLinux_mips64 members. -// ---------------------------------------------------------------------------- static RegisterInfoInterface * CreateRegisterInfoInterface(const ArchSpec &target_arch) { @@ -384,13 +381,6 @@ Status error; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (!data_sp) { - error.SetErrorStringWithFormat( - "failed to allocate DataBufferHeap instance of size %" PRIu64, - REG_CONTEXT_SIZE); - return error; - } - error = ReadGPR(); if (!error.Success()) { error.SetErrorString("ReadGPR() failed"); @@ -404,13 +394,6 @@ } uint8_t *dst = data_sp->GetBytes(); - if (dst == nullptr) { - error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64 - " returned a null pointer", - REG_CONTEXT_SIZE); - return error; - } - ::memcpy(dst, &m_gpr, GetRegisterInfoInterface().GetGPRSize()); dst += GetRegisterInfoInterface().GetGPRSize(); @@ -941,25 +924,25 @@ lldb_private::ArchSpec arch; arch = GetRegisterInfoInterface().GetTargetArchitecture(); - std::unique_ptr<EmulateInstruction> emulator_ap( + std::unique_ptr<EmulateInstruction> emulator_up( EmulateInstruction::FindPlugin(arch, lldb_private::eInstructionTypeAny, nullptr)); - if (emulator_ap == nullptr) + if (emulator_up == nullptr) return LLDB_INVALID_ADDRESS; EmulatorBaton baton( static_cast<NativeProcessLinux *>(&m_thread.GetProcess()), this); - emulator_ap->SetBaton(&baton); - emulator_ap->SetReadMemCallback(&ReadMemoryCallback); - emulator_ap->SetReadRegCallback(&ReadRegisterCallback); - emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); - emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); + emulator_up->SetBaton(&baton); + emulator_up->SetReadMemCallback(&ReadMemoryCallback); + emulator_up->SetReadRegCallback(&ReadRegisterCallback); + emulator_up->SetWriteMemCallback(&WriteMemoryCallback); + emulator_up->SetWriteRegCallback(&WriteRegisterCallback); - if (!emulator_ap->ReadInstruction()) + if (!emulator_up->ReadInstruction()) return LLDB_INVALID_ADDRESS; - if (emulator_ap->EvaluateInstruction(lldb::eEmulateInstructionOptionNone)) + if (emulator_up->EvaluateInstruction(lldb::eEmulateInstructionOptionNone)) return baton.m_watch_hit_addr; return LLDB_INVALID_ADDRESS;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.h index c4e984a..5465b84 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_mips64.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_mips64.h ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.cpp index da51fda..11cf1a2 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_ppc64le.cpp ------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -355,10 +354,6 @@ Status error; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (!data_sp) - return Status("failed to allocate DataBufferHeap instance of size %" PRIu64, - REG_CONTEXT_SIZE); - error = ReadGPR(); if (error.Fail()) return error; @@ -376,13 +371,6 @@ return error; uint8_t *dst = data_sp->GetBytes(); - if (dst == nullptr) { - error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64 - " returned a null pointer", - REG_CONTEXT_SIZE); - return error; - } - ::memcpy(dst, &m_gpr_ppc64le, GetGPRSize()); dst += GetGPRSize(); ::memcpy(dst, &m_fpr_ppc64le, GetFPRSize());
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.h index 2c44719..37f9f5f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_ppc64le.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_ppc64le.h --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -48,9 +47,7 @@ Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) override; - //------------------------------------------------------------------ // Hardware watchpoint management functions - //------------------------------------------------------------------ uint32_t NumSupportedHardwareWatchpoints() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.cpp index 1bc916b..b44bb93 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_s390x.cpp --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,9 +25,7 @@ using namespace lldb_private; using namespace lldb_private::process_linux; -// ---------------------------------------------------------------------------- // Private namespace. -// ---------------------------------------------------------------------------- namespace { // s390x 64-bit general purpose registers. @@ -90,9 +87,7 @@ #define REG_CONTEXT_SIZE (sizeof(s390_regs) + sizeof(s390_fp_regs) + 4) -// ---------------------------------------------------------------------------- // Required ptrace defines. -// ---------------------------------------------------------------------------- #define NT_S390_LAST_BREAK 0x306 /* s390 breaking event address */ #define NT_S390_SYSTEM_CALL 0x307 /* s390 system call restart data */ @@ -104,9 +99,7 @@ native_thread); } -// ---------------------------------------------------------------------------- // NativeRegisterContextLinux_s390x members. -// ---------------------------------------------------------------------------- static RegisterInfoInterface * CreateRegisterInfoInterface(const ArchSpec &target_arch) { @@ -343,21 +336,7 @@ Status error; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (!data_sp) { - error.SetErrorStringWithFormat( - "failed to allocate DataBufferHeap instance of size %" PRIu64, - REG_CONTEXT_SIZE); - return error; - } - uint8_t *dst = data_sp->GetBytes(); - if (dst == nullptr) { - error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64 - " returned a null pointer", - REG_CONTEXT_SIZE); - return error; - } - error = DoReadGPR(dst, sizeof(s390_regs)); dst += sizeof(s390_regs); if (error.Fail())
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.h index 57b1a04..33fe9a6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_s390x.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_s390x.h ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.cpp index 50bf29b..3c53268 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_x86_64.cpp ---------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,15 +18,30 @@ #include "Plugins/Process/Utility/RegisterContextLinux_i386.h" #include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h" - +#include <cpuid.h> #include <linux/elf.h> +// Newer toolchains define __get_cpuid_count in cpuid.h, but some +// older-but-still-supported ones (e.g. gcc 5.4.0) don't, so we +// define it locally here, following the definition in clang/lib/Headers. +static inline int get_cpuid_count(unsigned int __leaf, + unsigned int __subleaf, + unsigned int *__eax, unsigned int *__ebx, + unsigned int *__ecx, unsigned int *__edx) +{ + unsigned int __max_leaf = __get_cpuid_max(__leaf & 0x80000000, nullptr); + + if (__max_leaf == 0 || __max_leaf < __leaf) + return 0; + + __cpuid_count(__leaf, __subleaf, *__eax, *__ebx, *__ecx, *__edx); + return 1; +} + using namespace lldb_private; using namespace lldb_private::process_linux; -// ---------------------------------------------------------------------------- // Private namespace. -// ---------------------------------------------------------------------------- namespace { // x86 32-bit general purpose registers. @@ -208,9 +222,7 @@ #define REG_CONTEXT_SIZE (GetRegisterInfoInterface().GetGPRSize() + sizeof(FPR)) -// ---------------------------------------------------------------------------- // Required ptrace defines. -// ---------------------------------------------------------------------------- // Support ptrace extensions even when compiled without required kernel support #ifndef NT_X86_XSTATE @@ -226,18 +238,14 @@ return arch.GetAddressByteSize() == 8 ? NT_PRFPREG : NT_PRXFPREG; } -// ---------------------------------------------------------------------------- // Required MPX define. -// ---------------------------------------------------------------------------- // Support MPX extensions also if compiled with compiler without MPX support. #ifndef bit_MPX #define bit_MPX 0x4000 #endif -// ---------------------------------------------------------------------------- // XCR0 extended register sets masks. -// ---------------------------------------------------------------------------- #define mask_XSTATE_AVX (1ULL << 2) #define mask_XSTATE_BNDREGS (1ULL << 3) #define mask_XSTATE_BNDCFG (1ULL << 4) @@ -250,9 +258,7 @@ new NativeRegisterContextLinux_x86_64(target_arch, native_thread)); } -// ---------------------------------------------------------------------------- // NativeRegisterContextLinux_x86_64 members. -// ---------------------------------------------------------------------------- static RegisterInfoInterface * CreateRegisterInfoInterface(const ArchSpec &target_arch) { @@ -268,12 +274,29 @@ } } +// Return the size of the XSTATE area supported on this cpu. It is necessary to +// allocate the full size of the area even if we do not use/recognise all of it +// because ptrace(PTRACE_SETREGSET, NT_X86_XSTATE) will refuse to write to it if +// we do not pass it a buffer of sufficient size. The size is always at least +// sizeof(FPR) so that the allocated buffer can be safely cast to FPR*. +static std::size_t GetXSTATESize() { + unsigned int eax, ebx, ecx, edx; + // First check whether the XSTATE are is supported at all. + if (!__get_cpuid(1, &eax, &ebx, &ecx, &edx) || !(ecx & bit_XSAVE)) + return sizeof(FPR); + + // Then fetch the maximum size of the area. + if (!get_cpuid_count(0x0d, 0, &eax, &ebx, &ecx, &edx)) + return sizeof(FPR); + return std::max<std::size_t>(ecx, sizeof(FPR)); +} + NativeRegisterContextLinux_x86_64::NativeRegisterContextLinux_x86_64( const ArchSpec &target_arch, NativeThreadProtocol &native_thread) : NativeRegisterContextLinux(native_thread, CreateRegisterInfoInterface(target_arch)), - m_xstate_type(XStateType::Invalid), m_fpr(), m_iovec(), m_ymm_set(), - m_mpx_set(), m_reg_info(), m_gpr_x86_64() { + m_xstate_type(XStateType::Invalid), m_ymm_set(), m_mpx_set(), + m_reg_info(), m_gpr_x86_64() { // Set up data about ranges of valid registers. switch (target_arch.GetMachine()) { case llvm::Triple::x86: @@ -329,14 +352,13 @@ break; } - // Initialize m_iovec to point to the buffer and buffer size using the - // conventions of Berkeley style UIO structures, as required by PTRACE - // extensions. - m_iovec.iov_base = &m_fpr; - m_iovec.iov_len = sizeof(m_fpr); + std::size_t xstate_size = GetXSTATESize(); + m_xstate.reset(static_cast<FPR *>(std::malloc(xstate_size))); + m_iovec.iov_base = m_xstate.get(); + m_iovec.iov_len = xstate_size; // Clear out the FPR state. - ::memset(&m_fpr, 0, sizeof(m_fpr)); + ::memset(m_xstate.get(), 0, xstate_size); // Store byte offset of fctrl (i.e. first register of FPR) const RegisterInfo *reg_info_fctrl = GetRegisterInfoByName("fctrl"); @@ -439,14 +461,17 @@ if (byte_order != lldb::eByteOrderInvalid) { if (reg >= m_reg_info.first_st && reg <= m_reg_info.last_st) - reg_value.SetBytes(m_fpr.fxsave.stmm[reg - m_reg_info.first_st].bytes, - reg_info->byte_size, byte_order); + reg_value.SetBytes( + m_xstate->fxsave.stmm[reg - m_reg_info.first_st].bytes, + reg_info->byte_size, byte_order); if (reg >= m_reg_info.first_mm && reg <= m_reg_info.last_mm) - reg_value.SetBytes(m_fpr.fxsave.stmm[reg - m_reg_info.first_mm].bytes, - reg_info->byte_size, byte_order); + reg_value.SetBytes( + m_xstate->fxsave.stmm[reg - m_reg_info.first_mm].bytes, + reg_info->byte_size, byte_order); if (reg >= m_reg_info.first_xmm && reg <= m_reg_info.last_xmm) - reg_value.SetBytes(m_fpr.fxsave.xmm[reg - m_reg_info.first_xmm].bytes, - reg_info->byte_size, byte_order); + reg_value.SetBytes( + m_xstate->fxsave.xmm[reg - m_reg_info.first_xmm].bytes, + reg_info->byte_size, byte_order); if (reg >= m_reg_info.first_ymm && reg <= m_reg_info.last_ymm) { // Concatenate ymm using the register halves in xmm.bytes and // ymmh.bytes @@ -488,7 +513,7 @@ return error; } - // Get pointer to m_fpr.fxsave variable and set the data from it. + // Get pointer to m_xstate->fxsave variable and set the data from it. // Byte offsets of all registers are calculated wrt 'UserArea' structure. // However, ReadFPR() reads fpu registers {using ptrace(PTRACE_GETFPREGS,..)} @@ -499,9 +524,9 @@ // Since, FPR structure is also one of the member of UserArea structure. // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) - // byte_offset(fctrl wrt UserArea) - assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) < sizeof(m_fpr)); - uint8_t *src = - (uint8_t *)&m_fpr + reg_info->byte_offset - m_fctrl_offset_in_userarea; + assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) < sizeof(FPR)); + uint8_t *src = (uint8_t *)m_xstate.get() + reg_info->byte_offset - + m_fctrl_offset_in_userarea; switch (reg_info->byte_size) { case 1: reg_value.SetUInt8(*(uint8_t *)src); @@ -527,7 +552,7 @@ void NativeRegisterContextLinux_x86_64::UpdateXSTATEforWrite( uint32_t reg_index) { - XSAVE_HDR::XFeature &xstate_bv = m_fpr.xsave.header.xstate_bv; + XSAVE_HDR::XFeature &xstate_bv = m_xstate->xsave.header.xstate_bv; if (IsFPR(reg_index)) { // IsFPR considers both %st and %xmm registers as floating point, but these // map to two features. Set both flags, just in case. @@ -559,15 +584,15 @@ if (IsFPR(reg_index) || IsAVX(reg_index) || IsMPX(reg_index)) { if (reg_info->encoding == lldb::eEncodingVector) { if (reg_index >= m_reg_info.first_st && reg_index <= m_reg_info.last_st) - ::memcpy(m_fpr.fxsave.stmm[reg_index - m_reg_info.first_st].bytes, + ::memcpy(m_xstate->fxsave.stmm[reg_index - m_reg_info.first_st].bytes, reg_value.GetBytes(), reg_value.GetByteSize()); if (reg_index >= m_reg_info.first_mm && reg_index <= m_reg_info.last_mm) - ::memcpy(m_fpr.fxsave.stmm[reg_index - m_reg_info.first_mm].bytes, + ::memcpy(m_xstate->fxsave.stmm[reg_index - m_reg_info.first_mm].bytes, reg_value.GetBytes(), reg_value.GetByteSize()); if (reg_index >= m_reg_info.first_xmm && reg_index <= m_reg_info.last_xmm) - ::memcpy(m_fpr.fxsave.xmm[reg_index - m_reg_info.first_xmm].bytes, + ::memcpy(m_xstate->fxsave.xmm[reg_index - m_reg_info.first_xmm].bytes, reg_value.GetBytes(), reg_value.GetByteSize()); if (reg_index >= m_reg_info.first_ymm && @@ -596,7 +621,7 @@ return Status("CopyMPXtoXSTATE() failed"); } } else { - // Get pointer to m_fpr.fxsave variable and set the data to it. + // Get pointer to m_xstate->fxsave variable and set the data to it. // Byte offsets of all registers are calculated wrt 'UserArea' structure. // However, WriteFPR() takes m_fpr (of type FPR structure) and writes @@ -608,8 +633,8 @@ // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) - // byte_offset(fctrl wrt UserArea) assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) < - sizeof(m_fpr)); - uint8_t *dst = (uint8_t *)&m_fpr + reg_info->byte_offset - + sizeof(FPR)); + uint8_t *dst = (uint8_t *)m_xstate.get() + reg_info->byte_offset - m_fctrl_offset_in_userarea; switch (reg_info->byte_size) { case 1: @@ -667,7 +692,7 @@ ::memcpy(dst, &m_gpr_x86_64, GetRegisterInfoInterface().GetGPRSize()); dst += GetRegisterInfoInterface().GetGPRSize(); if (m_xstate_type == XStateType::FXSAVE) - ::memcpy(dst, &m_fpr.fxsave, sizeof(m_fpr.fxsave)); + ::memcpy(dst, &m_xstate->fxsave, sizeof(m_xstate->fxsave)); else if (m_xstate_type == XStateType::XSAVE) { lldb::ByteOrder byte_order = GetByteOrder(); @@ -700,7 +725,7 @@ } } // Copy the extended register state including the assembled ymm registers. - ::memcpy(dst, &m_fpr, sizeof(m_fpr)); + ::memcpy(dst, m_xstate.get(), sizeof(FPR)); } else { assert(false && "how do we save the floating point registers?"); error.SetErrorString("unsure how to save the floating point registers"); @@ -758,9 +783,9 @@ src += GetRegisterInfoInterface().GetGPRSize(); if (m_xstate_type == XStateType::FXSAVE) - ::memcpy(&m_fpr.fxsave, src, sizeof(m_fpr.fxsave)); + ::memcpy(&m_xstate->fxsave, src, sizeof(m_xstate->fxsave)); else if (m_xstate_type == XStateType::XSAVE) - ::memcpy(&m_fpr.xsave, src, sizeof(m_fpr.xsave)); + ::memcpy(&m_xstate->xsave, src, sizeof(m_xstate->xsave)); error = WriteFPR(); if (error.Fail()) @@ -814,12 +839,12 @@ return true; case RegSet::avx: // Check if CPU has AVX and if there is kernel support, by // reading in the XCR0 area of XSAVE. - if ((m_fpr.xsave.i387.xcr0 & mask_XSTATE_AVX) == mask_XSTATE_AVX) + if ((m_xstate->xsave.i387.xcr0 & mask_XSTATE_AVX) == mask_XSTATE_AVX) return true; break; case RegSet::mpx: // Check if CPU has MPX and if there is kernel support, by // reading in the XCR0 area of XSAVE. - if ((m_fpr.xsave.i387.xcr0 & mask_XSTATE_MPX) == mask_XSTATE_MPX) + if ((m_xstate->xsave.i387.xcr0 & mask_XSTATE_MPX) == mask_XSTATE_MPX) return true; break; } @@ -856,10 +881,10 @@ switch (m_xstate_type) { case XStateType::FXSAVE: return WriteRegisterSet( - &m_iovec, sizeof(m_fpr.fxsave), + &m_iovec, sizeof(m_xstate->fxsave), fxsr_regset(GetRegisterInfoInterface().GetTargetArchitecture())); case XStateType::XSAVE: - return WriteRegisterSet(&m_iovec, sizeof(m_fpr.xsave), NT_X86_XSTATE); + return WriteRegisterSet(&m_iovec, sizeof(m_xstate->xsave), NT_X86_XSTATE); default: return Status("Unrecognized FPR type."); } @@ -878,26 +903,13 @@ return false; if (byte_order == lldb::eByteOrderLittle) { - ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes, - m_fpr.fxsave.xmm[reg_index - m_reg_info.first_ymm].bytes, - sizeof(XMMReg)); - ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes + - sizeof(XMMReg), - m_fpr.xsave.ymmh[reg_index - m_reg_info.first_ymm].bytes, - sizeof(YMMHReg)); + uint32_t reg_no = reg_index - m_reg_info.first_ymm; + m_ymm_set.ymm[reg_no] = XStateToYMM( + m_xstate->fxsave.xmm[reg_no].bytes, + m_xstate->xsave.ymmh[reg_no].bytes); return true; } - if (byte_order == lldb::eByteOrderBig) { - ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes + - sizeof(XMMReg), - m_fpr.fxsave.xmm[reg_index - m_reg_info.first_ymm].bytes, - sizeof(XMMReg)); - ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes, - m_fpr.xsave.ymmh[reg_index - m_reg_info.first_ymm].bytes, - sizeof(YMMHReg)); - return true; - } return false; // unsupported or invalid byte order } @@ -907,29 +919,20 @@ return false; if (byte_order == lldb::eByteOrderLittle) { - ::memcpy(m_fpr.fxsave.xmm[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(XMMReg)); - ::memcpy(m_fpr.xsave.ymmh[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg), - sizeof(YMMHReg)); + uint32_t reg_no = reg - m_reg_info.first_ymm; + YMMToXState(m_ymm_set.ymm[reg_no], + m_xstate->fxsave.xmm[reg_no].bytes, + m_xstate->xsave.ymmh[reg_no].bytes); return true; } - if (byte_order == lldb::eByteOrderBig) { - ::memcpy(m_fpr.fxsave.xmm[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg), - sizeof(XMMReg)); - ::memcpy(m_fpr.xsave.ymmh[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(YMMHReg)); - return true; - } return false; // unsupported or invalid byte order } void *NativeRegisterContextLinux_x86_64::GetFPRBuffer() { switch (m_xstate_type) { case XStateType::FXSAVE: - return &m_fpr.fxsave; + return &m_xstate->fxsave; case XStateType::XSAVE: return &m_iovec; default: @@ -940,7 +943,7 @@ size_t NativeRegisterContextLinux_x86_64::GetFPRSize() { switch (m_xstate_type) { case XStateType::FXSAVE: - return sizeof(m_fpr.fxsave); + return sizeof(m_xstate->fxsave); case XStateType::XSAVE: return sizeof(m_iovec); default: @@ -953,14 +956,14 @@ // Probe XSAVE and if it is not supported fall back to FXSAVE. if (m_xstate_type != XStateType::FXSAVE) { - error = ReadRegisterSet(&m_iovec, sizeof(m_fpr.xsave), NT_X86_XSTATE); + error = ReadRegisterSet(&m_iovec, sizeof(m_xstate->xsave), NT_X86_XSTATE); if (!error.Fail()) { m_xstate_type = XStateType::XSAVE; return error; } } error = ReadRegisterSet( - &m_iovec, sizeof(m_fpr.xsave), + &m_iovec, sizeof(m_xstate->xsave), fxsr_regset(GetRegisterInfoInterface().GetTargetArchitecture())); if (!error.Fail()) { m_xstate_type = XStateType::FXSAVE; @@ -982,11 +985,11 @@ if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) { ::memcpy(m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes, - m_fpr.xsave.mpxr[reg - m_reg_info.first_mpxr].bytes, + m_xstate->xsave.mpxr[reg - m_reg_info.first_mpxr].bytes, sizeof(MPXReg)); } else { ::memcpy(m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes, - m_fpr.xsave.mpxc[reg - m_reg_info.first_mpxc].bytes, + m_xstate->xsave.mpxc[reg - m_reg_info.first_mpxc].bytes, sizeof(MPXCsr)); } return true; @@ -997,10 +1000,10 @@ return false; if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) { - ::memcpy(m_fpr.xsave.mpxr[reg - m_reg_info.first_mpxr].bytes, + ::memcpy(m_xstate->xsave.mpxr[reg - m_reg_info.first_mpxr].bytes, m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes, sizeof(MPXReg)); } else { - ::memcpy(m_fpr.xsave.mpxc[reg - m_reg_info.first_mpxc].bytes, + ::memcpy(m_xstate->xsave.mpxc[reg - m_reg_info.first_mpxc].bytes, m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes, sizeof(MPXCsr)); } return true;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.h index 9dcf82f..6031ddb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_x86_64.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextLinux_x86_64.h ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -109,7 +108,8 @@ // Private member variables. mutable XStateType m_xstate_type; - FPR m_fpr; // Extended States Area, named FPR for historical reasons. + std::unique_ptr<FPR, llvm::FreeDeleter> + m_xstate; // Extended States Area, named FPR for historical reasons. struct iovec m_iovec; YMM m_ymm_set; MPX m_mpx_set;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.cpp index b64689c..287a271 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.cpp
@@ -1,9 +1,8 @@ //===-- NativeThreadLinux.cpp --------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.h index a7c4e98..fd43c89 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/NativeThreadLinux.h
@@ -1,9 +1,8 @@ //===-- NativeThreadLinux.h ----------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,9 +30,7 @@ public: NativeThreadLinux(NativeProcessLinux &process, lldb::tid_t tid); - // --------------------------------------------------------------------- // NativeThreadProtocol Interface - // --------------------------------------------------------------------- std::string GetName() override; lldb::StateType GetState() override; @@ -55,15 +52,13 @@ Status RemoveHardwareBreakpoint(lldb::addr_t addr) override; private: - // --------------------------------------------------------------------- // Interface for friend classes - // --------------------------------------------------------------------- - /// Resumes the thread. If @p signo is anything but + /// Resumes the thread. If \p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread. Status Resume(uint32_t signo); - /// Single steps the thread. If @p signo is anything but + /// Single steps the thread. If \p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread. Status SingleStep(uint32_t signo); @@ -92,18 +87,14 @@ Status RequestStop(); - // --------------------------------------------------------------------- // Private interface - // --------------------------------------------------------------------- void MaybeLogStateChange(lldb::StateType new_state); NativeProcessLinux &GetProcess(); void SetStopped(); - // --------------------------------------------------------------------- // Member Variables - // --------------------------------------------------------------------- lldb::StateType m_state; ThreadStopInfo m_stop_info; std::unique_ptr<NativeRegisterContextLinux> m_reg_context_up;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.cpp index 505c526..a7e8c00 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.cpp
@@ -1,9 +1,8 @@ //===-- ProcessorTrace.cpp ------------------------------------ -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -118,7 +117,7 @@ errno = 0; auto base = - mmap(NULL, (metabufsize + page_size), PROT_WRITE, MAP_SHARED, fd, 0); + mmap(nullptr, (metabufsize + page_size), PROT_WRITE, MAP_SHARED, fd, 0); if (base == MAP_FAILED) { LLDB_LOG(log, "mmap base error {0}", errno); @@ -134,7 +133,7 @@ m_mmap_meta->aux_size = bufsize; errno = 0; - auto mmap_aux = mmap(NULL, bufsize, PROT_READ, MAP_SHARED, fd, + auto mmap_aux = mmap(nullptr, bufsize, PROT_READ, MAP_SHARED, fd, static_cast<long int>(m_mmap_meta->aux_offset)); if (mmap_aux == MAP_FAILED) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.h index 6fd918c..de9bd8c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/ProcessorTrace.h
@@ -1,9 +1,8 @@ //===-- ProcessorTrace.h -------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,7 +23,6 @@ namespace process_linux { -// --------------------------------------------------------------------- // This class keeps track of one tracing instance of // Intel(R) Processor Trace on Linux OS. There is a map keeping track // of different tracing instances on each thread, which enables trace @@ -37,7 +35,6 @@ // The trace id could map to trace instances for a group of threads // (spanning to all the threads in the process) or a single thread. // The kernel interface for us is the perf_event_open. -// --------------------------------------------------------------------- class ProcessorTraceMonitor; typedef std::unique_ptr<ProcessorTraceMonitor> ProcessorTraceMonitorUP; @@ -116,22 +113,20 @@ Status GetTraceConfig(TraceOptions &config) const; - // --------------------------------------------------------------------- /// Read data from a cyclic buffer /// - /// @param[in] [out] buf + /// \param[in] [out] buf /// Destination buffer, the buffer will be truncated to written size. /// - /// @param[in] src + /// \param[in] src /// Source buffer which must be a cyclic buffer. /// - /// @param[in] src_cyc_index + /// \param[in] src_cyc_index /// The index pointer (start of the valid data in the cyclic /// buffer). /// - /// @param[in] offset + /// \param[in] offset /// The offset to begin reading the data in the cyclic buffer. - // --------------------------------------------------------------------- static void ReadCyclicBuffer(llvm::MutableArrayRef<uint8_t> &dst, llvm::MutableArrayRef<uint8_t> src, size_t src_cyc_index, size_t offset);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/Procfs.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/Procfs.h index 1d9c9db..59dd76a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/Procfs.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/Procfs.h
@@ -1,9 +1,8 @@ //===-- Procfs.h ---------------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.cpp b/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.cpp index c57a2da..a7837da 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.cpp
@@ -1,9 +1,8 @@ //===-- SingleStepCheck.cpp ----------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,6 +16,7 @@ #include "NativeProcessLinux.h" #include "llvm/Support/Compiler.h" +#include "llvm/Support/Errno.h" #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" #include "lldb/Host/linux/Ptrace.h" @@ -52,8 +52,10 @@ ~ChildDeleter() { int status; - kill(pid, SIGKILL); // Kill the child. - waitpid(pid, &status, __WALL); // Pick up the remains. + // Kill the child. + kill(pid, SIGKILL); + // Pick up the remains. + llvm::sys::RetryAfterSignal(-1, waitpid, pid, &status, __WALL); } }; @@ -82,7 +84,8 @@ } int status; - ::pid_t wpid = waitpid(child_pid, &status, __WALL); + ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, waitpid, + child_pid, &status, __WALL); if (wpid != child_pid || !WIFSTOPPED(status)) { LLDB_LOG(log, "waitpid() failed (status = {0:x}): {1}", status, Status(errno, eErrorTypePOSIX)); @@ -111,7 +114,8 @@ break; } - wpid = waitpid(child_pid, &status, __WALL); + wpid = llvm::sys::RetryAfterSignal(-1, waitpid, + child_pid, &status, __WALL); if (wpid != child_pid || !WIFSTOPPED(status)) { LLDB_LOG(log, "waitpid() failed (status = {0:x}): {1}", status, Status(errno, eErrorTypePOSIX));
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.h b/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.h index afeda73..c55771e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Linux/SingleStepCheck.h
@@ -1,9 +1,8 @@ //===-- SingleStepCheck.h ------------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.cpp index 8908108..1a75326 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.cpp
@@ -1,9 +1,8 @@ //===-- CommunicationKDP.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,9 +28,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // CommunicationKDP constructor -//---------------------------------------------------------------------- CommunicationKDP::CommunicationKDP(const char *comm_name) : Communication(comm_name), m_addr_byte_size(4), m_byte_order(eByteOrderLittle), m_packet_timeout(5), m_sequence_mutex(), @@ -40,9 +37,7 @@ m_kdp_version_feature(0u), m_kdp_hostinfo_cpu_mask(0u), m_kdp_hostinfo_cpu_type(0u), m_kdp_hostinfo_cpu_subtype(0u) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- CommunicationKDP::~CommunicationKDP() { if (IsConnected()) { Disconnect(); @@ -92,7 +87,7 @@ for (uint32_t i = 0; i < num_retries; ++i) { if (SendRequestPacketNoLock(request_packet)) { const uint8_t request_sequence_id = (uint8_t)request_packet.GetData()[1]; - while (1) { + while (true) { if (WaitForPacketWithTimeoutMicroSecondsNoLock( reply_packet, std::chrono::microseconds(GetPacketTimeout()).count())) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.h index 64bfe55..47013c9 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.h
@@ -1,9 +1,8 @@ //===-- CommunicationKDP.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -27,7 +26,7 @@ const static uint32_t kMaxPacketSize = 1200; const static uint32_t kMaxDataSize = 1024; typedef lldb_private::StreamBuffer<1024> PacketStreamType; - typedef enum { + enum CommandType { KDP_CONNECT = 0u, KDP_DISCONNECT, KDP_HOSTINFO, @@ -60,26 +59,24 @@ KDP_READMSR64, KDP_WRITEMSR64, KDP_DUMPINFO - } CommandType; + }; enum { KDP_FEATURE_BP = (1u << 0) }; - typedef enum { + enum KDPError { KDP_PROTERR_SUCCESS = 0, KDP_PROTERR_ALREADY_CONNECTED, KDP_PROTERR_BAD_NBYTES, KDP_PROTERR_BADFLAVOR - } KDPError; + }; - typedef enum { + enum PacketType { ePacketTypeRequest = 0x00u, ePacketTypeReply = 0x80u, ePacketTypeMask = 0x80u, eCommandTypeMask = 0x7fu - } PacketType; - //------------------------------------------------------------------ + }; // Constructors and Destructors - //------------------------------------------------------------------ CommunicationKDP(const char *comm_name); virtual ~CommunicationKDP(); @@ -97,14 +94,12 @@ lldb_private::DataExtractor &packet); bool IsRunning() const { return m_is_running.GetValue(); } - //------------------------------------------------------------------ // Set the global packet timeout. // // For clients, this is the timeout that gets used when sending // packets and waiting for responses. For servers, this might not // get used, and if it doesn't this should be moved to the // CommunicationKDPClient. - //------------------------------------------------------------------ std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout) { const auto old_packet_timeout = m_packet_timeout; m_packet_timeout = packet_timeout; @@ -113,9 +108,7 @@ std::chrono::seconds GetPacketTimeout() const { return m_packet_timeout; } - //------------------------------------------------------------------ // Public Request Packets - //------------------------------------------------------------------ bool SendRequestConnect(uint16_t reply_port, uint16_t exc_port, const char *greeting); @@ -189,10 +182,8 @@ PacketStreamType &request_packet, uint16_t request_length); - //------------------------------------------------------------------ // Protected Request Packets (use public accessors which will cache // results. - //------------------------------------------------------------------ bool SendRequestVersion(); bool SendRequestHostInfo(); @@ -229,9 +220,7 @@ bool SendRequestAndGetReply(const CommandType command, const PacketStreamType &request_packet, lldb_private::DataExtractor &reply_packet); - //------------------------------------------------------------------ // Classes that inherit from CommunicationKDP can see and modify these - //------------------------------------------------------------------ uint32_t m_addr_byte_size; lldb::ByteOrder m_byte_order; std::chrono::seconds m_packet_timeout; @@ -251,9 +240,7 @@ // hang the KDP connection... lldb::addr_t m_last_read_memory_addr; // Last memory read address for logging private: - //------------------------------------------------------------------ // For CommunicationKDP only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(CommunicationKDP); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.cpp index c1c3678..6f1bb4b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.cpp
@@ -1,15 +1,15 @@ //===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <errno.h> #include <stdlib.h> +#include <memory> #include <mutex> #include "lldb/Core/Debugger.h" @@ -18,7 +18,6 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/Host.h" -#include "lldb/Host/Symbols.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Host/common/TCPSocket.h" #include "lldb/Interpreter/CommandInterpreter.h" @@ -28,10 +27,12 @@ #include "lldb/Interpreter/OptionGroupString.h" #include "lldb/Interpreter/OptionGroupUInt64.h" #include "lldb/Interpreter/OptionValueProperties.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" +#include "lldb/Utility/Log.h" #include "lldb/Utility/State.h" #include "lldb/Utility/StringExtractor.h" #include "lldb/Utility/UUID.h" @@ -64,7 +65,7 @@ } PluginProperties() : Properties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); } @@ -82,7 +83,7 @@ static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() { static ProcessKDPPropertiesSP g_settings_sp; if (!g_settings_sp) - g_settings_sp.reset(new PluginProperties()); + g_settings_sp = std::make_shared<PluginProperties>(); return g_settings_sp; } @@ -109,7 +110,7 @@ const FileSpec *crash_file_path) { lldb::ProcessSP process_sp; if (crash_file_path == NULL) - process_sp.reset(new ProcessKDP(target_sp, listener_sp)); + process_sp = std::make_shared<ProcessKDP>(target_sp, listener_sp); return process_sp; } @@ -143,9 +144,7 @@ return false; } -//---------------------------------------------------------------------- // ProcessKDP constructor -//---------------------------------------------------------------------- ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp) : Process(target_sp, listener_sp), m_comm("lldb.process.kdp-remote.communication"), @@ -162,9 +161,7 @@ m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds)); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ProcessKDP::~ProcessKDP() { Clear(); // We need to call finalize on the process before destroying ourselves to @@ -174,9 +171,7 @@ Finalize(); } -//---------------------------------------------------------------------- // PluginInterface -//---------------------------------------------------------------------- lldb_private::ConstString ProcessKDP::GetPluginName() { return GetPluginNameStatic(); } @@ -231,27 +226,27 @@ return error; } - std::unique_ptr<ConnectionFileDescriptor> conn_ap( + std::unique_ptr<ConnectionFileDescriptor> conn_up( new ConnectionFileDescriptor()); - if (conn_ap.get()) { + if (conn_up) { // Only try once for now. // TODO: check if we should be retrying? const uint32_t max_retry_count = 1; for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count) { - if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess) + if (conn_up->Connect(remote_url, &error) == eConnectionStatusSuccess) break; usleep(100000); } } - if (conn_ap->IsConnected()) { + if (conn_up->IsConnected()) { const TCPSocket &socket = - static_cast<const TCPSocket &>(*conn_ap->GetReadObject()); + static_cast<const TCPSocket &>(*conn_up->GetReadObject()); const uint16_t reply_port = socket.GetLocalPortNumber(); if (reply_port != 0) { - m_comm.SetConnection(conn_ap.release()); + m_comm.SetConnection(conn_up.release()); if (m_comm.SendRequestReattach(reply_port)) { if (m_comm.SendRequestConnect(reply_port, reply_port, @@ -291,8 +286,11 @@ module_spec.GetArchitecture() = target.GetArchitecture(); // Lookup UUID locally, before attempting dsymForUUID like action + FileSpecList search_paths = + Target::GetDefaultDebugFileSearchPaths(); module_spec.GetSymbolFileSpec() = - Symbols::LocateExecutableSymbolFile(module_spec); + Symbols::LocateExecutableSymbolFile(module_spec, + search_paths); if (module_spec.GetSymbolFileSpec()) { ModuleSpec executable_module_spec = Symbols::LocateExecutableObjectFile(module_spec); @@ -366,9 +364,7 @@ return error; } -//---------------------------------------------------------------------- // Process Control -//---------------------------------------------------------------------- Status ProcessKDP::DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) { Status error; @@ -408,11 +404,11 @@ addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; } lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() { - if (m_dyld_ap.get() == NULL) - m_dyld_ap.reset(DynamicLoader::FindPlugin( + if (m_dyld_up.get() == NULL) + m_dyld_up.reset(DynamicLoader::FindPlugin( this, m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString())); - return m_dyld_ap.get(); + return m_dyld_up.get(); } Status ProcessKDP::WillResume() { return Status(); } @@ -506,7 +502,7 @@ ThreadSP thread_sp(m_kernel_thread_wp.lock()); if (!thread_sp) { - thread_sp.reset(new ThreadKDP(*this, g_kernel_tid)); + thread_sp = std::make_shared<ThreadKDP>(*this, g_kernel_tid); m_kernel_thread_wp = thread_sp; } return thread_sp; @@ -592,17 +588,13 @@ return DoDetach(keep_stopped); } -//------------------------------------------------------------------ // Process Queries -//------------------------------------------------------------------ bool ProcessKDP::IsAlive() { return m_comm.IsConnected() && Process::IsAlive(); } -//------------------------------------------------------------------ // Process Memory -//------------------------------------------------------------------ size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size, Status &error) { uint8_t *data_buffer = (uint8_t *)buf; @@ -748,8 +740,15 @@ if (m_async_thread.IsJoinable()) return true; - m_async_thread = ThreadLauncher::LaunchThread( - "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL); + llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( + "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this); + if (!async_thread) { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(async_thread.takeError())); + return false; + } + m_async_thread = *async_thread; return m_async_thread.IsJoinable(); } @@ -1031,7 +1030,7 @@ CommandObject *ProcessKDP::GetPluginCommandObject() { if (!m_command_sp) - m_command_sp.reset(new CommandObjectMultiwordProcessKDP( - GetTarget().GetDebugger().GetCommandInterpreter())); + m_command_sp = std::make_shared<CommandObjectMultiwordProcessKDP>( + GetTarget().GetDebugger().GetCommandInterpreter()); return m_command_sp.get(); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.h index f910244..a7f8466 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.h
@@ -1,9 +1,8 @@ //===-- ProcessKDP.h --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,9 +30,7 @@ class ProcessKDP : public lldb_private::Process { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const lldb_private::FileSpec *crash_file_path); @@ -48,23 +45,17 @@ static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ ProcessKDP(lldb::TargetSP target_sp, lldb::ListenerSP listener); ~ProcessKDP() override; - //------------------------------------------------------------------ // Check if a given Process - //------------------------------------------------------------------ bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override; lldb_private::CommandObject *GetPluginCommandObject() override; - //------------------------------------------------------------------ // Creating a new process, or attaching to an existing one - //------------------------------------------------------------------ lldb_private::Status WillLaunch(lldb_private::Module *module) override; lldb_private::Status @@ -94,16 +85,12 @@ lldb_private::DynamicLoader *GetDynamicLoader() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - //------------------------------------------------------------------ // Process Control - //------------------------------------------------------------------ lldb_private::Status WillResume() override; lldb_private::Status DoResume() override; @@ -118,14 +105,10 @@ void RefreshStateAfterStop() override; - //------------------------------------------------------------------ // Process Queries - //------------------------------------------------------------------ bool IsAlive() override; - //------------------------------------------------------------------ // Process Memory - //------------------------------------------------------------------ size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, lldb_private::Status &error) override; @@ -137,18 +120,14 @@ lldb_private::Status DoDeallocateMemory(lldb::addr_t ptr) override; - //---------------------------------------------------------------------- // Process Breakpoints - //---------------------------------------------------------------------- lldb_private::Status EnableBreakpointSite(lldb_private::BreakpointSite *bp_site) override; lldb_private::Status DisableBreakpointSite(lldb_private::BreakpointSite *bp_site) override; - //---------------------------------------------------------------------- // Process Watchpoints - //---------------------------------------------------------------------- lldb_private::Status EnableWatchpoint(lldb_private::Watchpoint *wp, bool notify = true) override; @@ -161,9 +140,7 @@ friend class ThreadKDP; friend class CommunicationKDP; - //---------------------------------------------------------------------- // Accessors - //---------------------------------------------------------------------- bool IsRunning(lldb::StateType state) { return state == lldb::eStateRunning || IsStepping(state); } @@ -192,9 +169,7 @@ lldb::ThreadSP GetKernelThread(); - //------------------------------------------------------------------ /// Broadcaster event bits definitions. - //------------------------------------------------------------------ CommunicationKDP m_comm; lldb_private::Broadcaster m_async_broadcaster; lldb_private::HostThread m_async_thread; @@ -210,9 +185,7 @@ static void *AsyncThread(void *arg); private: - //------------------------------------------------------------------ // For ProcessKDP only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(ProcessKDP); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.cpp index ffab3e5..96d2921 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.cpp
@@ -1,9 +1,8 @@ //===-- ProcessKDPLog.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.h index 908754e..c22dd98 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDPLog.h
@@ -1,9 +1,8 @@ //===-- ProcessKDPLog.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.cpp index 0f9e62c..da6e0f5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextKDP_arm.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.h index 1532f23..e31da42 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterContextKDP_arm.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.cpp index e13a7f3..f834986 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.cpp
@@ -1,10 +1,9 @@ //===-- RegisterContextKDP_arm64.cpp ------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.h index be4038b..29dfc67 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_arm64.h
@@ -1,10 +1,9 @@ //===-- RegisterContextKDP_arm64.h --------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.cpp index 096aa0f..7cb057d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextKDP_i386.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.h index 699d5fa..fd48fbd 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_i386.h
@@ -1,9 +1,8 @@ //===-- RegisterContextKDP_i386.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.cpp index 9d85145..701c160 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextKDP_x86_64.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.h index 9841ad7..7962309 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/RegisterContextKDP_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextKDP_x86_64.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.cpp b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.cpp index 6f26acd..77361ef 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.cpp
@@ -1,9 +1,8 @@ //===-- ThreadKDP.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,12 +29,12 @@ #include "RegisterContextKDP_i386.h" #include "RegisterContextKDP_x86_64.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Thread Registers -//---------------------------------------------------------------------- ThreadKDP::ThreadKDP(Process &process, lldb::tid_t tid) : Thread(process, tid), m_thread_name(), m_dispatch_queue_name(), @@ -99,19 +98,20 @@ ->GetCommunication() .GetCPUType()) { case llvm::MachO::CPU_TYPE_ARM: - reg_ctx_sp.reset(new RegisterContextKDP_arm(*this, concrete_frame_idx)); + reg_ctx_sp = + std::make_shared<RegisterContextKDP_arm>(*this, concrete_frame_idx); break; case llvm::MachO::CPU_TYPE_ARM64: - reg_ctx_sp.reset( - new RegisterContextKDP_arm64(*this, concrete_frame_idx)); + reg_ctx_sp = std::make_shared<RegisterContextKDP_arm64>( + *this, concrete_frame_idx); break; case llvm::MachO::CPU_TYPE_I386: - reg_ctx_sp.reset( - new RegisterContextKDP_i386(*this, concrete_frame_idx)); + reg_ctx_sp = std::make_shared<RegisterContextKDP_i386>( + *this, concrete_frame_idx); break; case llvm::MachO::CPU_TYPE_X86_64: - reg_ctx_sp.reset( - new RegisterContextKDP_x86_64(*this, concrete_frame_idx)); + reg_ctx_sp = std::make_shared<RegisterContextKDP_x86_64>( + *this, concrete_frame_idx); break; default: llvm_unreachable("Add CPU type support in KDP");
diff --git a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.h b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.h index ea517b4..9971ea7 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.h +++ b/src/llvm-project/lldb/source/Plugins/Process/MacOSX-Kernel/ThreadKDP.h
@@ -1,9 +1,8 @@ //===-- ThreadKDP.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -61,16 +60,12 @@ protected: friend class ProcessKDP; - //------------------------------------------------------------------ // Member variables. - //------------------------------------------------------------------ std::string m_thread_name; std::string m_dispatch_queue_name; lldb::addr_t m_thread_dispatch_qaddr; lldb::StopInfoSP m_cached_stop_info_sp; - //------------------------------------------------------------------ // Protected member functions. - //------------------------------------------------------------------ virtual bool CalculateStopInfo(); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp index a1b7d7d..32d20d2 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp
@@ -1,9 +1,8 @@ //===-- NativeProcessNetBSD.cpp ------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -55,9 +54,7 @@ return error; } -// ----------------------------------------------------------------------------- // Public Static Methods -// ----------------------------------------------------------------------------- llvm::Expected<std::unique_ptr<NativeProcessProtocol>> NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info, @@ -137,9 +134,7 @@ return std::move(process_up); } -// ----------------------------------------------------------------------------- // Public Instance Methods -// ----------------------------------------------------------------------------- NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd, NativeDelegate &delegate, @@ -243,12 +238,25 @@ SetState(StateType::eStateStopped, true); } break; case TRAP_DBREG: { + // Find the thread. + NativeThreadNetBSD* thread = nullptr; + for (const auto &t : m_threads) { + if (t->GetID() == info.psi_lwpid) { + thread = static_cast<NativeThreadNetBSD *>(t.get()); + break; + } + } + if (!thread) { + LLDB_LOG(log, + "thread not found in m_threads, pid = {0}, LWP = {1}", + GetID(), info.psi_lwpid); + break; + } + // If a watchpoint was hit, report it - uint32_t wp_index; - Status error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid]) - .GetRegisterContext() - .GetWatchpointHitIndex( - wp_index, (uintptr_t)info.psi_siginfo.si_addr); + uint32_t wp_index = LLDB_INVALID_INDEX32; + Status error = thread->GetRegisterContext().GetWatchpointHitIndex( + wp_index, (uintptr_t)info.psi_siginfo.si_addr); if (error.Fail()) LLDB_LOG(log, "received error while checking for watchpoint hits, pid = " @@ -263,11 +271,9 @@ } // If a breakpoint was hit, report it - uint32_t bp_index; - error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid]) - .GetRegisterContext() - .GetHardwareBreakHitIndex(bp_index, - (uintptr_t)info.psi_siginfo.si_addr); + uint32_t bp_index = LLDB_INVALID_INDEX32; + error = thread->GetRegisterContext().GetHardwareBreakHitIndex( + bp_index, (uintptr_t)info.psi_siginfo.si_addr); if (error.Fail()) LLDB_LOG(log, "received error while checking for hardware " @@ -666,7 +672,8 @@ int wstatus; // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this // point we should have a thread stopped if waitpid succeeds. - if ((wstatus = waitpid(m_pid, NULL, WALLSIG)) < 0) + if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, + m_pid, nullptr, WALLSIG)) < 0) return Status(errno, eErrorTypePOSIX); /* Initialize threads */ @@ -699,10 +706,10 @@ io.piod_addr = dst + bytes_read; Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); - if (error.Fail()) + if (error.Fail() || io.piod_len == 0) return error; - bytes_read = io.piod_len; + bytes_read += io.piod_len; io.piod_len = size - bytes_read; } while (bytes_read < size); @@ -727,10 +734,10 @@ io.piod_offs = (void *)(addr + bytes_written); Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); - if (error.Fail()) + if (error.Fail() || io.piod_len == 0) return error; - bytes_written = io.piod_len; + bytes_written += io.piod_len; io.piod_len = size - bytes_written; } while (bytes_written < size);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h index a3f1c4c..e85ca3b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h
@@ -1,9 +1,8 @@ //===-- NativeProcessNetBSD.h --------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,7 +18,7 @@ namespace lldb_private { namespace process_netbsd { -/// @class NativeProcessNetBSD +/// \class NativeProcessNetBSD /// Manages communication with the inferior (debugee) process. /// /// Upon construction, this class prepares and launches an inferior process @@ -39,9 +38,7 @@ MainLoop &mainloop) const override; }; - // --------------------------------------------------------------------- // NativeProcessProtocol Interface - // --------------------------------------------------------------------- Status Resume(const ResumeActionList &resume_actions) override; Status Halt() override; @@ -84,9 +81,7 @@ llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> GetAuxvData() const override; - // --------------------------------------------------------------------- // Interface used by NativeRegisterContext-derived classes. - // --------------------------------------------------------------------- static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr, int data = 0, int *result = nullptr); @@ -96,9 +91,7 @@ LazyBool m_supports_mem_region = eLazyBoolCalculate; std::vector<std::pair<MemoryRegionInfo, FileSpec>> m_mem_region_cache; - // --------------------------------------------------------------------- // Private Instance Methods - // --------------------------------------------------------------------- NativeProcessNetBSD(::pid_t pid, int terminal_fd, NativeDelegate &delegate, const ArchSpec &arch, MainLoop &mainloop);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp index d4fef63..3a9caaa 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextNetBSD.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,81 +24,8 @@ : NativeRegisterContextRegisterInfo(native_thread, reg_info_interface_p) {} -Status NativeRegisterContextNetBSD::ReadGPR() { - void *buf = GetGPRBuffer(); - if (!buf) - return Status("GPR buffer is NULL"); - - return DoReadGPR(buf); -} - -Status NativeRegisterContextNetBSD::WriteGPR() { - void *buf = GetGPRBuffer(); - if (!buf) - return Status("GPR buffer is NULL"); - - return DoWriteGPR(buf); -} - -Status NativeRegisterContextNetBSD::ReadFPR() { - void *buf = GetFPRBuffer(); - if (!buf) - return Status("FPR buffer is NULL"); - - return DoReadFPR(buf); -} - -Status NativeRegisterContextNetBSD::WriteFPR() { - void *buf = GetFPRBuffer(); - if (!buf) - return Status("FPR buffer is NULL"); - - return DoWriteFPR(buf); -} - -Status NativeRegisterContextNetBSD::ReadDBR() { - void *buf = GetDBRBuffer(); - if (!buf) - return Status("DBR buffer is NULL"); - - return DoReadDBR(buf); -} - -Status NativeRegisterContextNetBSD::WriteDBR() { - void *buf = GetDBRBuffer(); - if (!buf) - return Status("DBR buffer is NULL"); - - return DoWriteDBR(buf); -} - -Status NativeRegisterContextNetBSD::DoReadGPR(void *buf) { - return NativeProcessNetBSD::PtraceWrapper(PT_GETREGS, GetProcessPid(), buf, - m_thread.GetID()); -} - -Status NativeRegisterContextNetBSD::DoWriteGPR(void *buf) { - return NativeProcessNetBSD::PtraceWrapper(PT_SETREGS, GetProcessPid(), buf, - m_thread.GetID()); -} - -Status NativeRegisterContextNetBSD::DoReadFPR(void *buf) { - return NativeProcessNetBSD::PtraceWrapper(PT_GETFPREGS, GetProcessPid(), buf, - m_thread.GetID()); -} - -Status NativeRegisterContextNetBSD::DoWriteFPR(void *buf) { - return NativeProcessNetBSD::PtraceWrapper(PT_SETFPREGS, GetProcessPid(), buf, - m_thread.GetID()); -} - -Status NativeRegisterContextNetBSD::DoReadDBR(void *buf) { - return NativeProcessNetBSD::PtraceWrapper(PT_GETDBREGS, GetProcessPid(), buf, - m_thread.GetID()); -} - -Status NativeRegisterContextNetBSD::DoWriteDBR(void *buf) { - return NativeProcessNetBSD::PtraceWrapper(PT_SETDBREGS, GetProcessPid(), buf, +Status NativeRegisterContextNetBSD::DoRegisterSet(int ptrace_req, void *buf) { + return NativeProcessNetBSD::PtraceWrapper(ptrace_req, GetProcessPid(), buf, m_thread.GetID()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h index b81430e..f5dd0c3 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextNetBSD.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,35 +32,7 @@ NativeThreadProtocol &native_thread); protected: - virtual Status ReadGPR(); - virtual Status WriteGPR(); - - virtual Status ReadFPR(); - virtual Status WriteFPR(); - - virtual Status ReadDBR(); - virtual Status WriteDBR(); - - virtual void *GetGPRBuffer() { return nullptr; } - virtual size_t GetGPRSize() { - return GetRegisterInfoInterface().GetGPRSize(); - } - - virtual void *GetFPRBuffer() { return nullptr; } - virtual size_t GetFPRSize() { return 0; } - - virtual void *GetDBRBuffer() { return nullptr; } - virtual size_t GetDBRSize() { return 0; } - - virtual Status DoReadGPR(void *buf); - virtual Status DoWriteGPR(void *buf); - - virtual Status DoReadFPR(void *buf); - virtual Status DoWriteFPR(void *buf); - - virtual Status DoReadDBR(void *buf); - virtual Status DoWriteDBR(void *buf); - + Status DoRegisterSet(int req, void *buf); virtual NativeProcessNetBSD &GetProcess(); virtual ::pid_t GetProcessPid(); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp index 78da352..a7cd637 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextNetBSD_x86_64.cpp ---------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,8 +20,12 @@ // clang-format off #include <sys/types.h> +#include <sys/ptrace.h> #include <sys/sysctl.h> +#include <sys/uio.h> #include <x86/cpu.h> +#include <x86/cpu_extended_state.h> +#include <x86/specialreg.h> #include <elf.h> #include <err.h> #include <stdint.h> @@ -32,9 +35,7 @@ using namespace lldb_private; using namespace lldb_private::process_netbsd; -// ---------------------------------------------------------------------------- // Private namespace. -// ---------------------------------------------------------------------------- namespace { // x86 64-bit general purpose registers. @@ -93,58 +94,6 @@ }; #define REG_CONTEXT_SIZE (GetRegisterInfoInterface().GetGPRSize()) - -const int fpu_present = []() -> int { - int mib[2]; - int error; - size_t len; - int val; - - len = sizeof(val); - mib[0] = CTL_MACHDEP; - mib[1] = CPU_FPU_PRESENT; - - error = sysctl(mib, __arraycount(mib), &val, &len, NULL, 0); - if (error) - errx(EXIT_FAILURE, "sysctl"); - - return val; -}(); - -const int osfxsr = []() -> int { - int mib[2]; - int error; - size_t len; - int val; - - len = sizeof(val); - mib[0] = CTL_MACHDEP; - mib[1] = CPU_OSFXSR; - - error = sysctl(mib, __arraycount(mib), &val, &len, NULL, 0); - if (error) - errx(EXIT_FAILURE, "sysctl"); - - return val; -}(); - -const int fpu_save = []() -> int { - int mib[2]; - int error; - size_t len; - int val; - - len = sizeof(val); - mib[0] = CTL_MACHDEP; - mib[1] = CPU_FPU_SAVE; - - error = sysctl(mib, __arraycount(mib), &val, &len, NULL, 0); - if (error) - errx(EXIT_FAILURE, "sysctl"); - - return val; -}(); - } // namespace NativeRegisterContextNetBSD * @@ -153,9 +102,7 @@ return new NativeRegisterContextNetBSD_x86_64(target_arch, native_thread); } -// ---------------------------------------------------------------------------- // NativeRegisterContextNetBSD_x86_64 members. -// ---------------------------------------------------------------------------- static RegisterInfoInterface * CreateRegisterInfoInterface(const ArchSpec &target_arch) { @@ -202,9 +149,9 @@ if (reg_num <= k_last_gpr_x86_64) return GPRegSet; else if (reg_num <= k_last_fpr_x86_64) - return (fpu_present == 1 && osfxsr == 1 && fpu_save >= 1) ? FPRegSet : -1; + return FPRegSet; else if (reg_num <= k_last_avx_x86_64) - return -1; // AVX + return XStateRegSet; // AVX else if (reg_num <= k_last_mpxr_x86_64) return -1; // MPXR else if (reg_num <= k_last_mpxc_x86_64) @@ -215,37 +162,46 @@ return -1; } -int NativeRegisterContextNetBSD_x86_64::ReadRegisterSet(uint32_t set) { +Status NativeRegisterContextNetBSD_x86_64::ReadRegisterSet(uint32_t set) { switch (set) { case GPRegSet: - ReadGPR(); - return 0; + return DoRegisterSet(PT_GETREGS, &m_gpr_x86_64); case FPRegSet: - ReadFPR(); - return 0; + return DoRegisterSet(PT_GETFPREGS, &m_fpr_x86_64); case DBRegSet: - ReadDBR(); - return 0; - default: - break; + return DoRegisterSet(PT_GETDBREGS, &m_dbr_x86_64); + case XStateRegSet: +#ifdef HAVE_XSTATE + { + struct iovec iov = {&m_xstate_x86_64, sizeof(m_xstate_x86_64)}; + return DoRegisterSet(PT_GETXSTATE, &iov); + } +#else + return Status("XState is not supported by the kernel"); +#endif } - return -1; + llvm_unreachable("NativeRegisterContextNetBSD_x86_64::ReadRegisterSet"); } -int NativeRegisterContextNetBSD_x86_64::WriteRegisterSet(uint32_t set) { + +Status NativeRegisterContextNetBSD_x86_64::WriteRegisterSet(uint32_t set) { switch (set) { case GPRegSet: - WriteGPR(); - return 0; + return DoRegisterSet(PT_SETREGS, &m_gpr_x86_64); case FPRegSet: - WriteFPR(); - return 0; + return DoRegisterSet(PT_SETFPREGS, &m_fpr_x86_64); case DBRegSet: - WriteDBR(); - return 0; - default: - break; + return DoRegisterSet(PT_SETDBREGS, &m_dbr_x86_64); + case XStateRegSet: +#ifdef HAVE_XSTATE + { + struct iovec iov = {&m_xstate_x86_64, sizeof(m_xstate_x86_64)}; + return DoRegisterSet(PT_SETXSTATE, &iov); + } +#else + return Status("XState is not supported by the kernel"); +#endif } - return -1; + llvm_unreachable("NativeRegisterContextNetBSD_x86_64::WriteRegisterSet"); } Status @@ -277,13 +233,9 @@ return error; } - if (ReadRegisterSet(set) != 0) { - // This is likely an internal register for lldb use only and should not be - // directly queried. - error.SetErrorStringWithFormat( - "reading register set for register \"%s\" failed", reg_info->name); + error = ReadRegisterSet(set); + if (error.Fail()) return error; - } switch (reg) { case lldb_rax_x86_64: @@ -407,7 +359,7 @@ case lldb_mm5_x86_64: case lldb_mm6_x86_64: case lldb_mm7_x86_64: - reg_value.SetBytes(&m_fpr_x86_64.fxstate.fx_xmm[reg - lldb_mm0_x86_64], + reg_value.SetBytes(&m_fpr_x86_64.fxstate.fx_87_ac[reg - lldb_mm0_x86_64], reg_info->byte_size, endian::InlHostByteOrder()); break; case lldb_xmm0_x86_64: @@ -429,6 +381,39 @@ reg_value.SetBytes(&m_fpr_x86_64.fxstate.fx_xmm[reg - lldb_xmm0_x86_64], reg_info->byte_size, endian::InlHostByteOrder()); break; + case lldb_ymm0_x86_64: + case lldb_ymm1_x86_64: + case lldb_ymm2_x86_64: + case lldb_ymm3_x86_64: + case lldb_ymm4_x86_64: + case lldb_ymm5_x86_64: + case lldb_ymm6_x86_64: + case lldb_ymm7_x86_64: + case lldb_ymm8_x86_64: + case lldb_ymm9_x86_64: + case lldb_ymm10_x86_64: + case lldb_ymm11_x86_64: + case lldb_ymm12_x86_64: + case lldb_ymm13_x86_64: + case lldb_ymm14_x86_64: + case lldb_ymm15_x86_64: +#ifdef HAVE_XSTATE + if (!(m_xstate_x86_64.xs_rfbm & XCR0_SSE) || + !(m_xstate_x86_64.xs_rfbm & XCR0_YMM_Hi128)) { + error.SetErrorStringWithFormat("register \"%s\" not supported by CPU/kernel", + reg_info->name); + } else { + uint32_t reg_index = reg - lldb_ymm0_x86_64; + YMMReg ymm = XStateToYMM( + m_xstate_x86_64.xs_fxsave.fx_xmm[reg_index].xmm_bytes, + m_xstate_x86_64.xs_ymm_hi128.xs_ymm[reg_index].ymm_bytes); + reg_value.SetBytes(ymm.bytes, reg_info->byte_size, + endian::InlHostByteOrder()); + } +#else + error.SetErrorString("XState queries not supported by the kernel"); +#endif + break; case lldb_dr0_x86_64: case lldb_dr1_x86_64: case lldb_dr2_x86_64: @@ -473,13 +458,9 @@ return error; } - if (ReadRegisterSet(set) != 0) { - // This is likely an internal register for lldb use only and should not be - // directly queried. - error.SetErrorStringWithFormat( - "reading register set for register \"%s\" failed", reg_info->name); + error = ReadRegisterSet(set); + if (error.Fail()) return error; - } switch (reg) { case lldb_rax_x86_64: @@ -603,7 +584,7 @@ case lldb_mm5_x86_64: case lldb_mm6_x86_64: case lldb_mm7_x86_64: - ::memcpy(&m_fpr_x86_64.fxstate.fx_xmm[reg - lldb_mm0_x86_64], + ::memcpy(&m_fpr_x86_64.fxstate.fx_87_ac[reg - lldb_mm0_x86_64], reg_value.GetBytes(), reg_value.GetByteSize()); break; case lldb_xmm0_x86_64: @@ -625,6 +606,39 @@ ::memcpy(&m_fpr_x86_64.fxstate.fx_xmm[reg - lldb_xmm0_x86_64], reg_value.GetBytes(), reg_value.GetByteSize()); break; + case lldb_ymm0_x86_64: + case lldb_ymm1_x86_64: + case lldb_ymm2_x86_64: + case lldb_ymm3_x86_64: + case lldb_ymm4_x86_64: + case lldb_ymm5_x86_64: + case lldb_ymm6_x86_64: + case lldb_ymm7_x86_64: + case lldb_ymm8_x86_64: + case lldb_ymm9_x86_64: + case lldb_ymm10_x86_64: + case lldb_ymm11_x86_64: + case lldb_ymm12_x86_64: + case lldb_ymm13_x86_64: + case lldb_ymm14_x86_64: + case lldb_ymm15_x86_64: +#ifdef HAVE_XSTATE + if (!(m_xstate_x86_64.xs_rfbm & XCR0_SSE) || + !(m_xstate_x86_64.xs_rfbm & XCR0_YMM_Hi128)) { + error.SetErrorStringWithFormat("register \"%s\" not supported by CPU/kernel", + reg_info->name); + } else { + uint32_t reg_index = reg - lldb_ymm0_x86_64; + YMMReg ymm; + ::memcpy(ymm.bytes, reg_value.GetBytes(), reg_value.GetByteSize()); + YMMToXState(ymm, + m_xstate_x86_64.xs_fxsave.fx_xmm[reg_index].xmm_bytes, + m_xstate_x86_64.xs_ymm_hi128.xs_ymm[reg_index].ymm_bytes); + } +#else + error.SetErrorString("XState not supported by the kernel"); +#endif + break; case lldb_dr0_x86_64: case lldb_dr1_x86_64: case lldb_dr2_x86_64: @@ -637,10 +651,7 @@ break; } - if (WriteRegisterSet(set) != 0) - error.SetErrorStringWithFormat("failed to write register set"); - - return error; + return WriteRegisterSet(set); } Status NativeRegisterContextNetBSD_x86_64::ReadAllRegisterValues( @@ -648,25 +659,11 @@ Status error; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (!data_sp) { - error.SetErrorStringWithFormat( - "failed to allocate DataBufferHeap instance of size %" PRIu64, - REG_CONTEXT_SIZE); - return error; - } - - error = ReadGPR(); + error = ReadRegisterSet(GPRegSet); if (error.Fail()) return error; uint8_t *dst = data_sp->GetBytes(); - if (dst == nullptr) { - error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64 - " returned a null pointer", - REG_CONTEXT_SIZE); - return error; - } - ::memcpy(dst, &m_gpr_x86_64, GetRegisterInfoInterface().GetGPRSize()); dst += GetRegisterInfoInterface().GetGPRSize(); @@ -707,7 +704,7 @@ } ::memcpy(&m_gpr_x86_64, src, GetRegisterInfoInterface().GetGPRSize()); - error = WriteGPR(); + error = WriteRegisterSet(GPRegSet); if (error.Fail()) return error; src += GetRegisterInfoInterface().GetGPRSize(); @@ -767,7 +764,7 @@ uint64_t control_bits = reg_value.GetAsUInt64(); - is_vacant = !(control_bits & (1 << (2 * wp_index))); + is_vacant = !(control_bits & (1 << (2 * wp_index + 1))); return error; } @@ -806,7 +803,7 @@ return error; // for watchpoints 0, 1, 2, or 3, respectively, set bits 1, 3, 5, or 7 - uint64_t enable_bit = 1 << (2 * wp_index); + uint64_t enable_bit = 1 << (2 * wp_index + 1); // set bits 16-17, 20-21, 24-25, or 28-29 // with 0b01 for write, and 0b11 for read/write
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h index c55ddfe..0fed165 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextNetBSD_x86_64.h --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,6 +14,7 @@ // clang-format off #include <sys/param.h> #include <sys/types.h> +#include <sys/ptrace.h> #include <machine/reg.h> // clang-format on @@ -22,6 +22,10 @@ #include "Plugins/Process/Utility/RegisterContext_x86.h" #include "Plugins/Process/Utility/lldb-x86-register-enums.h" +#if defined(PT_GETXSTATE) && defined(PT_SETXSTATE) +#define HAVE_XSTATE +#endif + namespace lldb_private { namespace process_netbsd { @@ -67,24 +71,22 @@ uint32_t NumSupportedHardwareWatchpoints() override; -protected: - void *GetGPRBuffer() override { return &m_gpr_x86_64; } - void *GetFPRBuffer() override { return &m_fpr_x86_64; } - void *GetDBRBuffer() override { return &m_dbr_x86_64; } - private: // Private member types. - enum { GPRegSet, FPRegSet, DBRegSet }; + enum { GPRegSet, FPRegSet, DBRegSet, XStateRegSet }; // Private member variables. struct reg m_gpr_x86_64; struct fpreg m_fpr_x86_64; struct dbreg m_dbr_x86_64; +#ifdef HAVE_XSTATE + struct xstate m_xstate_x86_64; +#endif int GetSetForNativeRegNum(int reg_num) const; - int ReadRegisterSet(uint32_t set); - int WriteRegisterSet(uint32_t set); + Status ReadRegisterSet(uint32_t set); + Status WriteRegisterSet(uint32_t set); }; } // namespace process_netbsd
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp index 6f5d112..e25975c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp
@@ -1,9 +1,8 @@ //===-- NativeThreadNetBSD.cpp -------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h index 7242624..015d899 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h +++ b/src/llvm-project/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h
@@ -1,9 +1,8 @@ //===-- NativeThreadNetBSD.h ---------------------------------- -*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -27,9 +26,7 @@ public: NativeThreadNetBSD(NativeProcessNetBSD &process, lldb::tid_t tid); - // --------------------------------------------------------------------- // NativeThreadProtocol Interface - // --------------------------------------------------------------------- std::string GetName() override; lldb::StateType GetState() override; @@ -49,9 +46,7 @@ Status RemoveHardwareBreakpoint(lldb::addr_t addr) override; private: - // --------------------------------------------------------------------- // Interface for friend classes - // --------------------------------------------------------------------- void SetStoppedBySignal(uint32_t signo, const siginfo_t *info = nullptr); void SetStoppedByBreakpoint(); @@ -62,9 +57,7 @@ void SetRunning(); void SetStepping(); - // --------------------------------------------------------------------- // Member Variables - // --------------------------------------------------------------------- lldb::StateType m_state; ThreadStopInfo m_stop_info; std::unique_ptr<NativeRegisterContext> m_reg_context_up;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Process/POSIX/CMakeLists.txt index f058e01..fd74f81 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/POSIX/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/CMakeLists.txt
@@ -1,10 +1,12 @@ add_lldb_library(lldbPluginProcessPOSIX PLUGIN CrashReason.cpp + NativeProcessELF.cpp ProcessMessage.cpp ProcessPOSIXLog.cpp LINK_LIBS - lldbInterpreter + lldbPluginProcessUtility + lldbUtility LINK_COMPONENTS Support )
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.cpp b/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.cpp index 4b24d31..70c2687 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.cpp
@@ -1,9 +1,8 @@ //===-- CrashReason.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.h b/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.h index 57abe47..9b4784a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.h +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/CrashReason.h
@@ -1,9 +1,8 @@ //===-- CrashReason.h -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/NativeProcessELF.cpp b/src/llvm-project/lldb/source/Plugins/Process/POSIX/NativeProcessELF.cpp new file mode 100644 index 0000000..559b16c --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/NativeProcessELF.cpp
@@ -0,0 +1,110 @@ +//===-- NativeProcessELF.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 "NativeProcessELF.h" + +#include "lldb/Utility/DataExtractor.h" + +namespace lldb_private { + +llvm::Optional<uint64_t> +NativeProcessELF::GetAuxValue(enum AuxVector::EntryType type) { + if (m_aux_vector == nullptr) { + auto buffer_or_error = GetAuxvData(); + if (!buffer_or_error) + return llvm::None; + DataExtractor auxv_data(buffer_or_error.get()->getBufferStart(), + buffer_or_error.get()->getBufferSize(), + GetByteOrder(), GetAddressByteSize()); + m_aux_vector = llvm::make_unique<AuxVector>(auxv_data); + } + + return m_aux_vector->GetAuxValue(type); +} + +lldb::addr_t NativeProcessELF::GetSharedLibraryInfoAddress() { + if (!m_shared_library_info_addr.hasValue()) { + if (GetAddressByteSize() == 8) + m_shared_library_info_addr = + GetELFImageInfoAddress<llvm::ELF::Elf64_Ehdr, llvm::ELF::Elf64_Phdr, + llvm::ELF::Elf64_Dyn>(); + else + m_shared_library_info_addr = + GetELFImageInfoAddress<llvm::ELF::Elf32_Ehdr, llvm::ELF::Elf32_Phdr, + llvm::ELF::Elf32_Dyn>(); + } + + return m_shared_library_info_addr.getValue(); +} + +template <typename ELF_EHDR, typename ELF_PHDR, typename ELF_DYN> +lldb::addr_t NativeProcessELF::GetELFImageInfoAddress() { + llvm::Optional<uint64_t> maybe_phdr_addr = + GetAuxValue(AuxVector::AUXV_AT_PHDR); + llvm::Optional<uint64_t> maybe_phdr_entry_size = + GetAuxValue(AuxVector::AUXV_AT_PHENT); + llvm::Optional<uint64_t> maybe_phdr_num_entries = + GetAuxValue(AuxVector::AUXV_AT_PHNUM); + if (!maybe_phdr_addr || !maybe_phdr_entry_size || !maybe_phdr_num_entries) + return LLDB_INVALID_ADDRESS; + lldb::addr_t phdr_addr = *maybe_phdr_addr; + size_t phdr_entry_size = *maybe_phdr_entry_size; + size_t phdr_num_entries = *maybe_phdr_num_entries; + + // Find the PT_DYNAMIC segment (.dynamic section) in the program header and + // what the load bias by calculating the difference of the program header + // load address and its virtual address. + lldb::offset_t load_bias; + bool found_load_bias = false; + lldb::addr_t dynamic_section_addr = 0; + uint64_t dynamic_section_size = 0; + bool found_dynamic_section = false; + ELF_PHDR phdr_entry; + for (size_t i = 0; i < phdr_num_entries; i++) { + size_t bytes_read; + auto error = ReadMemory(phdr_addr + i * phdr_entry_size, &phdr_entry, + sizeof(phdr_entry), bytes_read); + if (!error.Success()) + return LLDB_INVALID_ADDRESS; + if (phdr_entry.p_type == llvm::ELF::PT_PHDR) { + load_bias = phdr_addr - phdr_entry.p_vaddr; + found_load_bias = true; + } + + if (phdr_entry.p_type == llvm::ELF::PT_DYNAMIC) { + dynamic_section_addr = phdr_entry.p_vaddr; + dynamic_section_size = phdr_entry.p_memsz; + found_dynamic_section = true; + } + } + + if (!found_load_bias || !found_dynamic_section) + return LLDB_INVALID_ADDRESS; + + // Find the DT_DEBUG entry in the .dynamic section + dynamic_section_addr += load_bias; + ELF_DYN dynamic_entry; + size_t dynamic_num_entries = dynamic_section_size / sizeof(dynamic_entry); + for (size_t i = 0; i < dynamic_num_entries; i++) { + size_t bytes_read; + auto error = ReadMemory(dynamic_section_addr + i * sizeof(dynamic_entry), + &dynamic_entry, sizeof(dynamic_entry), bytes_read); + if (!error.Success()) + return LLDB_INVALID_ADDRESS; + // Return the &DT_DEBUG->d_ptr which points to r_debug which contains the + // link_map. + if (dynamic_entry.d_tag == llvm::ELF::DT_DEBUG) { + return dynamic_section_addr + i * sizeof(dynamic_entry) + + sizeof(dynamic_entry.d_tag); + } + } + + return LLDB_INVALID_ADDRESS; +} + +} // namespace lldb_private \ No newline at end of file
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/NativeProcessELF.h b/src/llvm-project/lldb/source/Plugins/Process/POSIX/NativeProcessELF.h new file mode 100644 index 0000000..84dc8d0 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/NativeProcessELF.h
@@ -0,0 +1,46 @@ +//===-- NativeProcessELF.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 liblldb_NativeProcessELF_H_ +#define liblldb_NativeProcessELF_H_ + +#include "Plugins/Process/Utility/AuxVector.h" +#include "lldb/Host/common/NativeProcessProtocol.h" +#include "llvm/BinaryFormat/ELF.h" + +namespace lldb_private { + +/// \class NativeProcessELF +/// Abstract class that extends \a NativeProcessProtocol with ELF specific +/// logic. Meant to be subclassed by ELF based NativeProcess* implementations. +class NativeProcessELF : public NativeProcessProtocol { + using NativeProcessProtocol::NativeProcessProtocol; + +protected: + template <typename T> struct ELFLinkMap { + T l_addr; + T l_name; + T l_ld; + T l_next; + T l_prev; + }; + + llvm::Optional<uint64_t> GetAuxValue(enum AuxVector::EntryType type); + + lldb::addr_t GetSharedLibraryInfoAddress() override; + + template <typename ELF_EHDR, typename ELF_PHDR, typename ELF_DYN> + lldb::addr_t GetELFImageInfoAddress(); + + std::unique_ptr<AuxVector> m_aux_vector; + llvm::Optional<lldb::addr_t> m_shared_library_info_addr; +}; + +} // namespace lldb_private + +#endif \ No newline at end of file
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.cpp b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.cpp index 48f2a78..aa84491 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.cpp
@@ -1,9 +1,8 @@ //===-- ProcessMessage.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,7 @@ chcar str[8]; sprintf(str, "%d", reason); #else - const char *str = NULL; + const char *str = nullptr; switch (kind) { case eInvalidMessage:
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.h b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.h index 3c596ca..d9c10ca 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.h +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessMessage.h
@@ -1,9 +1,8 @@ //===-- ProcessMessage.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -45,33 +44,33 @@ lldb::tid_t GetTID() const { return m_tid; } - /// Indicates that the process @p pid has successfully attached. + /// Indicates that the process \p pid has successfully attached. static ProcessMessage Attach(lldb::pid_t pid) { return ProcessMessage(pid, eAttachMessage); } - /// Indicates that the thread @p tid is about to exit with status @p status. + /// Indicates that the thread \p tid is about to exit with status \p status. static ProcessMessage Limbo(lldb::tid_t tid, int status) { return ProcessMessage(tid, eLimboMessage, status); } - /// Indicates that the thread @p tid had the signal @p signum delivered. + /// Indicates that the thread \p tid had the signal \p signum delivered. static ProcessMessage Signal(lldb::tid_t tid, int signum) { return ProcessMessage(tid, eSignalMessage, signum); } - /// Indicates that a signal @p signum generated by the debugging process was - /// delivered to the thread @p tid. + /// Indicates that a signal \p signum generated by the debugging process was + /// delivered to the thread \p tid. static ProcessMessage SignalDelivered(lldb::tid_t tid, int signum) { return ProcessMessage(tid, eSignalDeliveredMessage, signum); } - /// Indicates that the thread @p tid encountered a trace point. + /// Indicates that the thread \p tid encountered a trace point. static ProcessMessage Trace(lldb::tid_t tid) { return ProcessMessage(tid, eTraceMessage); } - /// Indicates that the thread @p tid encountered a break point. + /// Indicates that the thread \p tid encountered a break point. static ProcessMessage Break(lldb::tid_t tid) { return ProcessMessage(tid, eBreakpointMessage); } @@ -80,7 +79,7 @@ return ProcessMessage(tid, eWatchpointMessage, 0, wp_addr); } - /// Indicates that the thread @p tid crashed. + /// Indicates that the thread \p tid crashed. static ProcessMessage Crash(lldb::pid_t pid, CrashReason reason, int signo, lldb::addr_t fault_addr) { ProcessMessage message(pid, eCrashMessage, signo, fault_addr); @@ -88,18 +87,18 @@ return message; } - /// Indicates that the thread @p child_tid was spawned. + /// Indicates that the thread \p child_tid was spawned. static ProcessMessage NewThread(lldb::tid_t parent_tid, lldb::tid_t child_tid) { return ProcessMessage(parent_tid, eNewThreadMessage, child_tid); } - /// Indicates that the thread @p tid is about to exit with status @p status. + /// Indicates that the thread \p tid is about to exit with status \p status. static ProcessMessage Exit(lldb::tid_t tid, int status) { return ProcessMessage(tid, eExitMessage, status); } - /// Indicates that the thread @p pid has exec'd. + /// Indicates that the thread \p pid has exec'd. static ProcessMessage Exec(lldb::tid_t tid) { return ProcessMessage(tid, eExecMessage); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.cpp b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.cpp index f1beb0f..a17558b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.cpp
@@ -1,10 +1,9 @@ //===-- ProcessPOSIXLog.cpp ---------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.h b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.h index 3ac798b..c0147c4 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.h +++ b/src/llvm-project/lldb/source/Plugins/Process/POSIX/ProcessPOSIXLog.h
@@ -1,10 +1,9 @@ //===-- ProcessPOSIXLog.h -----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMDefines.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMDefines.h index 84c2cf1..1f7eb54 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMDefines.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMDefines.h
@@ -1,15 +1,16 @@ -//===-- lldb_ARMDefines.h ---------------------------------------*- C++ -*-===// +//===-- ARMDefines.h --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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_ARMDefines_h_ #define lldb_ARMDefines_h_ +#include "llvm/Support/ErrorHandling.h" + #include <cassert> #include <cstdint> @@ -18,14 +19,14 @@ namespace lldb_private { // ARM shifter types -typedef enum { +enum ARM_ShifterType { SRType_LSL, SRType_LSR, SRType_ASR, SRType_ROR, SRType_RRX, SRType_Invalid -} ARM_ShifterType; +}; // ARM conditions // Meaning (integer) Meaning (floating-point) // Condition flags @@ -69,8 +70,6 @@ static inline const char *ARMCondCodeToString(uint32_t CC) { switch (CC) { - default: - assert(0 && "Unknown condition code"); case COND_EQ: return "eq"; case COND_NE: @@ -102,6 +101,7 @@ case COND_AL: return "al"; } + llvm_unreachable("Unknown condition code"); } static inline bool ARMConditionPassed(const uint32_t condition,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMUtils.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMUtils.h index 2c14dc9..d860348 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMUtils.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/ARMUtils.h
@@ -1,9 +1,8 @@ //===-- ARMUtils.h ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/AuxVector.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/AuxVector.cpp new file mode 100644 index 0000000..aab164f --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/AuxVector.cpp
@@ -0,0 +1,96 @@ +//===-- AuxVector.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 "AuxVector.h" + +AuxVector::AuxVector(const lldb_private::DataExtractor &data) { + ParseAuxv(data); +} + +void AuxVector::ParseAuxv(const lldb_private::DataExtractor &data) { + lldb::offset_t offset = 0; + const size_t value_type_size = data.GetAddressByteSize() * 2; + while (data.ValidOffsetForDataOfSize(offset, value_type_size)) { + // We're not reading an address but an int that could be 32 or 64 bit + // depending on the address size, which is what GetAddress does. + const uint64_t type = data.GetAddress(&offset); + const uint64_t value = data.GetAddress(&offset); + if (type == AUXV_AT_NULL) + break; + if (type == AUXV_AT_IGNORE) + continue; + + m_auxv_entries[type] = value; + } +} + +llvm::Optional<uint64_t> +AuxVector::GetAuxValue(enum EntryType entry_type) const { + auto it = m_auxv_entries.find(static_cast<uint64_t>(entry_type)); + if (it != m_auxv_entries.end()) + return it->second; + return llvm::None; +} + +void AuxVector::DumpToLog(lldb_private::Log *log) const { + if (!log) + return; + + log->PutCString("AuxVector: "); + for (auto entry : m_auxv_entries) { + log->Printf(" %s [%" PRIu64 "]: %" PRIx64, + GetEntryName(static_cast<EntryType>(entry.first)), entry.first, + entry.second); + } +} + +const char *AuxVector::GetEntryName(EntryType type) const { + const char *name = "AT_???"; + +#define ENTRY_NAME(_type) \ + _type: \ + name = &#_type[5] + switch (type) { + case ENTRY_NAME(AUXV_AT_NULL); break; + case ENTRY_NAME(AUXV_AT_IGNORE); break; + case ENTRY_NAME(AUXV_AT_EXECFD); break; + case ENTRY_NAME(AUXV_AT_PHDR); break; + case ENTRY_NAME(AUXV_AT_PHENT); break; + case ENTRY_NAME(AUXV_AT_PHNUM); break; + case ENTRY_NAME(AUXV_AT_PAGESZ); break; + case ENTRY_NAME(AUXV_AT_BASE); break; + case ENTRY_NAME(AUXV_AT_FLAGS); break; + case ENTRY_NAME(AUXV_AT_ENTRY); break; + case ENTRY_NAME(AUXV_AT_NOTELF); break; + case ENTRY_NAME(AUXV_AT_UID); break; + case ENTRY_NAME(AUXV_AT_EUID); break; + case ENTRY_NAME(AUXV_AT_GID); break; + case ENTRY_NAME(AUXV_AT_EGID); break; + case ENTRY_NAME(AUXV_AT_CLKTCK); break; + case ENTRY_NAME(AUXV_AT_PLATFORM); break; + case ENTRY_NAME(AUXV_AT_HWCAP); break; + case ENTRY_NAME(AUXV_AT_FPUCW); break; + case ENTRY_NAME(AUXV_AT_DCACHEBSIZE); break; + case ENTRY_NAME(AUXV_AT_ICACHEBSIZE); break; + case ENTRY_NAME(AUXV_AT_UCACHEBSIZE); break; + case ENTRY_NAME(AUXV_AT_IGNOREPPC); break; + case ENTRY_NAME(AUXV_AT_SECURE); break; + case ENTRY_NAME(AUXV_AT_BASE_PLATFORM); break; + case ENTRY_NAME(AUXV_AT_RANDOM); break; + case ENTRY_NAME(AUXV_AT_EXECFN); break; + case ENTRY_NAME(AUXV_AT_SYSINFO); break; + case ENTRY_NAME(AUXV_AT_SYSINFO_EHDR); break; + case ENTRY_NAME(AUXV_AT_L1I_CACHESHAPE); break; + case ENTRY_NAME(AUXV_AT_L1D_CACHESHAPE); break; + case ENTRY_NAME(AUXV_AT_L2_CACHESHAPE); break; + case ENTRY_NAME(AUXV_AT_L3_CACHESHAPE); break; + } +#undef ENTRY_NAME + + return name; +}
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/AuxVector.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/AuxVector.h new file mode 100644 index 0000000..c16be68 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/AuxVector.h
@@ -0,0 +1,73 @@ +//===-- AuxVector.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 liblldb_AuxVector_H_ +#define liblldb_AuxVector_H_ + +#include "lldb/Utility/DataExtractor.h" +#include "lldb/Utility/Log.h" +#include <unordered_map> + +class AuxVector { + +public: + AuxVector(const lldb_private::DataExtractor &data); + + /// Constants describing the type of entry. + /// On Linux, running "LD_SHOW_AUXV=1 ./executable" will spew AUX + /// information. Added AUXV prefix to avoid potential conflicts with system- + /// defined macros + enum EntryType { + AUXV_AT_NULL = 0, ///< End of auxv. + AUXV_AT_IGNORE = 1, ///< Ignore entry. + AUXV_AT_EXECFD = 2, ///< File descriptor of program. + AUXV_AT_PHDR = 3, ///< Program headers. + AUXV_AT_PHENT = 4, ///< Size of program header. + AUXV_AT_PHNUM = 5, ///< Number of program headers. + AUXV_AT_PAGESZ = 6, ///< Page size. + AUXV_AT_BASE = 7, ///< Interpreter base address. + AUXV_AT_FLAGS = 8, ///< Flags. + AUXV_AT_ENTRY = 9, ///< Program entry point. + AUXV_AT_NOTELF = 10, ///< Set if program is not an ELF. + AUXV_AT_UID = 11, ///< UID. + AUXV_AT_EUID = 12, ///< Effective UID. + AUXV_AT_GID = 13, ///< GID. + AUXV_AT_EGID = 14, ///< Effective GID. + AUXV_AT_CLKTCK = 17, ///< Clock frequency (e.g. times(2)). + AUXV_AT_PLATFORM = 15, ///< String identifying platform. + AUXV_AT_HWCAP = + 16, ///< Machine dependent hints about processor capabilities. + AUXV_AT_FPUCW = 18, ///< Used FPU control word. + AUXV_AT_DCACHEBSIZE = 19, ///< Data cache block size. + AUXV_AT_ICACHEBSIZE = 20, ///< Instruction cache block size. + AUXV_AT_UCACHEBSIZE = 21, ///< Unified cache block size. + AUXV_AT_IGNOREPPC = 22, ///< Entry should be ignored. + AUXV_AT_SECURE = 23, ///< Boolean, was exec setuid-like? + AUXV_AT_BASE_PLATFORM = 24, ///< String identifying real platforms. + AUXV_AT_RANDOM = 25, ///< Address of 16 random bytes. + AUXV_AT_EXECFN = 31, ///< Filename of executable. + AUXV_AT_SYSINFO = 32, ///< Pointer to the global system page used for system + /// calls and other nice things. + AUXV_AT_SYSINFO_EHDR = 33, + AUXV_AT_L1I_CACHESHAPE = 34, ///< Shapes of the caches. + AUXV_AT_L1D_CACHESHAPE = 35, + AUXV_AT_L2_CACHESHAPE = 36, + AUXV_AT_L3_CACHESHAPE = 37, + }; + + llvm::Optional<uint64_t> GetAuxValue(enum EntryType entry_type) const; + void DumpToLog(lldb_private::Log *log) const; + const char *GetEntryName(EntryType type) const; + +private: + void ParseAuxv(const lldb_private::DataExtractor &data); + + std::unordered_map<uint64_t, uint64_t> m_auxv_entries; +}; + +#endif
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Process/Utility/CMakeLists.txt index e36ce4d..9ed2d02 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/CMakeLists.txt
@@ -1,4 +1,5 @@ add_lldb_library(lldbPluginProcessUtility PLUGIN + AuxVector.cpp DynamicRegisterInfo.cpp FreeBSDSignals.cpp GDBRemoteSignals.cpp
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp index dcbf474..1afe4d9 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp
@@ -1,9 +1,8 @@ //===-- DynamicRegisterInfo.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -68,7 +67,7 @@ for (uint32_t i = 0; i < num_sets; ++i) { ConstString set_name; if (sets->GetItemAtIndexAsString(i, set_name) && !set_name.IsEmpty()) { - m_sets.push_back({ set_name.AsCString(), NULL, 0, NULL }); + m_sets.push_back({set_name.AsCString(), nullptr, 0, nullptr}); } else { Clear(); printf("error: register sets must have valid names\n"); @@ -303,7 +302,7 @@ llvm::StringRef format_str; if (reg_info_dict->GetValueForKeyAsString("format", format_str, nullptr)) { if (OptionArgParser::ToFormat(format_str.str().c_str(), reg_info.format, - NULL) + nullptr) .Fail()) { Clear(); printf("error: invalid 'format' value in register dictionary\n"); @@ -415,7 +414,7 @@ const uint32_t reg_num = m_regs.size(); reg_info.name = reg_name.AsCString(); assert(reg_info.name); - reg_info.alt_name = reg_alt_name.AsCString(NULL); + reg_info.alt_name = reg_alt_name.AsCString(nullptr); uint32_t i; if (reg_info.value_regs) { for (i = 0; reg_info.value_regs[i] != LLDB_INVALID_REGNUM; ++i) @@ -481,7 +480,7 @@ if (m_value_regs_map.find(i) != m_value_regs_map.end()) m_regs[i].value_regs = m_value_regs_map[i].data(); else - m_regs[i].value_regs = NULL; + m_regs[i].value_regs = nullptr; } // Expand all invalidation dependencies @@ -530,7 +529,7 @@ if (m_invalidate_regs_map.find(i) != m_invalidate_regs_map.end()) m_regs[i].invalidate_regs = m_invalidate_regs_map[i].data(); else - m_regs[i].invalidate_regs = NULL; + m_regs[i].invalidate_regs = nullptr; } // Check if we need to automatically set the generic registers in case they @@ -640,19 +639,19 @@ DynamicRegisterInfo::GetRegisterInfoAtIndex(uint32_t i) const { if (i < m_regs.size()) return &m_regs[i]; - return NULL; + return nullptr; } RegisterInfo *DynamicRegisterInfo::GetRegisterInfoAtIndex(uint32_t i) { if (i < m_regs.size()) return &m_regs[i]; - return NULL; + return nullptr; } const RegisterSet *DynamicRegisterInfo::GetRegisterSet(uint32_t i) const { if (i < m_sets.size()) return &m_sets[i]; - return NULL; + return nullptr; } uint32_t DynamicRegisterInfo::GetRegisterSetIndexByName(ConstString &set_name, @@ -665,7 +664,7 @@ m_set_names.push_back(set_name); m_set_reg_nums.resize(m_set_reg_nums.size() + 1); - RegisterSet new_set = {set_name.AsCString(), NULL, 0, NULL}; + RegisterSet new_set = {set_name.AsCString(), nullptr, 0, nullptr}; m_sets.push_back(new_set); return m_sets.size() - 1; } @@ -747,7 +746,7 @@ } const lldb_private::RegisterInfo *DynamicRegisterInfo::GetRegisterInfo( - const lldb_private::ConstString ®_name) const { + lldb_private::ConstString reg_name) const { for (auto ®_info : m_regs) { // We can use pointer comparison since we used a ConstString to set the // "name" member in AddRegister() @@ -755,5 +754,5 @@ return ®_info; } } - return NULL; + return nullptr; }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h index 68f3902..aacf547 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h
@@ -1,9 +1,8 @@ //===-- DynamicRegisterInfo.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -65,9 +64,7 @@ void Clear(); protected: - //------------------------------------------------------------------ // Classes that inherit from DynamicRegisterInfo can see and modify these - //------------------------------------------------------------------ typedef std::vector<lldb_private::RegisterInfo> reg_collection; typedef std::vector<lldb_private::RegisterSet> set_collection; typedef std::vector<uint32_t> reg_num_collection; @@ -78,7 +75,7 @@ typedef std::map<uint32_t, dwarf_opcode> dynamic_reg_size_map; const lldb_private::RegisterInfo * - GetRegisterInfo(const lldb_private::ConstString ®_name) const; + GetRegisterInfo(lldb_private::ConstString reg_name) const; void MoveFrom(DynamicRegisterInfo &&info);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.cpp index 0b56b60..9f63a59 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.cpp
@@ -1,9 +1,8 @@ //===-- FreeBSDSignals.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.h index 174025c..75462f3 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/FreeBSDSignals.h
@@ -1,9 +1,8 @@ //===-- FreeBSDSignals.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.cpp index cc0537c..ed35273 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteSignals.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.h index 79d8ec3..a02dd06 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/GDBRemoteSignals.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteSignals.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.cpp index 4983dcd..3cb5831 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.cpp
@@ -1,15 +1,15 @@ //===-- HistoryThread.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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-private.h" #include "Plugins/Process/Utility/HistoryThread.h" + #include "Plugins/Process/Utility/HistoryUnwind.h" #include "Plugins/Process/Utility/RegisterContextHistory.h" @@ -17,20 +17,20 @@ #include "lldb/Target/StackFrameList.h" #include "lldb/Utility/Log.h" +#include <memory> + using namespace lldb; using namespace lldb_private; // Constructor HistoryThread::HistoryThread(lldb_private::Process &process, lldb::tid_t tid, - std::vector<lldb::addr_t> pcs, uint32_t stop_id, - bool stop_id_is_valid) + std::vector<lldb::addr_t> pcs) : Thread(process, tid, true), m_framelist_mutex(), m_framelist(), - m_pcs(pcs), m_stop_id(stop_id), m_stop_id_is_valid(stop_id_is_valid), - m_extended_unwind_token(LLDB_INVALID_ADDRESS), m_queue_name(), + m_pcs(pcs), m_extended_unwind_token(LLDB_INVALID_ADDRESS), m_queue_name(), m_thread_name(), m_originating_unique_thread_id(tid), m_queue_id(LLDB_INVALID_QUEUE_ID) { - m_unwinder_ap.reset(new HistoryUnwind(*this, pcs, stop_id_is_valid)); + m_unwinder_up.reset(new HistoryUnwind(*this, pcs)); Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); if (log) log->Printf("%p HistoryThread::HistoryThread", static_cast<void *>(this)); @@ -49,23 +49,24 @@ lldb::RegisterContextSP HistoryThread::GetRegisterContext() { RegisterContextSP rctx; if (m_pcs.size() > 0) { - rctx.reset(new RegisterContextHistory( - *this, 0, GetProcess()->GetAddressByteSize(), m_pcs[0])); + rctx = std::make_shared<RegisterContextHistory>( + *this, 0, GetProcess()->GetAddressByteSize(), m_pcs[0]); } return rctx; } lldb::RegisterContextSP HistoryThread::CreateRegisterContextForFrame(StackFrame *frame) { - return m_unwinder_ap->CreateRegisterContextForFrame(frame); + return m_unwinder_up->CreateRegisterContextForFrame(frame); } lldb::StackFrameListSP HistoryThread::GetStackFrameList() { // FIXME do not throw away the lock after we acquire it.. std::unique_lock<std::mutex> lock(m_framelist_mutex); lock.unlock(); - if (m_framelist.get() == NULL) { - m_framelist.reset(new StackFrameList(*this, StackFrameListSP(), true)); + if (m_framelist.get() == nullptr) { + m_framelist = + std::make_shared<StackFrameList>(*this, StackFrameListSP(), true); } return m_framelist;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.h index dc24922..1e26586 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryThread.h
@@ -1,9 +1,8 @@ //===-- HistoryThread.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,22 +22,18 @@ namespace lldb_private { -//---------------------------------------------------------------------- -/// @class HistoryThread HistoryThread.h "HistoryThread.h" +/// \class HistoryThread HistoryThread.h "HistoryThread.h" /// A thread object representing a backtrace from a previous point in the /// process execution /// /// This subclass of Thread is used to provide a backtrace from earlier in -/// process execution. It is given a backtrace list of pc addresses and -/// optionally a stop_id of when those pc addresses were collected, and it +/// process execution. It is given a backtrace list of pc addresses and it /// will create stack frames for them. -//---------------------------------------------------------------------- class HistoryThread : public lldb_private::Thread { public: HistoryThread(lldb_private::Process &process, lldb::tid_t tid, - std::vector<lldb::addr_t> pcs, uint32_t stop_id, - bool stop_id_is_valid); + std::vector<lldb::addr_t> pcs); ~HistoryThread() override; @@ -83,8 +78,6 @@ mutable std::mutex m_framelist_mutex; lldb::StackFrameListSP m_framelist; std::vector<lldb::addr_t> m_pcs; - uint32_t m_stop_id; - bool m_stop_id_is_valid; uint64_t m_extended_unwind_token; std::string m_queue_name;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.cpp index 4f0ecba..7d473bf 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.cpp
@@ -1,9 +1,8 @@ //===-- HistoryUnwind.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,14 +16,15 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" +#include <memory> + using namespace lldb; using namespace lldb_private; // Constructor -HistoryUnwind::HistoryUnwind(Thread &thread, std::vector<lldb::addr_t> pcs, - bool stop_id_is_valid) - : Unwind(thread), m_pcs(pcs), m_stop_id_is_valid(stop_id_is_valid) {} +HistoryUnwind::HistoryUnwind(Thread &thread, std::vector<lldb::addr_t> pcs) + : Unwind(thread), m_pcs(pcs) {} // Destructor @@ -33,7 +33,6 @@ void HistoryUnwind::DoClear() { std::lock_guard<std::recursive_mutex> guard(m_unwind_mutex); m_pcs.clear(); - m_stop_id_is_valid = false; } lldb::RegisterContextSP @@ -43,9 +42,9 @@ addr_t pc = frame->GetFrameCodeAddress().GetLoadAddress( &frame->GetThread()->GetProcess()->GetTarget()); if (pc != LLDB_INVALID_ADDRESS) { - rctx.reset(new RegisterContextHistory( + rctx = std::make_shared<RegisterContextHistory>( *frame->GetThread().get(), frame->GetConcreteFrameIndex(), - frame->GetThread()->GetProcess()->GetAddressByteSize(), pc)); + frame->GetThread()->GetProcess()->GetAddressByteSize(), pc); } } return rctx;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.h index 2cbfb68..6c4522e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/HistoryUnwind.h
@@ -1,9 +1,8 @@ //===-- HistoryUnwind.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,8 +18,7 @@ class HistoryUnwind : public lldb_private::Unwind { public: - HistoryUnwind(Thread &thread, std::vector<lldb::addr_t> pcs, - bool stop_id_is_valid); + HistoryUnwind(Thread &thread, std::vector<lldb::addr_t> pcs); ~HistoryUnwind() override; @@ -36,7 +34,6 @@ private: std::vector<lldb::addr_t> m_pcs; - bool m_stop_id_is_valid; }; } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.cpp index 5c51a03..9beaf2f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.cpp
@@ -1,9 +1,8 @@ //===-- InferiorCallPOSIX.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -39,7 +38,7 @@ unsigned flags, addr_t fd, addr_t offset) { Thread *thread = process->GetThreadList().GetExpressionExecutionThread().get(); - if (thread == NULL) + if (thread == nullptr) return false; const bool append = true; @@ -61,7 +60,7 @@ options.SetIgnoreBreakpoints(true); options.SetTryAllThreads(true); options.SetDebug(false); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(process->GetUtilityExpressionTimeout()); options.SetTrapExceptions(false); addr_t prot_arg; @@ -127,7 +126,7 @@ addr_t length) { Thread *thread = process->GetThreadList().GetExpressionExecutionThread().get(); - if (thread == NULL) + if (thread == nullptr) return false; const bool append = true; @@ -149,7 +148,7 @@ options.SetIgnoreBreakpoints(true); options.SetTryAllThreads(true); options.SetDebug(false); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(process->GetUtilityExpressionTimeout()); options.SetTrapExceptions(false); AddressRange munmap_range; @@ -189,7 +188,7 @@ addr_t &returned_func, bool trap_exceptions) { Thread *thread = process->GetThreadList().GetExpressionExecutionThread().get(); - if (thread == NULL || address == NULL) + if (thread == nullptr || address == nullptr) return false; EvaluateExpressionOptions options; @@ -198,7 +197,7 @@ options.SetIgnoreBreakpoints(true); options.SetTryAllThreads(true); options.SetDebug(false); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(process->GetUtilityExpressionTimeout()); options.SetTrapExceptions(trap_exceptions); ClangASTContext *clang_ast_context =
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.h index 07bde5b..0431680 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.h
@@ -1,9 +1,8 @@ //===-- InferiorCallPOSIX.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/InstructionUtils.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/InstructionUtils.h index 186d525..f74933e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/InstructionUtils.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/InstructionUtils.h
@@ -1,9 +1,8 @@ //===-- InstructionUtils.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.cpp index d45bf6d..1ba432a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.cpp
@@ -1,9 +1,8 @@ //===-- LinuxProcMaps.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.h index e6eabb2..e1f0e48 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxProcMaps.h
@@ -1,9 +1,8 @@ //===-- LinuxProcMaps.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.cpp index 6f1f67a..bef47cd 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.cpp
@@ -1,9 +1,8 @@ //===-- LinuxSignals.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.h index f93a9d2..7ad8cfc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/LinuxSignals.h
@@ -1,9 +1,8 @@ //===-- LinuxSignals.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.cpp index b6f3b34..d8e5426 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.cpp
@@ -1,10 +1,9 @@ //===-- MipsLinuxSignals.cpp ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.h index 2796f6b..b5e3ed8 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/MipsLinuxSignals.h
@@ -1,10 +1,9 @@ //===-- MipsLinuxSignals.h ------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.cpp index 3a9d497..be61cfd 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.cpp
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextRegisterInfo.cpp -------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.h index 8f2e440..b285c47 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/NativeRegisterContextRegisterInfo.h
@@ -1,9 +1,8 @@ //===-- NativeRegisterContextRegisterInfo.h ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.cpp index a4baab9..29967de 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.cpp
@@ -1,9 +1,8 @@ //===-- NetBSDSignals.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.h index 7bb57fa..bf7399a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/NetBSDSignals.h
@@ -1,9 +1,8 @@ //===-- NetBSDSignals.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwinConstants.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwinConstants.h index ff57464..ef40162 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwinConstants.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwinConstants.h
@@ -1,9 +1,8 @@ //===-- RegisterContextDarwinConstants.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.cpp index 9ad896a..e804a4d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextDarwin_arm.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,6 +19,8 @@ #include "Plugins/Process/Utility/InstructionUtils.h" +#include <memory> + // Support building against older versions of LLVM, this macro was added // recently. #ifndef LLVM_EXTENSION @@ -197,7 +198,7 @@ // =============== =============== ========================= // ===================== ============= {"r0", - NULL, + nullptr, 4, GPR_OFFSET(0), eEncodingUint, @@ -208,7 +209,7 @@ nullptr, 0}, {"r1", - NULL, + nullptr, 4, GPR_OFFSET(1), eEncodingUint, @@ -219,7 +220,7 @@ nullptr, 0}, {"r2", - NULL, + nullptr, 4, GPR_OFFSET(2), eEncodingUint, @@ -230,7 +231,7 @@ nullptr, 0}, {"r3", - NULL, + nullptr, 4, GPR_OFFSET(3), eEncodingUint, @@ -241,7 +242,7 @@ nullptr, 0}, {"r4", - NULL, + nullptr, 4, GPR_OFFSET(4), eEncodingUint, @@ -252,7 +253,7 @@ nullptr, 0}, {"r5", - NULL, + nullptr, 4, GPR_OFFSET(5), eEncodingUint, @@ -263,7 +264,7 @@ nullptr, 0}, {"r6", - NULL, + nullptr, 4, GPR_OFFSET(6), eEncodingUint, @@ -274,7 +275,7 @@ nullptr, 0}, {"r7", - NULL, + nullptr, 4, GPR_OFFSET(7), eEncodingUint, @@ -286,7 +287,7 @@ nullptr, 0}, {"r8", - NULL, + nullptr, 4, GPR_OFFSET(8), eEncodingUint, @@ -297,7 +298,7 @@ nullptr, 0}, {"r9", - NULL, + nullptr, 4, GPR_OFFSET(9), eEncodingUint, @@ -308,7 +309,7 @@ nullptr, 0}, {"r10", - NULL, + nullptr, 4, GPR_OFFSET(10), eEncodingUint, @@ -320,7 +321,7 @@ nullptr, 0}, {"r11", - NULL, + nullptr, 4, GPR_OFFSET(11), eEncodingUint, @@ -332,7 +333,7 @@ nullptr, 0}, {"r12", - NULL, + nullptr, 4, GPR_OFFSET(12), eEncodingUint, @@ -393,7 +394,7 @@ 0}, {"s0", - NULL, + nullptr, 4, FPU_OFFSET(0), eEncodingIEEE754, @@ -405,7 +406,7 @@ nullptr, 0}, {"s1", - NULL, + nullptr, 4, FPU_OFFSET(1), eEncodingIEEE754, @@ -417,7 +418,7 @@ nullptr, 0}, {"s2", - NULL, + nullptr, 4, FPU_OFFSET(2), eEncodingIEEE754, @@ -429,7 +430,7 @@ nullptr, 0}, {"s3", - NULL, + nullptr, 4, FPU_OFFSET(3), eEncodingIEEE754, @@ -441,7 +442,7 @@ nullptr, 0}, {"s4", - NULL, + nullptr, 4, FPU_OFFSET(4), eEncodingIEEE754, @@ -453,7 +454,7 @@ nullptr, 0}, {"s5", - NULL, + nullptr, 4, FPU_OFFSET(5), eEncodingIEEE754, @@ -465,7 +466,7 @@ nullptr, 0}, {"s6", - NULL, + nullptr, 4, FPU_OFFSET(6), eEncodingIEEE754, @@ -477,7 +478,7 @@ nullptr, 0}, {"s7", - NULL, + nullptr, 4, FPU_OFFSET(7), eEncodingIEEE754, @@ -489,7 +490,7 @@ nullptr, 0}, {"s8", - NULL, + nullptr, 4, FPU_OFFSET(8), eEncodingIEEE754, @@ -501,7 +502,7 @@ nullptr, 0}, {"s9", - NULL, + nullptr, 4, FPU_OFFSET(9), eEncodingIEEE754, @@ -513,7 +514,7 @@ nullptr, 0}, {"s10", - NULL, + nullptr, 4, FPU_OFFSET(10), eEncodingIEEE754, @@ -525,7 +526,7 @@ nullptr, 0}, {"s11", - NULL, + nullptr, 4, FPU_OFFSET(11), eEncodingIEEE754, @@ -537,7 +538,7 @@ nullptr, 0}, {"s12", - NULL, + nullptr, 4, FPU_OFFSET(12), eEncodingIEEE754, @@ -549,7 +550,7 @@ nullptr, 0}, {"s13", - NULL, + nullptr, 4, FPU_OFFSET(13), eEncodingIEEE754, @@ -561,7 +562,7 @@ nullptr, 0}, {"s14", - NULL, + nullptr, 4, FPU_OFFSET(14), eEncodingIEEE754, @@ -573,7 +574,7 @@ nullptr, 0}, {"s15", - NULL, + nullptr, 4, FPU_OFFSET(15), eEncodingIEEE754, @@ -585,7 +586,7 @@ nullptr, 0}, {"s16", - NULL, + nullptr, 4, FPU_OFFSET(16), eEncodingIEEE754, @@ -597,7 +598,7 @@ nullptr, 0}, {"s17", - NULL, + nullptr, 4, FPU_OFFSET(17), eEncodingIEEE754, @@ -609,7 +610,7 @@ nullptr, 0}, {"s18", - NULL, + nullptr, 4, FPU_OFFSET(18), eEncodingIEEE754, @@ -621,7 +622,7 @@ nullptr, 0}, {"s19", - NULL, + nullptr, 4, FPU_OFFSET(19), eEncodingIEEE754, @@ -633,7 +634,7 @@ nullptr, 0}, {"s20", - NULL, + nullptr, 4, FPU_OFFSET(20), eEncodingIEEE754, @@ -645,7 +646,7 @@ nullptr, 0}, {"s21", - NULL, + nullptr, 4, FPU_OFFSET(21), eEncodingIEEE754, @@ -657,7 +658,7 @@ nullptr, 0}, {"s22", - NULL, + nullptr, 4, FPU_OFFSET(22), eEncodingIEEE754, @@ -669,7 +670,7 @@ nullptr, 0}, {"s23", - NULL, + nullptr, 4, FPU_OFFSET(23), eEncodingIEEE754, @@ -681,7 +682,7 @@ nullptr, 0}, {"s24", - NULL, + nullptr, 4, FPU_OFFSET(24), eEncodingIEEE754, @@ -693,7 +694,7 @@ nullptr, 0}, {"s25", - NULL, + nullptr, 4, FPU_OFFSET(25), eEncodingIEEE754, @@ -705,7 +706,7 @@ nullptr, 0}, {"s26", - NULL, + nullptr, 4, FPU_OFFSET(26), eEncodingIEEE754, @@ -717,7 +718,7 @@ nullptr, 0}, {"s27", - NULL, + nullptr, 4, FPU_OFFSET(27), eEncodingIEEE754, @@ -729,7 +730,7 @@ nullptr, 0}, {"s28", - NULL, + nullptr, 4, FPU_OFFSET(28), eEncodingIEEE754, @@ -741,7 +742,7 @@ nullptr, 0}, {"s29", - NULL, + nullptr, 4, FPU_OFFSET(29), eEncodingIEEE754, @@ -753,7 +754,7 @@ nullptr, 0}, {"s30", - NULL, + nullptr, 4, FPU_OFFSET(30), eEncodingIEEE754, @@ -765,7 +766,7 @@ nullptr, 0}, {"s31", - NULL, + nullptr, 4, FPU_OFFSET(31), eEncodingIEEE754, @@ -777,7 +778,7 @@ nullptr, 0}, {"fpscr", - NULL, + nullptr, 4, FPU_OFFSET(32), eEncodingUint, @@ -790,7 +791,7 @@ 0}, {"exception", - NULL, + nullptr, 4, EXC_OFFSET(0), eEncodingUint, @@ -802,7 +803,7 @@ nullptr, 0}, {"fsr", - NULL, + nullptr, 4, EXC_OFFSET(1), eEncodingUint, @@ -814,7 +815,7 @@ nullptr, 0}, {"far", - NULL, + nullptr, 4, EXC_OFFSET(2), eEncodingUint, @@ -943,7 +944,7 @@ assert(k_num_register_infos == k_num_registers); if (reg < k_num_registers) return &g_register_infos[reg]; - return NULL; + return nullptr; } size_t RegisterContextDarwin_arm::GetRegisterInfosCount() { @@ -959,11 +960,9 @@ const size_t k_num_fpu_registers = llvm::array_lengthof(g_fpu_regnums); const size_t k_num_exc_registers = llvm::array_lengthof(g_exc_regnums); -//---------------------------------------------------------------------- // Register set definitions. The first definitions at register set index of // zero is for all registers, followed by other registers sets. The register // information for the all register set need not be filled in. -//---------------------------------------------------------------------- static const RegisterSet g_reg_sets[] = { { "General Purpose Registers", "gpr", k_num_gpr_registers, g_gpr_regnums, @@ -980,12 +979,10 @@ const RegisterSet *RegisterContextDarwin_arm::GetRegisterSet(size_t reg_set) { if (reg_set < k_num_regsets) return &g_reg_sets[reg_set]; - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Register information definitions for 32 bit i386. -//---------------------------------------------------------------------- int RegisterContextDarwin_arm::GetSetForNativeRegNum(int reg) { if (reg < fpu_s0) return GPRRegSet; @@ -1297,7 +1294,7 @@ bool RegisterContextDarwin_arm::ReadAllRegisterValues( lldb::DataBufferSP &data_sp) { - data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); + data_sp = std::make_shared<DataBufferHeap>(REG_CONTEXT_SIZE, 0); if (data_sp && ReadGPR(false) == KERN_SUCCESS && ReadFPU(false) == KERN_SUCCESS && ReadEXC(false) == KERN_SUCCESS) { uint8_t *dst = data_sp->GetBytes();
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.h index b46946d..d7c1809 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterContextDarwin_arm.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.cpp index b478645..85d518a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.cpp
@@ -1,10 +1,9 @@ //===-- RegisterContextDarwin_arm64.cpp ---------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,6 +23,8 @@ #include "Plugins/Process/Utility/InstructionUtils.h" +#include <memory> + // Support building against older versions of LLVM, this macro was added // recently. #ifndef LLVM_EXTENSION @@ -66,9 +67,7 @@ sizeof(RegisterContextDarwin_arm64::FPU) + \ sizeof(RegisterContextDarwin_arm64::EXC)) -//----------------------------------------------------------------------------- // Include RegisterInfos_arm64 to declare our g_register_infos_arm64 structure. -//----------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_ARM64_STRUCT #include "RegisterInfos_arm64.h" #undef DECLARE_REGISTER_INFOS_ARM64_STRUCT @@ -123,7 +122,7 @@ assert(k_num_register_infos == k_num_registers); if (reg < k_num_registers) return &g_register_infos_arm64_le[reg]; - return NULL; + return nullptr; } size_t RegisterContextDarwin_arm64::GetRegisterInfosCount() { @@ -139,11 +138,9 @@ const size_t k_num_fpu_registers = llvm::array_lengthof(g_fpu_regnums); const size_t k_num_exc_registers = llvm::array_lengthof(g_exc_regnums); -//---------------------------------------------------------------------- // Register set definitions. The first definitions at register set index of // zero is for all registers, followed by other registers sets. The register // information for the all register set need not be filled in. -//---------------------------------------------------------------------- static const RegisterSet g_reg_sets[] = { { "General Purpose Registers", "gpr", k_num_gpr_registers, g_gpr_regnums, @@ -160,12 +157,10 @@ const RegisterSet *RegisterContextDarwin_arm64::GetRegisterSet(size_t reg_set) { if (reg_set < k_num_regsets) return &g_reg_sets[reg_set]; - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Register information definitions for arm64 -//---------------------------------------------------------------------- int RegisterContextDarwin_arm64::GetSetForNativeRegNum(int reg) { if (reg < fpu_v0) return GPRRegSet; @@ -428,7 +423,7 @@ case fpu_v29: case fpu_v30: case fpu_v31: - value.SetBytes(fpu.v[reg].bytes.buffer, reg_info->byte_size, + value.SetBytes(fpu.v[reg - fpu_v0].bytes.buffer, reg_info->byte_size, endian::InlHostByteOrder()); break; @@ -620,7 +615,8 @@ case fpu_v29: case fpu_v30: case fpu_v31: - ::memcpy(fpu.v[reg].bytes.buffer, value.GetBytes(), value.GetByteSize()); + ::memcpy(fpu.v[reg - fpu_v0].bytes.buffer, value.GetBytes(), + value.GetByteSize()); break; case fpu_fpsr: @@ -649,9 +645,9 @@ bool RegisterContextDarwin_arm64::ReadAllRegisterValues( lldb::DataBufferSP &data_sp) { - data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR(false) == KERN_SUCCESS && - ReadFPU(false) == KERN_SUCCESS && ReadEXC(false) == KERN_SUCCESS) { + data_sp = std::make_shared<DataBufferHeap>(REG_CONTEXT_SIZE, 0); + if (ReadGPR(false) == KERN_SUCCESS && ReadFPU(false) == KERN_SUCCESS && + ReadEXC(false) == KERN_SUCCESS) { uint8_t *dst = data_sp->GetBytes(); ::memcpy(dst, &gpr, sizeof(gpr)); dst += sizeof(gpr);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.h index 9e826d8..2f691c8 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_arm64.h
@@ -1,10 +1,9 @@ //===-- RegisterContextDarwin_arm64.h -----------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.cpp index c9e4b37..820d280 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.cpp
@@ -1,14 +1,11 @@ //===-- RegisterContextDarwin_i386.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <stddef.h> - #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" @@ -18,6 +15,10 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Compiler.h" +#include <stddef.h> + +#include <memory> + // Support building against older versions of LLVM, this macro was added // recently. #ifndef LLVM_EXTENSION @@ -175,42 +176,42 @@ // =============================== ======================= // =================== ========================= ================== // ================= - {DEFINE_GPR(eax, NULL), + {DEFINE_GPR(eax, nullptr), {ehframe_eax, dwarf_eax, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_eax}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(ebx, NULL), + {DEFINE_GPR(ebx, nullptr), {ehframe_ebx, dwarf_ebx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_ebx}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(ecx, NULL), + {DEFINE_GPR(ecx, nullptr), {ehframe_ecx, dwarf_ecx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_ecx}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(edx, NULL), + {DEFINE_GPR(edx, nullptr), {ehframe_edx, dwarf_edx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_edx}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(edi, NULL), + {DEFINE_GPR(edi, nullptr), {ehframe_edi, dwarf_edi, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_edi}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(esi, NULL), + {DEFINE_GPR(esi, nullptr), {ehframe_esi, dwarf_esi, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_esi}, nullptr, @@ -231,7 +232,7 @@ nullptr, nullptr, 0}, - {DEFINE_GPR(ss, NULL), + {DEFINE_GPR(ss, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_ss}, nullptr, @@ -252,35 +253,35 @@ nullptr, nullptr, 0}, - {DEFINE_GPR(cs, NULL), + {DEFINE_GPR(cs, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_cs}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(ds, NULL), + {DEFINE_GPR(ds, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_ds}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(es, NULL), + {DEFINE_GPR(es, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_es}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(fs, NULL), + {DEFINE_GPR(fs, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_fs}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(gs, NULL), + {DEFINE_GPR(gs, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_gs}, nullptr, @@ -426,7 +427,7 @@ assert(k_num_register_infos == k_num_registers); if (reg < k_num_registers) return &g_register_infos[reg]; - return NULL; + return nullptr; } size_t RegisterContextDarwin_i386::GetRegisterInfosCount() { @@ -459,11 +460,9 @@ const size_t k_num_fpu_registers = llvm::array_lengthof(g_fpu_regnums); const size_t k_num_exc_registers = llvm::array_lengthof(g_exc_regnums); -//---------------------------------------------------------------------- // Register set definitions. The first definitions at register set index of // zero is for all registers, followed by other registers sets. The register // information for the all register set need not be filled in. -//---------------------------------------------------------------------- static const RegisterSet g_reg_sets[] = { { "General Purpose Registers", "gpr", k_num_gpr_registers, g_gpr_regnums, @@ -480,12 +479,10 @@ const RegisterSet *RegisterContextDarwin_i386::GetRegisterSet(size_t reg_set) { if (reg_set < k_num_regsets) return &g_reg_sets[reg_set]; - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Register information definitions for 32 bit i386. -//---------------------------------------------------------------------- int RegisterContextDarwin_i386::GetSetForNativeRegNum(int reg_num) { if (reg_num < fpu_fcw) return GPRRegSet; @@ -832,9 +829,8 @@ bool RegisterContextDarwin_i386::ReadAllRegisterValues( lldb::DataBufferSP &data_sp) { - data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR(false) == 0 && ReadFPU(false) == 0 && - ReadEXC(false) == 0) { + data_sp = std::make_shared<DataBufferHeap>(REG_CONTEXT_SIZE, 0); + if (ReadGPR(false) == 0 && ReadFPU(false) == 0 && ReadEXC(false) == 0) { uint8_t *dst = data_sp->GetBytes(); ::memcpy(dst, &gpr, sizeof(gpr)); dst += sizeof(gpr);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.h index ad6a1e4..e52f0fe 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_i386.h
@@ -1,9 +1,8 @@ //===-- RegisterContextDarwin_i386.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.cpp index 9546030..62e512a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextDarwin_x86_64.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,6 +10,8 @@ #include <stdarg.h> #include <stddef.h> +#include <memory> + #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" @@ -194,42 +195,42 @@ // =============================== ====================== // =================== ========================== ==================== // =================== - {DEFINE_GPR(rax, NULL), + {DEFINE_GPR(rax, nullptr), {ehframe_dwarf_gpr_rax, ehframe_dwarf_gpr_rax, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_rax}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(rbx, NULL), + {DEFINE_GPR(rbx, nullptr), {ehframe_dwarf_gpr_rbx, ehframe_dwarf_gpr_rbx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_rbx}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(rcx, NULL), + {DEFINE_GPR(rcx, nullptr), {ehframe_dwarf_gpr_rcx, ehframe_dwarf_gpr_rcx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_rcx}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(rdx, NULL), + {DEFINE_GPR(rdx, nullptr), {ehframe_dwarf_gpr_rdx, ehframe_dwarf_gpr_rdx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_rdx}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(rdi, NULL), + {DEFINE_GPR(rdi, nullptr), {ehframe_dwarf_gpr_rdi, ehframe_dwarf_gpr_rdi, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_rdi}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(rsi, NULL), + {DEFINE_GPR(rsi, nullptr), {ehframe_dwarf_gpr_rsi, ehframe_dwarf_gpr_rsi, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_rsi}, nullptr, @@ -250,56 +251,56 @@ nullptr, nullptr, 0}, - {DEFINE_GPR(r8, NULL), + {DEFINE_GPR(r8, nullptr), {ehframe_dwarf_gpr_r8, ehframe_dwarf_gpr_r8, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r8}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(r9, NULL), + {DEFINE_GPR(r9, nullptr), {ehframe_dwarf_gpr_r9, ehframe_dwarf_gpr_r9, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r9}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(r10, NULL), + {DEFINE_GPR(r10, nullptr), {ehframe_dwarf_gpr_r10, ehframe_dwarf_gpr_r10, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r10}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(r11, NULL), + {DEFINE_GPR(r11, nullptr), {ehframe_dwarf_gpr_r11, ehframe_dwarf_gpr_r11, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r11}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(r12, NULL), + {DEFINE_GPR(r12, nullptr), {ehframe_dwarf_gpr_r12, ehframe_dwarf_gpr_r12, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r12}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(r13, NULL), + {DEFINE_GPR(r13, nullptr), {ehframe_dwarf_gpr_r13, ehframe_dwarf_gpr_r13, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r13}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(r14, NULL), + {DEFINE_GPR(r14, nullptr), {ehframe_dwarf_gpr_r14, ehframe_dwarf_gpr_r14, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r14}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(r15, NULL), + {DEFINE_GPR(r15, nullptr), {ehframe_dwarf_gpr_r15, ehframe_dwarf_gpr_r15, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_r15}, nullptr, @@ -320,21 +321,21 @@ nullptr, nullptr, 0}, - {DEFINE_GPR(cs, NULL), + {DEFINE_GPR(cs, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_cs}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(fs, NULL), + {DEFINE_GPR(fs, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_fs}, nullptr, nullptr, nullptr, 0}, - {DEFINE_GPR(gs, NULL), + {DEFINE_GPR(gs, nullptr), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, gpr_gs}, nullptr, @@ -488,7 +489,7 @@ assert(k_num_register_infos == k_num_registers); if (reg < k_num_registers) return &g_register_infos[reg]; - return NULL; + return nullptr; } size_t RegisterContextDarwin_x86_64::GetRegisterInfosCount() { @@ -520,11 +521,9 @@ const size_t k_num_fpu_registers = llvm::array_lengthof(g_fpu_regnums); const size_t k_num_exc_registers = llvm::array_lengthof(g_exc_regnums); -//---------------------------------------------------------------------- // Register set definitions. The first definitions at register set index of // zero is for all registers, followed by other registers sets. The register // information for the all register set need not be filled in. -//---------------------------------------------------------------------- static const RegisterSet g_reg_sets[] = { { "General Purpose Registers", "gpr", k_num_gpr_registers, g_gpr_regnums, @@ -542,7 +541,7 @@ RegisterContextDarwin_x86_64::GetRegisterSet(size_t reg_set) { if (reg_set < k_num_regsets) return &g_reg_sets[reg_set]; - return NULL; + return nullptr; } int RegisterContextDarwin_x86_64::GetSetForNativeRegNum(int reg_num) { @@ -910,9 +909,8 @@ bool RegisterContextDarwin_x86_64::ReadAllRegisterValues( lldb::DataBufferSP &data_sp) { - data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); - if (data_sp && ReadGPR(false) == 0 && ReadFPU(false) == 0 && - ReadEXC(false) == 0) { + data_sp = std::make_shared<DataBufferHeap>(REG_CONTEXT_SIZE, 0); + if (ReadGPR(false) == 0 && ReadFPU(false) == 0 && ReadEXC(false) == 0) { uint8_t *dst = data_sp->GetBytes(); ::memcpy(dst, &gpr, sizeof(gpr)); dst += sizeof(gpr);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.h index 6d94bf7..1a65a4f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDarwin_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextDarwin_x86_64.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.cpp index c51c30f..6832b60 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.cpp
@@ -1,10 +1,9 @@ //===-- RegisterContextDummy.cpp ---------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -50,8 +49,8 @@ m_pc_reg_info.byte_size = address_byte_size; m_pc_reg_info.encoding = eEncodingUint; m_pc_reg_info.format = eFormatPointer; - m_pc_reg_info.invalidate_regs = NULL; - m_pc_reg_info.value_regs = NULL; + m_pc_reg_info.invalidate_regs = nullptr; + m_pc_reg_info.value_regs = nullptr; m_pc_reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM; m_pc_reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM; m_pc_reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC; @@ -72,7 +71,7 @@ const lldb_private::RegisterInfo * RegisterContextDummy::GetRegisterInfoAtIndex(size_t reg) { if (reg) - return NULL; + return nullptr; return &m_pc_reg_info; } @@ -81,7 +80,7 @@ const lldb_private::RegisterSet * RegisterContextDummy::GetRegisterSet(size_t reg_set) { if (reg_set) - return NULL; + return nullptr; return &m_reg_set0; }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.h index d560861..bdaa221 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextDummy.h
@@ -1,10 +1,9 @@ //===-- RegisterContextDummy.h ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -52,9 +51,7 @@ uint32_t num) override; private: - //------------------------------------------------------------------ // For RegisterContextLLDB only - //------------------------------------------------------------------ lldb_private::RegisterSet m_reg_set0; // register set 0 (PC only) lldb_private::RegisterInfo m_pc_reg_info;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.cpp index 4ccfa2a..b90b381 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextFreeBSD_i386.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -54,9 +53,7 @@ #define DR_SIZE sizeof(uint32_t) #define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(dbreg, dr[reg_index])) -//--------------------------------------------------------------------------- // Include RegisterInfos_i386 to declare our g_register_infos_i386 structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_I386_STRUCT #include "RegisterInfos_i386.h" #undef DECLARE_REGISTER_INFOS_I386_STRUCT @@ -73,7 +70,7 @@ return g_register_infos_i386; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.h index 35a79c1..7aadf3a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_i386.h
@@ -1,9 +1,8 @@ //===-- RegisterContextFreeBSD_i386.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.cpp index 55a72b2..4331ef5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextFreeBSD_mips64.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -80,10 +79,8 @@ uint64_t dummy; } GPR_freebsd_mips; -//--------------------------------------------------------------------------- // Include RegisterInfos_mips64 to declare our g_register_infos_mips64 // structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_MIPS64_STRUCT #include "RegisterInfos_mips64.h" #undef DECLARE_REGISTER_INFOS_MIPS64_STRUCT
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h index 5e5de71..96f02b4 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextFreeBSD_mips64.h -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.cpp index efa4cc6..4f869eb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextFreeBSD_powerpc.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -169,10 +168,8 @@ uint32_t vscr; } VMX; -//--------------------------------------------------------------------------- // Include RegisterInfos_powerpc to declare our g_register_infos_powerpc // structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_POWERPC_STRUCT #include "RegisterInfos_powerpc.h" #undef DECLARE_REGISTER_INFOS_POWERPC_STRUCT @@ -191,7 +188,7 @@ const RegisterInfo *RegisterContextFreeBSD_powerpc::GetRegisterInfo() const { // assert (m_target_arch.GetCore() == ArchSpec::eCore_powerpc); llvm_unreachable("Abstract class!"); - return NULL; + return nullptr; } uint32_t RegisterContextFreeBSD_powerpc::GetRegisterCount() const { return 0; }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h index b74d0ea..ba27511 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h
@@ -1,10 +1,9 @@ //===-- RegisterContextFreeBSD_powerpc.h -------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.cpp index 4bbbd5c..bcf3951 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextFreeBSD_x86_64.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -62,10 +61,8 @@ #define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(DBG, dr[reg_index])) -//--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 // structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_X86_64_STRUCT #include "RegisterInfos_x86_64.h" #undef DECLARE_REGISTER_INFOS_X86_64_STRUCT @@ -89,10 +86,8 @@ g_register_infos.insert(g_register_infos.end(), &base_info[0], &base_info[k_num_registers_i386]); -//--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to update the g_register_infos structure // with x86_64 offsets. -//--------------------------------------------------------------------------- #define UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS #include "RegisterInfos_x86_64.h" #undef UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h index dc30f17..c379e1a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextFreeBSD_x86_64.h -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.cpp index c9b7766..c19a2bf 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.cpp
@@ -1,10 +1,9 @@ //===-- RegisterContextHistory.cpp ---------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -51,8 +50,8 @@ m_pc_reg_info.byte_size = address_byte_size; m_pc_reg_info.encoding = eEncodingUint; m_pc_reg_info.format = eFormatPointer; - m_pc_reg_info.invalidate_regs = NULL; - m_pc_reg_info.value_regs = NULL; + m_pc_reg_info.invalidate_regs = nullptr; + m_pc_reg_info.value_regs = nullptr; m_pc_reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM; m_pc_reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM; m_pc_reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC; @@ -73,7 +72,7 @@ const lldb_private::RegisterInfo * RegisterContextHistory::GetRegisterInfoAtIndex(size_t reg) { if (reg) - return NULL; + return nullptr; return &m_pc_reg_info; } @@ -82,7 +81,7 @@ const lldb_private::RegisterSet * RegisterContextHistory::GetRegisterSet(size_t reg_set) { if (reg_set) - return NULL; + return nullptr; return &m_reg_set0; }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.h index 01b3624..952e426 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextHistory.h
@@ -1,10 +1,9 @@ //===-- RegisterContextHistory.h ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -52,9 +51,7 @@ uint32_t num) override; private: - //------------------------------------------------------------------ // For RegisterContextLLDB only - //------------------------------------------------------------------ lldb_private::RegisterSet m_reg_set0; // register set 0 (PC only) lldb_private::RegisterInfo m_pc_reg_info;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp index 8c420a8..76646d8 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextLLDB.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,6 +34,8 @@ #include "RegisterContextLLDB.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -112,7 +113,7 @@ ExecutionContext exe_ctx(m_thread.shared_from_this()); RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext(); - if (reg_ctx_sp.get() == NULL) { + if (reg_ctx_sp.get() == nullptr) { m_frame_type = eNotAValidFrame; UnwindLogMsg("frame does not have a register context"); return; @@ -238,14 +239,13 @@ if (m_sym_ctx_valid) { func_unwinders_sp = - pc_module_sp->GetObjectFile() - ->GetUnwindTable() - .GetFuncUnwindersContainingAddress(m_current_pc, m_sym_ctx); + pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress( + m_current_pc, m_sym_ctx); } if (func_unwinders_sp.get() != nullptr) call_site_unwind_plan = func_unwinders_sp->GetUnwindPlanAtCallSite( - process->GetTarget(), m_current_offset_backed_up_one); + process->GetTarget(), m_thread); if (call_site_unwind_plan.get() != nullptr) { m_fallback_unwind_plan_sp = call_site_unwind_plan; @@ -370,7 +370,8 @@ if (abi) { m_fast_unwind_plan_sp.reset(); - m_full_unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric)); + m_full_unwind_plan_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); abi->CreateDefaultUnwindPlan(*m_full_unwind_plan_sp); if (m_frame_type != eSkipFrame) // don't override eSkipFrame { @@ -663,16 +664,15 @@ ModuleSP pc_module_sp(m_current_pc.GetModule()); if (!m_current_pc.IsValid() || !pc_module_sp || - pc_module_sp->GetObjectFile() == NULL) + pc_module_sp->GetObjectFile() == nullptr) return unwind_plan_sp; if (IsFrameZero()) return unwind_plan_sp; FuncUnwindersSP func_unwinders_sp( - pc_module_sp->GetObjectFile() - ->GetUnwindTable() - .GetFuncUnwindersContainingAddress(m_current_pc, m_sym_ctx)); + pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress( + m_current_pc, m_sym_ctx)); if (!func_unwinders_sp) return unwind_plan_sp; @@ -715,10 +715,10 @@ UnwindPlanSP arch_default_unwind_plan_sp; ExecutionContext exe_ctx(m_thread.shared_from_this()); Process *process = exe_ctx.GetProcessPtr(); - ABI *abi = process ? process->GetABI().get() : NULL; + ABI *abi = process ? process->GetABI().get() : nullptr; if (abi) { - arch_default_unwind_plan_sp.reset( - new UnwindPlan(lldb::eRegisterKindGeneric)); + arch_default_unwind_plan_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); abi->CreateDefaultUnwindPlan(*arch_default_unwind_plan_sp); } else { UnwindLogMsg( @@ -743,7 +743,7 @@ // This is for jumping to memory regions without any information available. if ((!m_sym_ctx_valid || - (m_sym_ctx.function == NULL && m_sym_ctx.symbol == NULL)) && + (m_sym_ctx.function == nullptr && m_sym_ctx.symbol == nullptr)) && behaves_like_zeroth_frame && m_current_pc.IsValid()) { uint32_t permissions; addr_t current_pc_addr = @@ -753,7 +753,8 @@ process->GetLoadAddressPermissions(current_pc_addr, permissions) && (permissions & ePermissionsExecutable) == 0)) { if (abi) { - unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric)); + unwind_plan_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); abi->CreateFunctionEntryUnwindPlan(*unwind_plan_sp); m_frame_type = eNormalFrame; return unwind_plan_sp; @@ -764,7 +765,7 @@ // No Module for the current pc, try using the architecture default unwind. ModuleSP pc_module_sp(m_current_pc.GetModule()); if (!m_current_pc.IsValid() || !pc_module_sp || - pc_module_sp->GetObjectFile() == NULL) { + pc_module_sp->GetObjectFile() == nullptr) { m_frame_type = eNormalFrame; return arch_default_unwind_plan_sp; } @@ -772,9 +773,8 @@ FuncUnwindersSP func_unwinders_sp; if (m_sym_ctx_valid) { func_unwinders_sp = - pc_module_sp->GetObjectFile() - ->GetUnwindTable() - .GetFuncUnwindersContainingAddress(m_current_pc, m_sym_ctx); + pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress( + m_current_pc, m_sym_ctx); } // No FuncUnwinders available for this pc (stripped function symbols, lldb @@ -792,9 +792,9 @@ // Even with -fomit-frame-pointer, we can try eh_frame to get back on // track. DWARFCallFrameInfo *eh_frame = - pc_module_sp->GetObjectFile()->GetUnwindTable().GetEHFrameInfo(); + pc_module_sp->GetUnwindTable().GetEHFrameInfo(); if (eh_frame) { - unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric)); + unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); if (eh_frame->GetUnwindPlan(m_current_pc, *unwind_plan_sp)) return unwind_plan_sp; else @@ -802,9 +802,9 @@ } ArmUnwindInfo *arm_exidx = - pc_module_sp->GetObjectFile()->GetUnwindTable().GetArmUnwindInfo(); + pc_module_sp->GetUnwindTable().GetArmUnwindInfo(); if (arm_exidx) { - unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric)); + unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); if (arm_exidx->GetUnwindPlan(exe_ctx.GetTargetRef(), m_current_pc, *unwind_plan_sp)) return unwind_plan_sp; @@ -822,8 +822,8 @@ // unwind out of sigtramp. if (m_frame_type == eTrapHandlerFrame && process) { m_fast_unwind_plan_sp.reset(); - unwind_plan_sp = func_unwinders_sp->GetEHFrameUnwindPlan( - process->GetTarget(), m_current_offset_backed_up_one); + unwind_plan_sp = + func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget()); if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc) && unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes) { return unwind_plan_sp; @@ -844,8 +844,8 @@ // normally we would call GetUnwindPlanAtCallSite() -- because CallSite may // return an unwind plan sourced from either eh_frame (that's what we // intend) or compact unwind (this won't work) - unwind_plan_sp = func_unwinders_sp->GetEHFrameUnwindPlan( - process->GetTarget(), m_current_offset_backed_up_one); + unwind_plan_sp = + func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget()); if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) { UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because the " "DynamicLoader suggested we prefer it", @@ -858,7 +858,7 @@ // the assembly language instructions if (behaves_like_zeroth_frame && process) { unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite( - process->GetTarget(), m_thread, m_current_offset_backed_up_one); + process->GetTarget(), m_thread); if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) { if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) { // We probably have an UnwindPlan created by inspecting assembly @@ -873,8 +873,8 @@ // location what helps in the most common cases when the instruction // emulation fails. UnwindPlanSP call_site_unwind_plan = - func_unwinders_sp->GetUnwindPlanAtCallSite( - process->GetTarget(), m_current_offset_backed_up_one); + func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(), + m_thread); if (call_site_unwind_plan && call_site_unwind_plan.get() != unwind_plan_sp.get() && call_site_unwind_plan->GetSourceName() != @@ -884,21 +884,39 @@ m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp; } } - UnwindLogMsgVerbose("frame uses %s for full UnwindPlan", + UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this " + "is the non-call site unwind plan and this is a " + "zeroth frame", unwind_plan_sp->GetSourceName().GetCString()); return unwind_plan_sp; } + + // If we're on the first instruction of a function, and we have an + // architectural default UnwindPlan for the initial instruction of a + // function, use that. + if (m_current_offset == 0) { + unwind_plan_sp = + func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry( + m_thread); + if (unwind_plan_sp) { + UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we are at " + "the first instruction of a function", + unwind_plan_sp->GetSourceName().GetCString()); + return unwind_plan_sp; + } + } } // Typically this is unwind info from an eh_frame section intended for // exception handling; only valid at call sites if (process) { unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite( - process->GetTarget(), m_current_offset_backed_up_one); + process->GetTarget(), m_thread); } int valid_offset = -1; if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) { - UnwindLogMsgVerbose("frame uses %s for full UnwindPlan", + UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this " + "is the call-site unwind plan", unwind_plan_sp->GetSourceName().GetCString()); return unwind_plan_sp; } @@ -908,7 +926,7 @@ // call-site assembly inspection UnwindPlan if possible. if (process) { unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite( - process->GetTarget(), m_thread, m_current_offset_backed_up_one); + process->GetTarget(), m_thread); } if (unwind_plan_sp && unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) { @@ -923,8 +941,8 @@ // code it is often written in a way that it valid at all location what // helps in the most common cases when the instruction emulation fails. UnwindPlanSP call_site_unwind_plan = - func_unwinders_sp->GetUnwindPlanAtCallSite( - process->GetTarget(), m_current_offset_backed_up_one); + func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(), + m_thread); if (call_site_unwind_plan && call_site_unwind_plan.get() != unwind_plan_sp.get() && call_site_unwind_plan->GetSourceName() != @@ -936,30 +954,18 @@ } if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) { - UnwindLogMsgVerbose("frame uses %s for full UnwindPlan", + UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we " + "failed to find a call-site unwind plan that would work", unwind_plan_sp->GetSourceName().GetCString()); return unwind_plan_sp; } - // If we're on the first instruction of a function, and we have an - // architectural default UnwindPlan for the initial instruction of a - // function, use that. - if (m_current_offset_backed_up_one == 0) { - unwind_plan_sp = - func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry( - m_thread); - if (unwind_plan_sp) { - UnwindLogMsgVerbose("frame uses %s for full UnwindPlan", - unwind_plan_sp->GetSourceName().GetCString()); - return unwind_plan_sp; - } - } - // If nothing else, use the architectural default UnwindPlan and hope that // does the job. if (arch_default_unwind_plan_sp) UnwindLogMsgVerbose( - "frame uses %s for full UnwindPlan", + "frame uses %s for full UnwindPlan because we are falling back " + "to the arch default plan", arch_default_unwind_plan_sp->GetSourceName().GetCString()); else UnwindLogMsg( @@ -1345,7 +1351,7 @@ // register, we may be able to fall back to some ABI-defined default. For // example, some ABIs allow to determine the caller's SP via the CFA. Also, // the ABI may set volatile registers to the undefined state. - ABI *abi = process ? process->GetABI().get() : NULL; + ABI *abi = process ? process->GetABI().get() : nullptr; if (abi) { const RegisterInfo *reg_info = GetRegisterInfoAtIndex(regnum.GetAsKind(eRegisterKindLLDB)); @@ -1509,9 +1515,11 @@ DWARFExpression dwarfexpr(opcode_ctx, dwarfdata, nullptr, 0, unwindplan_regloc.GetDWARFExpressionLength()); dwarfexpr.SetRegisterKind(unwindplan_registerkind); + Value cfa_val = Scalar(m_cfa); + cfa_val.SetValueType(Value::eValueTypeLoadAddress); Value result; Status error; - if (dwarfexpr.Evaluate(&exe_ctx, this, 0, nullptr, nullptr, result, + if (dwarfexpr.Evaluate(&exe_ctx, this, 0, &cfa_val, nullptr, result, &error)) { addr_t val; val = result.GetScalar().ULongLong(); @@ -1696,10 +1704,10 @@ } bool RegisterContextLLDB::ForceSwitchToFallbackUnwindPlan() { - if (m_fallback_unwind_plan_sp.get() == NULL) + if (m_fallback_unwind_plan_sp.get() == nullptr) return false; - if (m_full_unwind_plan_sp.get() == NULL) + if (m_full_unwind_plan_sp.get() == nullptr) return false; if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() || @@ -2061,7 +2069,7 @@ va_start(args, fmt); char *logmsg; - if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == NULL) { + if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == nullptr) { if (logmsg) free(logmsg); va_end(args); @@ -2082,7 +2090,7 @@ va_start(args, fmt); char *logmsg; - if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == NULL) { + if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == nullptr) { if (logmsg) free(logmsg); va_end(args);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.h index 50f12c6..64dd394 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.h
@@ -1,10 +1,9 @@ //===-- RegisterContextLLDB.h --------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -111,15 +110,13 @@ // user somehow. bool IsSkipFrame() const; - //------------------------------------------------------------------ /// Determines if a SymbolContext is a trap handler or not /// /// Given a SymbolContext, determines if this is a trap handler function /// aka asynchronous signal handler. /// - /// @return + /// \return /// Returns true if the SymbolContext is a trap handler. - //------------------------------------------------------------------ bool IsTrapHandlerSymbol(lldb_private::Process *process, const lldb_private::SymbolContext &m_sym_ctx) const; @@ -155,7 +152,6 @@ const lldb_private::RegisterInfo *reg_info, const lldb_private::RegisterValue &value); - //------------------------------------------------------------------ /// If the unwind has to the caller frame has failed, try something else /// /// If lldb is using an assembly language based UnwindPlan for a frame and @@ -164,12 +160,10 @@ /// better. This is mostly helping to work around problems where the /// assembly language inspection fails on hand-written assembly code. /// - /// @return + /// \return /// Returns true if a fallback unwindplan was found & was installed. - //------------------------------------------------------------------ bool TryFallbackUnwindPlan(); - //------------------------------------------------------------------ /// Switch to the fallback unwind plan unconditionally without any safety /// checks that it is providing better results than the normal unwind plan. /// @@ -177,7 +171,6 @@ /// found to be fundamentally incorrect/impossible. /// /// Returns true if it was able to install the fallback unwind plan. - //------------------------------------------------------------------ bool ForceSwitchToFallbackUnwindPlan(); // Get the contents of a general purpose (address-size) register for this @@ -250,9 +243,7 @@ lldb_private::UnwindLLDB &m_parent_unwind; // The UnwindLLDB that is creating // this RegisterContextLLDB - //------------------------------------------------------------------ // For RegisterContextLLDB only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(RegisterContextLLDB); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.cpp index 2cb17cb..7997963 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_i386.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -82,9 +81,7 @@ #define DR_OFFSET(reg_index) (DR_0_OFFSET + (reg_index * 4)) #define FPR_SIZE(reg) sizeof(((FPR_i386 *)NULL)->reg) -//--------------------------------------------------------------------------- // Include RegisterInfos_i386 to declare our g_register_infos_i386 structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_I386_STRUCT #include "RegisterInfos_i386.h" #undef DECLARE_REGISTER_INFOS_I386_STRUCT @@ -93,8 +90,8 @@ const ArchSpec &target_arch) : RegisterInfoInterface(target_arch) { RegisterInfo orig_ax = {"orig_eax", - NULL, - sizeof(((GPR *)NULL)->orig_eax), + nullptr, + sizeof(((GPR *)nullptr)->orig_eax), (LLVM_EXTENSION offsetof(GPR, orig_eax)), eEncodingUint, eFormatHex, @@ -117,7 +114,7 @@ return g_register_infos_i386; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.h index fbf8037..5567a1a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_i386.h
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_i386.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.cpp index 7b16531..fc60fea 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_mips.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -22,9 +21,7 @@ using namespace lldb_private; using namespace lldb; -//--------------------------------------------------------------------------- // Include RegisterInfos_mips to declare our g_register_infos_mips structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_MIPS_STRUCT #include "RegisterInfos_mips.h" #undef DECLARE_REGISTER_INFOS_MIPS_STRUCT @@ -119,7 +116,7 @@ return g_register_infos_mips; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.h index a16c4ec..e637dfc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips.h
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_mips.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.cpp index 1bb16c7..3927883 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_mips64.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -23,19 +22,15 @@ using namespace lldb; using namespace lldb_private; -//--------------------------------------------------------------------------- // Include RegisterInfos_mips64 to declare our g_register_infos_mips64 // structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_MIPS64_STRUCT #define LINUX_MIPS64 #include "RegisterInfos_mips64.h" #undef LINUX_MIPS64 #undef DECLARE_REGISTER_INFOS_MIPS64_STRUCT -//--------------------------------------------------------------------------- // Include RegisterInfos_mips to declare our g_register_infos_mips structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_MIPS_STRUCT #include "RegisterInfos_mips.h" #undef DECLARE_REGISTER_INFOS_MIPS_STRUCT
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.h index d3ca9d7..ca0f014 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_mips64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_mips64.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.cpp index 5a7f5a1..d6401d7 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_s390x.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,7 @@ using namespace lldb_private; using namespace lldb; -//--------------------------------------------------------------------------- // Include RegisterInfos_s390x to declare our g_register_infos_s390x structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_S390X_STRUCT #include "RegisterInfos_s390x.h" #undef DECLARE_REGISTER_INFOS_S390X_STRUCT
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.h index 556cc2e..10810c9 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_s390x.h
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_s390x.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.cpp index 526b3ec..640d5bc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_x86_64.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -76,10 +75,8 @@ (LLVM_EXTENSION offsetof(UserArea, dbg) + \ LLVM_EXTENSION offsetof(DBG, dr[reg_index])) -//--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 // structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_X86_64_STRUCT #include "RegisterInfos_x86_64.h" #undef DECLARE_REGISTER_INFOS_X86_64_STRUCT @@ -103,10 +100,8 @@ g_register_infos.insert(g_register_infos.end(), &base_info[0], &base_info[k_num_registers_i386]); -//--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to update the g_register_infos structure // with x86_64 offsets. -//--------------------------------------------------------------------------- #define UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS #include "RegisterInfos_x86_64.h" #undef UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS @@ -162,8 +157,8 @@ m_register_info_count(GetRegisterInfoCount(target_arch)), m_user_register_count(GetUserRegisterInfoCount(target_arch)) { RegisterInfo orig_ax = {"orig_rax", - NULL, - sizeof(((GPR *)NULL)->orig_rax), + nullptr, + sizeof(((GPR *)nullptr)->orig_rax), (LLVM_EXTENSION offsetof(GPR, orig_rax)), eEncodingUint, eFormatHex,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.h index 99a4cb7..02f273c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextLinux_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextLinux_x86_64.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.cpp index c0a6084..bc78c1d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMacOSXFrameBackchain.cpp -----------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,18 +19,14 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // RegisterContextMacOSXFrameBackchain constructor -//---------------------------------------------------------------------- RegisterContextMacOSXFrameBackchain::RegisterContextMacOSXFrameBackchain( Thread &thread, uint32_t concrete_frame_idx, const UnwindMacOSXFrameBackchain::Cursor &cursor) : RegisterContext(thread, concrete_frame_idx), m_cursor(cursor), m_cursor_is_valid(true) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- RegisterContextMacOSXFrameBackchain::~RegisterContextMacOSXFrameBackchain() {} void RegisterContextMacOSXFrameBackchain::InvalidateAllRegisters() {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.h index 69e23c2..36e5538 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMacOSXFrameBackchain.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMacOSXFrameBackchain.h -------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.cpp index 69522ac..c7042ab 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMach_arm.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.h index 5ea47f2..8b2425a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMach_arm.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.cpp index 9413860..e631ab9 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMach_i386.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.h index a7e29e9..b883556 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_i386.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMach_i386.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.cpp index e523b95..db17d7d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMach_x86_64.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.h index c73bdda..688009a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMach_x86_64.h
@@ -1,10 +1,9 @@ //===-- RegisterContextMach_x86_64.h ------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp index f05c07f..946d4fa 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMemory.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // RegisterContextMemory constructor -//---------------------------------------------------------------------- RegisterContextMemory::RegisterContextMemory(Thread &thread, uint32_t concrete_frame_idx, DynamicRegisterInfo ®_infos, @@ -41,9 +38,7 @@ m_reg_data.SetData(reg_data_sp); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- RegisterContextMemory::~RegisterContextMemory() {} void RegisterContextMemory::InvalidateAllRegisters() {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.h index cdf2a54..68223ea 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextMemory.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMemory.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -40,13 +39,11 @@ uint32_t ConvertRegisterKindToRegisterNumber(lldb::RegisterKind kind, uint32_t num) override; - //------------------------------------------------------------------ // If all of the thread register are in a contiguous buffer in // memory, then the default ReadRegister/WriteRegister and // ReadAllRegisterValues/WriteAllRegisterValues will work. If thread // registers are not contiguous, clients will want to subclass this // class and modify the read/write functions as needed. - //------------------------------------------------------------------ bool ReadRegister(const lldb_private::RegisterInfo *reg_info, lldb_private::RegisterValue ®_value) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.cpp index ca7a013..e620ff6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextNetBSD_x86_64.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -78,10 +77,8 @@ LLVM_EXTENSION offsetof(DBG, dr[reg_index])) -//--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 // structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_X86_64_STRUCT #include "RegisterInfos_x86_64.h" #undef DECLARE_REGISTER_INFOS_X86_64_STRUCT
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.h index 6b19981..4820ef8 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextNetBSD_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextNetBSD_x86_64.h -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.cpp index 1f95810..06eac6f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextOpenBSD_i386.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -51,9 +50,7 @@ #define DR_SIZE sizeof(uint32_t) #define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(dbreg, dr[reg_index])) -//--------------------------------------------------------------------------- // Include RegisterInfos_i386 to declare our g_register_infos_i386 structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_I386_STRUCT #include "RegisterInfos_i386.h" #undef DECLARE_REGISTER_INFOS_I386_STRUCT @@ -70,7 +67,7 @@ return g_register_infos_i386; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.h index d3c1300..992ce09 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_i386.h
@@ -1,9 +1,8 @@ //===-- RegisterContextOpenBSD_i386.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.cpp index e7ff073..e210196 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextOpenBSD_x86_64.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -59,10 +58,8 @@ #define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(DBG, dr[reg_index])) -//--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 // structure. -//--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_X86_64_STRUCT #include "RegisterInfos_x86_64.h" #undef DECLARE_REGISTER_INFOS_X86_64_STRUCT
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.h index aa2b773..9c76e72 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextOpenBSD_x86_64.h -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp index b0e53cf..821e2aa 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_arm.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -87,7 +86,7 @@ lldb_private::Thread &thread, uint32_t concrete_frame_idx, lldb_private::RegisterInfoInterface *register_info) : lldb_private::RegisterContext(thread, concrete_frame_idx) { - m_register_info_ap.reset(register_info); + m_register_info_up.reset(register_info); switch (register_info->m_target_arch.GetMachine()) { case llvm::Triple::arm: @@ -132,14 +131,14 @@ } size_t RegisterContextPOSIX_arm::GetGPRSize() { - return m_register_info_ap->GetGPRSize(); + return m_register_info_up->GetGPRSize(); } const lldb_private::RegisterInfo *RegisterContextPOSIX_arm::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. - return m_register_info_ap->GetRegisterInfo(); + return m_register_info_up->GetRegisterInfo(); } const lldb_private::RegisterInfo * @@ -147,7 +146,7 @@ if (reg < m_reg_info.num_registers) return &GetRegisterInfo()[reg]; else - return NULL; + return nullptr; } size_t RegisterContextPOSIX_arm::GetRegisterSetCount() { @@ -163,15 +162,15 @@ const lldb_private::RegisterSet * RegisterContextPOSIX_arm::GetRegisterSet(size_t set) { if (IsRegisterSetAvailable(set)) { - switch (m_register_info_ap->m_target_arch.GetMachine()) { + switch (m_register_info_up->m_target_arch.GetMachine()) { case llvm::Triple::arm: return &g_reg_sets_arm[set]; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } } - return NULL; + return nullptr; } const char *RegisterContextPOSIX_arm::GetRegisterName(unsigned reg) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.h index 4b5a8fe..603ba76 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_arm.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -84,7 +83,7 @@ struct RegisterContextPOSIX_arm::FPU m_fpr; // floating-point registers including extended register sets. std::unique_ptr<lldb_private::RegisterInfoInterface> - m_register_info_ap; // Register Info Interface (FreeBSD or Linux) + m_register_info_up; // Register Info Interface (FreeBSD or Linux) // Determines if an extended register set is supported on the processor // running the inferior process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.cpp index 8b00dfc..99b897d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_arm64.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -106,7 +105,7 @@ lldb_private::Thread &thread, uint32_t concrete_frame_idx, lldb_private::RegisterInfoInterface *register_info) : lldb_private::RegisterContext(thread, concrete_frame_idx) { - m_register_info_ap.reset(register_info); + m_register_info_up.reset(register_info); switch (register_info->m_target_arch.GetMachine()) { case llvm::Triple::aarch64: @@ -151,7 +150,7 @@ } size_t RegisterContextPOSIX_arm64::GetGPRSize() { - return m_register_info_ap->GetGPRSize(); + return m_register_info_up->GetGPRSize(); } const lldb_private::RegisterInfo * @@ -159,7 +158,7 @@ // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. - return m_register_info_ap->GetRegisterInfo(); + return m_register_info_up->GetRegisterInfo(); } const lldb_private::RegisterInfo * @@ -167,7 +166,7 @@ if (reg < m_reg_info.num_registers) return &GetRegisterInfo()[reg]; else - return NULL; + return nullptr; } size_t RegisterContextPOSIX_arm64::GetRegisterSetCount() { @@ -183,15 +182,15 @@ const lldb_private::RegisterSet * RegisterContextPOSIX_arm64::GetRegisterSet(size_t set) { if (IsRegisterSetAvailable(set)) { - switch (m_register_info_ap->m_target_arch.GetMachine()) { + switch (m_register_info_up->m_target_arch.GetMachine()) { case llvm::Triple::aarch64: return &g_reg_sets_arm64[set]; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } } - return NULL; + return nullptr; } const char *RegisterContextPOSIX_arm64::GetRegisterName(unsigned reg) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.h index 603c12d..49a49b6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_arm64.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -84,7 +83,7 @@ struct RegisterContextPOSIX_arm64::FPU m_fpr; // floating-point registers including extended register sets. std::unique_ptr<lldb_private::RegisterInfoInterface> - m_register_info_ap; // Register Info Interface (FreeBSD or Linux) + m_register_info_up; // Register Info Interface (FreeBSD or Linux) // Determines if an extended register set is supported on the processor // running the inferior process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.cpp index 9270d09..f1fa303 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_mips64.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -45,7 +44,7 @@ Thread &thread, uint32_t concrete_frame_idx, RegisterInfoInterface *register_info) : RegisterContext(thread, concrete_frame_idx) { - m_register_info_ap.reset(register_info); + m_register_info_up.reset(register_info); m_num_registers = GetRegisterCount(); int set = GetRegisterSetCount(); @@ -78,18 +77,18 @@ } size_t RegisterContextPOSIX_mips64::GetRegisterCount() { - return m_register_info_ap->GetRegisterCount(); + return m_register_info_up->GetRegisterCount(); } size_t RegisterContextPOSIX_mips64::GetGPRSize() { - return m_register_info_ap->GetGPRSize(); + return m_register_info_up->GetGPRSize(); } const RegisterInfo *RegisterContextPOSIX_mips64::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. - return m_register_info_ap->GetRegisterInfo(); + return m_register_info_up->GetRegisterInfo(); } const RegisterInfo * @@ -97,26 +96,26 @@ if (reg < m_num_registers) return &GetRegisterInfo()[reg]; else - return NULL; + return nullptr; } size_t RegisterContextPOSIX_mips64::GetRegisterSetCount() { - ArchSpec target_arch = m_register_info_ap->GetTargetArchitecture(); + ArchSpec target_arch = m_register_info_up->GetTargetArchitecture(); switch (target_arch.GetTriple().getOS()) { case llvm::Triple::Linux: { if ((target_arch.GetMachine() == llvm::Triple::mipsel) || (target_arch.GetMachine() == llvm::Triple::mips)) { - const auto *context = static_cast<const RegisterContextLinux_mips *> - (m_register_info_ap.get()); + const auto *context = static_cast<const RegisterContextLinux_mips *>( + m_register_info_up.get()); return context->GetRegisterSetCount(); } - const auto *context = static_cast<const RegisterContextLinux_mips64 *> - (m_register_info_ap.get()); + const auto *context = static_cast<const RegisterContextLinux_mips64 *>( + m_register_info_up.get()); return context->GetRegisterSetCount(); } default: { - const auto *context = static_cast<const RegisterContextFreeBSD_mips64 *> - (m_register_info_ap.get()); + const auto *context = static_cast<const RegisterContextFreeBSD_mips64 *>( + m_register_info_up.get()); return context->GetRegisterSetCount(); } @@ -124,22 +123,22 @@ } const RegisterSet *RegisterContextPOSIX_mips64::GetRegisterSet(size_t set) { - ArchSpec target_arch = m_register_info_ap->GetTargetArchitecture(); + ArchSpec target_arch = m_register_info_up->GetTargetArchitecture(); switch (target_arch.GetTriple().getOS()) { case llvm::Triple::Linux: { if ((target_arch.GetMachine() == llvm::Triple::mipsel) || (target_arch.GetMachine() == llvm::Triple::mips)) { - const auto *context = static_cast<const RegisterContextLinux_mips *> - (m_register_info_ap.get()); + const auto *context = static_cast<const RegisterContextLinux_mips *>( + m_register_info_up.get()); return context->GetRegisterSet(set); } - const auto *context = static_cast<const RegisterContextLinux_mips64 *> - (m_register_info_ap.get()); + const auto *context = static_cast<const RegisterContextLinux_mips64 *>( + m_register_info_up.get()); return context->GetRegisterSet(set); } default: { - const auto *context = static_cast<const RegisterContextFreeBSD_mips64 *> - (m_register_info_ap.get()); + const auto *context = static_cast<const RegisterContextFreeBSD_mips64 *>( + m_register_info_up.get()); return context->GetRegisterSet(set); } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.h index 09cfd42..c507e14 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_mips64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_mips64.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -62,7 +61,7 @@ uint32_t m_num_registers; uint8_t m_registers_count[register_set_count]; std::unique_ptr<lldb_private::RegisterInfoInterface> - m_register_info_ap; // Register Info Interface (FreeBSD or Linux) + m_register_info_up; // Register Info Interface (FreeBSD or Linux) // Determines if an extended register set is supported on the processor // running the inferior process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.cpp index 47a8e2c3..a78e9ed 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.cpp
@@ -1,10 +1,9 @@ //===-- RegisterContextPOSIX_powerpc.cpp -------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -94,7 +93,7 @@ Thread &thread, uint32_t concrete_frame_idx, RegisterInfoInterface *register_info) : RegisterContext(thread, concrete_frame_idx) { - m_register_info_ap.reset(register_info); + m_register_info_up.reset(register_info); } RegisterContextPOSIX_powerpc::~RegisterContextPOSIX_powerpc() {} @@ -119,14 +118,14 @@ } size_t RegisterContextPOSIX_powerpc::GetGPRSize() { - return m_register_info_ap->GetGPRSize(); + return m_register_info_up->GetGPRSize(); } const RegisterInfo *RegisterContextPOSIX_powerpc::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. - return m_register_info_ap->GetRegisterInfo(); + return m_register_info_up->GetRegisterInfo(); } const RegisterInfo * @@ -134,7 +133,7 @@ if (reg < k_num_registers_powerpc) return &GetRegisterInfo()[reg]; else - return NULL; + return nullptr; } size_t RegisterContextPOSIX_powerpc::GetRegisterSetCount() { @@ -151,7 +150,7 @@ if (IsRegisterSetAvailable(set)) return &g_reg_sets_powerpc[set]; else - return NULL; + return nullptr; } const char *RegisterContextPOSIX_powerpc::GetRegisterName(unsigned reg) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.h index 3260cb1..1a21a71 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_powerpc.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_powerpc.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,9 +16,7 @@ class ProcessMonitor; -// --------------------------------------------------------------------------- // Internal codes for all powerpc registers. -// --------------------------------------------------------------------------- enum { k_first_gpr_powerpc, gpr_r0_powerpc = k_first_gpr_powerpc, @@ -178,7 +175,7 @@ m_fpr_powerpc[k_num_fpr_registers_powerpc]; // floating point registers. uint32_t m_vmx_powerpc[k_num_vmx_registers_powerpc][4]; std::unique_ptr<lldb_private::RegisterInfoInterface> - m_register_info_ap; // Register Info Interface (FreeBSD or Linux) + m_register_info_up; // Register Info Interface (FreeBSD or Linux) // Determines if an extended register set is supported on the processor // running the inferior process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.cpp index ef221c9..02546c0 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_ppc64le.cpp -------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -116,7 +115,7 @@ Thread &thread, uint32_t concrete_frame_idx, RegisterInfoInterface *register_info) : RegisterContext(thread, concrete_frame_idx) { - m_register_info_ap.reset(register_info); + m_register_info_up.reset(register_info); } void RegisterContextPOSIX_ppc64le::InvalidateAllRegisters() {} @@ -137,14 +136,14 @@ } size_t RegisterContextPOSIX_ppc64le::GetGPRSize() { - return m_register_info_ap->GetGPRSize(); + return m_register_info_up->GetGPRSize(); } const RegisterInfo *RegisterContextPOSIX_ppc64le::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. - return m_register_info_ap->GetRegisterInfo(); + return m_register_info_up->GetRegisterInfo(); } const RegisterInfo * @@ -152,7 +151,7 @@ if (reg < k_num_registers_ppc64le) return &GetRegisterInfo()[reg]; else - return NULL; + return nullptr; } size_t RegisterContextPOSIX_ppc64le::GetRegisterSetCount() { @@ -169,7 +168,7 @@ if (IsRegisterSetAvailable(set)) return &g_reg_sets_ppc64le[set]; else - return NULL; + return nullptr; } const char *RegisterContextPOSIX_ppc64le::GetRegisterName(unsigned reg) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.h index 9159819..3707977 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_ppc64le.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_ppc64le.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -56,7 +55,7 @@ // VSX registers. uint64_t m_vsx_ppc64le[k_num_vsx_registers_ppc64le * 2]; - std::unique_ptr<lldb_private::RegisterInfoInterface> m_register_info_ap; + std::unique_ptr<lldb_private::RegisterInfoInterface> m_register_info_up; // Determines if an extended register set is supported on the processor // running the inferior process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.cpp index 24f1310..e040e50 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_s390x.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -82,7 +81,7 @@ Thread &thread, uint32_t concrete_frame_idx, RegisterInfoInterface *register_info) : RegisterContext(thread, concrete_frame_idx) { - m_register_info_ap.reset(register_info); + m_register_info_up.reset(register_info); switch (register_info->m_target_arch.GetMachine()) { case llvm::Triple::systemz: @@ -106,7 +105,7 @@ void RegisterContextPOSIX_s390x::InvalidateAllRegisters() {} const RegisterInfo *RegisterContextPOSIX_s390x::GetRegisterInfo() { - return m_register_info_ap->GetRegisterInfo(); + return m_register_info_up->GetRegisterInfo(); } const RegisterInfo * @@ -114,7 +113,7 @@ if (reg < m_reg_info.num_registers) return &GetRegisterInfo()[reg]; else - return NULL; + return nullptr; } size_t RegisterContextPOSIX_s390x::GetRegisterCount() { @@ -152,15 +151,15 @@ const RegisterSet *RegisterContextPOSIX_s390x::GetRegisterSet(size_t set) { if (IsRegisterSetAvailable(set)) { - switch (m_register_info_ap->m_target_arch.GetMachine()) { + switch (m_register_info_up->m_target_arch.GetMachine()) { case llvm::Triple::systemz: return &g_reg_sets_s390x[set]; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } } - return NULL; + return nullptr; } lldb::ByteOrder RegisterContextPOSIX_s390x::GetByteOrder() {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.h index 7a7b6bd..54993ce 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_s390x.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_s390x.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -59,7 +58,7 @@ }; RegInfo m_reg_info; - std::unique_ptr<lldb_private::RegisterInfoInterface> m_register_info_ap; + std::unique_ptr<lldb_private::RegisterInfoInterface> m_register_info_up; virtual bool IsRegisterSetAvailable(size_t set_index);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.cpp index 78f561a..4d5991f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_x86.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -319,7 +318,7 @@ Thread &thread, uint32_t concrete_frame_idx, RegisterInfoInterface *register_info) : RegisterContext(thread, concrete_frame_idx) { - m_register_info_ap.reset(register_info); + m_register_info_up.reset(register_info); switch (register_info->m_target_arch.GetMachine()) { case llvm::Triple::x86: @@ -405,7 +404,7 @@ } size_t RegisterContextPOSIX_x86::GetGPRSize() { - return m_register_info_ap->GetGPRSize(); + return m_register_info_up->GetGPRSize(); } size_t RegisterContextPOSIX_x86::GetFXSAVEOffset() { @@ -416,7 +415,7 @@ // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. - return m_register_info_ap->GetRegisterInfo(); + return m_register_info_up->GetRegisterInfo(); } const RegisterInfo * @@ -424,7 +423,7 @@ if (reg < m_reg_info.num_registers) return &GetRegisterInfo()[reg]; else - return NULL; + return nullptr; } size_t RegisterContextPOSIX_x86::GetRegisterSetCount() { @@ -439,17 +438,17 @@ const RegisterSet *RegisterContextPOSIX_x86::GetRegisterSet(size_t set) { if (IsRegisterSetAvailable(set)) { - switch (m_register_info_ap->m_target_arch.GetMachine()) { + switch (m_register_info_up->m_target_arch.GetMachine()) { case llvm::Triple::x86: return &g_reg_sets_i386[set]; case llvm::Triple::x86_64: return &g_reg_sets_x86_64[set]; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } } - return NULL; + return nullptr; } const char *RegisterContextPOSIX_x86::GetRegisterName(unsigned reg) { @@ -475,22 +474,13 @@ return false; if (byte_order == eByteOrderLittle) { - ::memcpy(m_fpr.fxsave.xmm[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(XMMReg)); - ::memcpy(m_fpr.xsave.ymmh[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg), - sizeof(YMMHReg)); + uint32_t reg_no = reg - m_reg_info.first_ymm; + YMMToXState(m_ymm_set.ymm[reg_no], + m_fpr.fxsave.xmm[reg_no].bytes, + m_fpr.xsave.ymmh[reg_no].bytes); return true; } - if (byte_order == eByteOrderBig) { - ::memcpy(m_fpr.fxsave.xmm[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg), - sizeof(XMMReg)); - ::memcpy(m_fpr.xsave.ymmh[reg - m_reg_info.first_ymm].bytes, - m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(YMMHReg)); - return true; - } return false; // unsupported or invalid byte order } @@ -501,24 +491,13 @@ return false; if (byte_order == eByteOrderLittle) { - ::memcpy(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, - m_fpr.fxsave.xmm[reg - m_reg_info.first_ymm].bytes, - sizeof(XMMReg)); - ::memcpy(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg), - m_fpr.xsave.ymmh[reg - m_reg_info.first_ymm].bytes, - sizeof(YMMHReg)); + uint32_t reg_no = reg - m_reg_info.first_ymm; + m_ymm_set.ymm[reg_no] = XStateToYMM( + m_fpr.fxsave.xmm[reg_no].bytes, + m_fpr.xsave.ymmh[reg_no].bytes); return true; } - if (byte_order == eByteOrderBig) { - ::memcpy(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg), - m_fpr.fxsave.xmm[reg - m_reg_info.first_ymm].bytes, - sizeof(XMMReg)); - ::memcpy(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, - m_fpr.xsave.ymmh[reg - m_reg_info.first_ymm].bytes, - sizeof(YMMHReg)); - return true; - } return false; // unsupported or invalid byte order }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.h index b6db45e..932f97b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_x86.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIX_x86.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -51,9 +50,7 @@ uint32_t ConvertRegisterKindToRegisterNumber(lldb::RegisterKind kind, uint32_t num) override; - //--------------------------------------------------------------------------- // Note: prefer kernel definitions over user-land - //--------------------------------------------------------------------------- enum FPRType { eNotValid = 0, eFSAVE, // TODO @@ -149,7 +146,7 @@ // register sets. lldb_private::YMM m_ymm_set; // copy of ymmh and xmm register halves. std::unique_ptr<lldb_private::RegisterInfoInterface> - m_register_info_ap; // Register Info Interface (FreeBSD or Linux) + m_register_info_up; // Register Info Interface (FreeBSD or Linux) // Determines if an extended register set is supported on the processor // running the inferior process.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp index 96ad139..bcf60cc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextThreadMemory.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -55,9 +54,7 @@ } } -//------------------------------------------------------------------ // Subclasses must override these functions -//------------------------------------------------------------------ void RegisterContextThreadMemory::InvalidateAllRegisters() { UpdateRegisterContext(); if (m_reg_ctx_sp) @@ -76,7 +73,7 @@ UpdateRegisterContext(); if (m_reg_ctx_sp) return m_reg_ctx_sp->GetRegisterInfoAtIndex(reg); - return NULL; + return nullptr; } size_t RegisterContextThreadMemory::GetRegisterSetCount() { @@ -90,7 +87,7 @@ UpdateRegisterContext(); if (m_reg_ctx_sp) return m_reg_ctx_sp->GetRegisterSet(reg_set); - return NULL; + return nullptr; } bool RegisterContextThreadMemory::ReadRegister(const RegisterInfo *reg_info,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h index 0d50c73..09a679a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h
@@ -1,9 +1,8 @@ //===-- RegisterContextThreadMemory.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_mips.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_mips.h index da470bd..7780be5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_mips.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_mips.h
@@ -1,9 +1,8 @@ //===-- RegisterContext_mips.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_powerpc.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_powerpc.h index 7324295..1ffcbeb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_powerpc.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_powerpc.h
@@ -1,10 +1,9 @@ //===-- RegisterContext_powerpc.h --------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_s390x.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_s390x.h index 90803dc..2cf39e9 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_s390x.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_s390x.h
@@ -1,18 +1,15 @@ //===-- RegisterContext_s390x.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 liblldb_RegisterContext_s390x_h_ #define liblldb_RegisterContext_s390x_h_ -//--------------------------------------------------------------------------- // SystemZ ehframe, dwarf regnums -//--------------------------------------------------------------------------- // EHFrame and DWARF Register numbers (eRegisterKindEHFrame & // eRegisterKindDWARF)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_x86.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_x86.h index e3ff492..2b79f77 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_x86.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterContext_x86.h
@@ -1,9 +1,8 @@ //===-- RegisterContext_x86.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,9 +16,7 @@ #include "llvm/Support/Compiler.h" namespace lldb_private { -//--------------------------------------------------------------------------- // i386 ehframe, dwarf regnums -//--------------------------------------------------------------------------- // Register numbers seen in eh_frame (eRegisterKindEHFrame) on i386 systems // (non-Darwin) @@ -132,9 +129,7 @@ dwarf_bnd3_i386, }; -//--------------------------------------------------------------------------- // AMD x86_64, AMD64, Intel EM64T, or Intel 64 ehframe, dwarf regnums -//--------------------------------------------------------------------------- // EHFrame and DWARF Register numbers (eRegisterKindEHFrame & // eRegisterKindDWARF) @@ -242,9 +237,7 @@ // dwarf_k7_x86_64, }; -//--------------------------------------------------------------------------- // Generic floating-point registers -//--------------------------------------------------------------------------- struct MMSReg { uint8_t bytes[10]; @@ -283,9 +276,7 @@ uint8_t padding2[40]; }; -//--------------------------------------------------------------------------- // Extended floating-point registers -//--------------------------------------------------------------------------- struct YMMHReg { uint8_t bytes[16]; // 16 * 8 bits for the high bytes of each YMM register @@ -341,7 +332,7 @@ // x86 extensions to FXSAVE (i.e. for AVX and MPX processors) LLVM_PACKED_START -struct LLVM_ALIGNAS(16) XSAVE { +struct XSAVE { FXSAVE i387; // floating point registers typical in i387_fxsave_struct XSAVE_HDR header; // The xsave_hdr_struct can be used to determine if the // following extensions are usable @@ -362,6 +353,22 @@ LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE(); +// Convenience function to combine YMM register data from XSAVE-style input. +inline YMMReg XStateToYMM(const void* xmm_bytes, const void* ymmh_bytes) { + YMMReg ret; + + ::memcpy(ret.bytes, xmm_bytes, sizeof(XMMReg)); + ::memcpy(ret.bytes + sizeof(XMMReg), ymmh_bytes, sizeof(YMMHReg)); + + return ret; +} + +// Convenience function to copy YMM register data into XSAVE-style output. +inline void YMMToXState(const YMMReg& input, void* xmm_bytes, void* ymmh_bytes) { + ::memcpy(xmm_bytes, input.bytes, sizeof(XMMReg)); + ::memcpy(ymmh_bytes, input.bytes + sizeof(XMMReg), sizeof(YMMHReg)); +} + } // namespace lldb_private #endif
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoInterface.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoInterface.h index 5d7ad89..4b58e74 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoInterface.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoInterface.h
@@ -1,9 +1,8 @@ //===-- RegisterInfoInterface.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,11 +15,9 @@ namespace lldb_private { -///------------------------------------------------------------------------------ -/// @class RegisterInfoInterface +/// \class RegisterInfoInterface /// /// RegisterInfo interface to patch RegisterInfo structure for archs. -///------------------------------------------------------------------------------ class RegisterInfoInterface { public: RegisterInfoInterface(const lldb_private::ArchSpec &target_arch)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.cpp index 0111b84..d392d3b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.cpp
@@ -1,9 +1,8 @@ //===-- RegisterInfoPOSIX_arm.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -44,9 +43,7 @@ (sizeof(RegisterInfoPOSIX_arm::GPR) + sizeof(RegisterInfoPOSIX_arm::FPU) + \ sizeof(RegisterInfoPOSIX_arm::EXC)) -//----------------------------------------------------------------------------- // Include RegisterInfos_arm to declare our g_register_infos_arm structure. -//----------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_ARM_STRUCT #include "RegisterInfos_arm.h" #undef DECLARE_REGISTER_INFOS_ARM_STRUCT @@ -58,7 +55,7 @@ return g_register_infos_arm; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.h index d90aec1..39c2047 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterInfoPOSIX_arm.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.cpp index 1b145e0..f747152 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterInfoPOSIX_arm64.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -49,9 +48,7 @@ sizeof(RegisterInfoPOSIX_arm64::FPU) + \ sizeof(RegisterInfoPOSIX_arm64::EXC)) -//----------------------------------------------------------------------------- // Include RegisterInfos_arm64 to declare our g_register_infos_arm64 structure. -//----------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_ARM64_STRUCT #include "RegisterInfos_arm64.h" #undef DECLARE_REGISTER_INFOS_ARM64_STRUCT @@ -63,7 +60,7 @@ return g_register_infos_arm64_le; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.h index af77076..ace179a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_arm64.h
@@ -1,9 +1,8 @@ //===-- RegisterInfoPOSIX_arm64.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.cpp index e5e7350..35051a3 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.cpp
@@ -1,9 +1,8 @@ //===-- RegisterInfoPOSIX_ppc64le.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===// @@ -16,9 +15,7 @@ #include "RegisterInfoPOSIX_ppc64le.h" -//----------------------------------------------------------------------------- // Include RegisterInfoPOSIX_ppc64le to declare our g_register_infos_ppc64le -//----------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_PPC64LE_STRUCT #include "RegisterInfos_ppc64le.h" #undef DECLARE_REGISTER_INFOS_PPC64LE_STRUCT @@ -30,7 +27,7 @@ return g_register_infos_ppc64le; default: assert(false && "Unhandled target architecture."); - return NULL; + return nullptr; } }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.h index 411ab05..c4d4d3b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.h
@@ -1,9 +1,8 @@ //===-- RegisterInfoPOSIX_ppc64le.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm.h index ec951ea..74b9e3b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_arm.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm64.h index 039d98e..4ee0b52 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_arm64.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_arm64.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_i386.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_i386.h index f894787..72ff904 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_i386.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_i386.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_i386.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips.h index 36483c0..08201fd 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_mips.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips64.h index 0194074..b6e218e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_mips64.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_mips64.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_powerpc.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_powerpc.h index c0d47f0..51be31f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_powerpc.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_powerpc.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_powerpc.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64.h index dbd87ad..1086d3d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_ppc64.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64le.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64le.h index e6fa17b..0b099a5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64le.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_ppc64le.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_ppc64le.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_s390x.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_s390x.h index b750be4..11344ff 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_s390x.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_s390x.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_s390x.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_x86_64.h index 651536c..4a3b3c7 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterInfos_x86_64.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp index de0821e..588015a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp
@@ -1,9 +1,8 @@ //===-- StopInfoMachException.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -38,11 +37,11 @@ target ? target->GetArchitecture().GetMachine() : llvm::Triple::UnknownArch; - const char *exc_desc = NULL; + const char *exc_desc = nullptr; const char *code_label = "code"; - const char *code_desc = NULL; + const char *code_desc = nullptr; const char *subcode_label = "subcode"; - const char *subcode_desc = NULL; + const char *subcode_desc = nullptr; #if defined(__APPLE__) char code_desc_buf[32]; @@ -594,7 +593,7 @@ // the thread ID so we must always report the breakpoint regardless // of the thread. if (bp_site_sp->ValidForThisThread(&thread) || - thread.GetProcess()->GetOperatingSystem() != NULL) + thread.GetProcess()->GetOperatingSystem() != nullptr) return StopInfo::CreateStopReasonWithBreakpointSiteID( thread, bp_site_sp->GetID()); else if (is_trace_if_actual_breakpoint_missing)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.h index 027ed80..74c0581 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/StopInfoMachException.h
@@ -1,9 +1,8 @@ //===-- StopInfoMachException.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,9 +17,7 @@ class StopInfoMachException : public StopInfo { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ StopInfoMachException(Thread &thread, uint32_t exc_type, uint32_t exc_data_count, uint64_t exc_code, uint64_t exc_subcode)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp index 0c7c195..80b04bb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp
@@ -1,14 +1,14 @@ //===-- ThreadMemory.cpp ----------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "Plugins/Process/Utility/ThreadMemory.h" + #include "Plugins/Process/Utility/RegisterContextThreadMemory.h" #include "lldb/Target/OperatingSystem.h" #include "lldb/Target/Process.h" @@ -16,6 +16,8 @@ #include "lldb/Target/StopInfo.h" #include "lldb/Target/Unwind.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -45,8 +47,8 @@ RegisterContextSP ThreadMemory::GetRegisterContext() { if (!m_reg_context_sp) - m_reg_context_sp.reset( - new RegisterContextThreadMemory(*this, m_register_data_addr)); + m_reg_context_sp = std::make_shared<RegisterContextThreadMemory>( + *this, m_register_data_addr); return m_reg_context_sp; }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.h index c966ca0..85bc145 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/ThreadMemory.h
@@ -1,9 +1,8 @@ //===-- ThreadMemory.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.cpp index b34c872..38209fb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.cpp
@@ -1,9 +1,8 @@ //===-- UnwindLLDB.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -51,7 +50,7 @@ return 0; ProcessSP process_sp(m_thread.GetProcess()); - ABI *abi = process_sp ? process_sp->GetABI().get() : NULL; + ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr; while (AddOneMoreFrame(abi)) { #if DEBUG_FRAME_SPEED @@ -74,13 +73,13 @@ return true; ProcessSP process_sp(m_thread.GetProcess()); - ABI *abi = process_sp ? process_sp->GetABI().get() : NULL; + ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr; // First, set up the 0th (initial) frame CursorSP first_cursor_sp(new Cursor()); RegisterContextLLDBSP reg_ctx_sp(new RegisterContextLLDB( m_thread, RegisterContextLLDBSP(), first_cursor_sp->sctx, 0, *this)); - if (reg_ctx_sp.get() == NULL) + if (reg_ctx_sp.get() == nullptr) goto unwind_done; if (!reg_ctx_sp->IsValid()) @@ -148,7 +147,7 @@ return nullptr; } - if (reg_ctx_sp.get() == NULL) { + if (reg_ctx_sp.get() == nullptr) { // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to // that and return true. Subsequent calls to TryFallbackUnwindPlan() will // return false. @@ -403,7 +402,7 @@ } ProcessSP process_sp(m_thread.GetProcess()); - ABI *abi = process_sp ? process_sp->GetABI().get() : NULL; + ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr; while (idx >= m_frames.size() && AddOneMoreFrame(abi)) ; @@ -431,7 +430,7 @@ } ProcessSP process_sp(m_thread.GetProcess()); - ABI *abi = process_sp ? process_sp->GetABI().get() : NULL; + ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr; while (idx >= m_frames.size()) { if (!AddOneMoreFrame(abi))
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.h index aec7b66..c512929 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindLLDB.h
@@ -1,9 +1,8 @@ //===-- UnwindLLDB.h --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -94,7 +93,6 @@ uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation ®loc, uint32_t starting_frame_num, bool pc_register); - //------------------------------------------------------------------ /// Provide the list of user-specified trap handler functions /// /// The Platform is one source of trap handler function names; that @@ -102,10 +100,9 @@ /// into an array of ConstStrings before it can be used - we only want /// to do that once per thread so it's here in the UnwindLLDB object. /// - /// @return + /// \return /// Vector of ConstStrings of trap handler function names. May be /// empty. - //------------------------------------------------------------------ const std::vector<ConstString> &GetUserSpecifiedTrapHandlerFunctionNames() { return m_user_supplied_trap_handler_functions; } @@ -139,12 +136,10 @@ std::vector<ConstString> m_user_supplied_trap_handler_functions; - //----------------------------------------------------------------- // Check if Full UnwindPlan of First frame is valid or not. // If not then try Fallback UnwindPlan of the frame. If Fallback // UnwindPlan succeeds then update the Full UnwindPlan with the // Fallback UnwindPlan. - //----------------------------------------------------------------- void UpdateUnwindPlanForFirstFrameIfInvalid(ABI *abi); CursorSP GetOneMoreFrame(ABI *abi); @@ -153,9 +148,7 @@ bool AddFirstFrame(); - //------------------------------------------------------------------ // For UnwindLLDB only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(UnwindLLDB); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp index ae0b9fb..7dc5a5f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp
@@ -1,9 +1,8 @@ //===-- UnwindMacOSXFrameBackchain.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,6 +17,8 @@ #include "RegisterContextMacOSXFrameBackchain.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -66,8 +67,8 @@ uint32_t concrete_idx = frame->GetConcreteFrameIndex(); const uint32_t frame_count = GetFrameCount(); if (concrete_idx < frame_count) - reg_ctx_sp.reset(new RegisterContextMacOSXFrameBackchain( - m_thread, concrete_idx, m_cursors[concrete_idx])); + reg_ctx_sp = std::make_shared<RegisterContextMacOSXFrameBackchain>( + m_thread, concrete_idx, m_cursors[concrete_idx]); return reg_ctx_sp; } @@ -78,7 +79,7 @@ StackFrame *first_frame = exe_ctx.GetFramePtr(); Process *process = exe_ctx.GetProcessPtr(); - if (process == NULL) + if (process == nullptr) return 0; struct Frame_i386 { @@ -120,7 +121,7 @@ SymbolContext first_frame_sc( first_frame->GetSymbolContext(resolve_scope)); - const AddressRange *addr_range_ptr = NULL; + const AddressRange *addr_range_ptr = nullptr; AddressRange range; if (first_frame_sc.function) addr_range_ptr = &first_frame_sc.function->GetAddressRange(); @@ -168,7 +169,7 @@ m_cursors.clear(); Process *process = exe_ctx.GetProcessPtr(); - if (process == NULL) + if (process == nullptr) return 0; StackFrame *first_frame = exe_ctx.GetFramePtr(); @@ -211,7 +212,7 @@ SymbolContext first_frame_sc( first_frame->GetSymbolContext(resolve_scope)); - const AddressRange *addr_range_ptr = NULL; + const AddressRange *addr_range_ptr = nullptr; AddressRange range; if (first_frame_sc.function) addr_range_ptr = &first_frame_sc.function->GetAddressRange();
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h index 9ee0b08..2208bcc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h
@@ -1,9 +1,8 @@ //===-- UnwindMacOSXFrameBackchain.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -47,9 +46,7 @@ size_t GetStackFrameData_x86_64(const lldb_private::ExecutionContext &exe_ctx); - //------------------------------------------------------------------ // For UnwindMacOSXFrameBackchain only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(UnwindMacOSXFrameBackchain); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm-register-enums.h index 49473bb..39cbf01 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm-register-enums.h
@@ -1,9 +1,8 @@ //===-- lldb-arm-register-enums.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,7 @@ namespace lldb_private { // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -//--------------------------------------------------------------------------- // Internal codes for all ARM registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_arm = 0, gpr_r0_arm = k_first_gpr_arm,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm64-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm64-register-enums.h index 7181ce4..cc414dc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm64-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-arm64-register-enums.h
@@ -1,9 +1,8 @@ //===-- lldb-arm64-register-enums.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,7 @@ namespace lldb_private { // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -//--------------------------------------------------------------------------- // Internal codes for all ARM64 registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_arm64, gpr_x0_arm64 = k_first_gpr_arm64,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-freebsd-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-freebsd-register-enums.h index 6192936..d97f771 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-freebsd-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-freebsd-register-enums.h
@@ -1,9 +1,8 @@ //===-- lldb-mips-freebsd-register-enums.h ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,7 @@ namespace lldb_private { // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -//--------------------------------------------------------------------------- // Internal codes for all mips registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_mips64, gpr_zero_mips64 = k_first_gpr_mips64,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-linux-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-linux-register-enums.h index 0ecf3e3..2f68b80 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-linux-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-mips-linux-register-enums.h
@@ -1,10 +1,9 @@ //===-- lldb-mips-linux-register-enums.h -------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,9 +13,7 @@ namespace lldb_private { // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -//--------------------------------------------------------------------------- // Internal codes for all mips registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_mips, gpr_zero_mips = k_first_gpr_mips, @@ -149,9 +146,7 @@ k_num_msa_registers_mips }; -//--------------------------------------------------------------------------- // Internal codes for all mips64 registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_mips64, gpr_zero_mips64 = k_first_gpr_mips64,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64-register-enums.h index 9ea81c0..6edf7ee 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64-register-enums.h
@@ -1,9 +1,8 @@ //===-- lldb-ppc64-register-enums.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,9 +11,7 @@ // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -// --------------------------------------------------------------------------- // Internal codes for all ppc64 registers. -// --------------------------------------------------------------------------- enum { k_first_gpr_ppc64, gpr_r0_ppc64 = k_first_gpr_ppc64,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64le-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64le-register-enums.h index 675804d..0c381a5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64le-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-ppc64le-register-enums.h
@@ -1,9 +1,8 @@ //===-- lldb-ppc64le-register-enums.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,9 +11,7 @@ // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -// --------------------------------------------------------------------------- // Internal codes for all ppc64le registers. -// --------------------------------------------------------------------------- enum { k_first_gpr_ppc64le, gpr_r0_ppc64le = k_first_gpr_ppc64le,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-s390x-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-s390x-register-enums.h index 65ff92f..bd66261 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-s390x-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-s390x-register-enums.h
@@ -1,9 +1,8 @@ //===-- lldb-s390x-register-enums.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,7 @@ namespace lldb_private { // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -//--------------------------------------------------------------------------- // Internal codes for all s390x registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_s390x, lldb_r0_s390x = k_first_gpr_s390x,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-x86-register-enums.h b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-x86-register-enums.h index 770ec5a..0d2149c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-x86-register-enums.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Utility/lldb-x86-register-enums.h
@@ -1,9 +1,8 @@ //===-- lldb-x86-register-enums.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,9 +12,7 @@ namespace lldb_private { // LLDB register codes (e.g. RegisterKind == eRegisterKindLLDB) -//--------------------------------------------------------------------------- // Internal codes for all i386 registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_i386, lldb_eax_i386 = k_first_gpr_i386, @@ -136,9 +133,7 @@ k_num_mpx_registers_i386, }; -//--------------------------------------------------------------------------- // Internal codes for all x86_64 registers. -//--------------------------------------------------------------------------- enum { k_first_gpr_x86_64, lldb_rax_x86_64 = k_first_gpr_x86_64,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/CMakeLists.txt index 0926290..1d7b8cc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/CMakeLists.txt
@@ -1,29 +1,21 @@ -set(PROC_WINDOWS_COMMON_SOURCES + +add_lldb_library(lldbPluginProcessWindowsCommon PLUGIN DebuggerThread.cpp LocalDebugDelegate.cpp + ProcessDebugger.cpp ProcessWindows.cpp ProcessWindowsLog.cpp RegisterContextWindows.cpp TargetThreadWindows.cpp - ) - -if (CMAKE_SIZEOF_VOID_P EQUAL 4) - set(PROC_WINDOWS_COMMON_SOURCES ${PROC_WINDOWS_COMMON_SOURCES} - x86/RegisterContextWindows_x86.cpp - ) -elseif (CMAKE_SIZEOF_VOID_P EQUAL 8) - set(PROC_WINDOWS_COMMON_SOURCES ${PROC_WINDOWS_COMMON_SOURCES} - x64/RegisterContextWindows_x64.cpp - ) -endif() - -add_lldb_library(lldbPluginProcessWindowsCommon PLUGIN - ${PROC_WINDOWS_COMMON_SOURCES} + x64/RegisterContextWindows_x64.cpp + x86/RegisterContextWindows_x86.cpp + # TODO add support for ARM (NT) and ARM64 LINK_LIBS lldbCore lldbHost lldbInterpreter + lldbPluginDynamicLoaderWindowsDYLD lldbSymbol lldbTarget ws2_32
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.cpp index 81ec258..58769bd 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.cpp
@@ -1,9 +1,8 @@ //===-- DebuggerThread.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,12 +11,12 @@ #include "IDebugDelegate.h" #include "lldb/Core/ModuleSpec.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Host/windows/HostProcessWindows.h" #include "lldb/Host/windows/HostThreadWindows.h" #include "lldb/Host/windows/ProcessLauncherWindows.h" #include "lldb/Target/Process.h" -#include "lldb/Target/ProcessLaunchInfo.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Predicate.h" @@ -64,16 +63,18 @@ Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); LLDB_LOG(log, "launching '{0}'", launch_info.GetExecutableFile().GetPath()); - Status error; + Status result; DebugLaunchContext *context = new DebugLaunchContext(this, launch_info); - HostThread slave_thread(ThreadLauncher::LaunchThread( + + llvm::Expected<HostThread> slave_thread = ThreadLauncher::LaunchThread( "lldb.plugin.process-windows.slave[?]", DebuggerThreadLaunchRoutine, - context, &error)); + context); + if (!slave_thread) { + result = Status(slave_thread.takeError()); + LLDB_LOG(log, "couldn't launch debugger thread. {0}", result); + } - if (!error.Success()) - LLDB_LOG(log, "couldn't launch debugger thread. {0}", error); - - return error; + return result; } Status DebuggerThread::DebugAttach(lldb::pid_t pid, @@ -81,16 +82,18 @@ Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); LLDB_LOG(log, "attaching to '{0}'", pid); - Status error; + Status result; DebugAttachContext *context = new DebugAttachContext(this, pid, attach_info); - HostThread slave_thread(ThreadLauncher::LaunchThread( + + llvm::Expected<HostThread> slave_thread = ThreadLauncher::LaunchThread( "lldb.plugin.process-windows.slave[?]", DebuggerThreadAttachRoutine, - context, &error)); + context); + if (!slave_thread) { + result = Status(slave_thread.takeError()); + LLDB_LOG(log, "couldn't attach to process '{0}'. {1}", pid, result); + } - if (!error.Success()) - LLDB_LOG(log, "couldn't attach to process '{0}'. {1}", pid, error); - - return error; + return result; } lldb::thread_result_t DebuggerThread::DebuggerThreadLaunchRoutine(void *data) { @@ -133,7 +136,7 @@ else m_debug_delegate->OnDebuggerError(error, 0); - return 0; + return {}; } lldb::thread_result_t DebuggerThread::DebuggerThreadAttachRoutine( @@ -149,7 +152,7 @@ if (!DebugActiveProcess((DWORD)pid)) { Status error(::GetLastError(), eErrorTypeWin32); m_debug_delegate->OnDebuggerError(error, 0); - return 0; + return {}; } // The attach was successful, enter the debug loop. From here on out, this @@ -157,7 +160,7 @@ // in DebugLaunch should apply from this point out. DebugLoop(); - return 0; + return {}; } Status DebuggerThread::StopDebugging(bool terminate) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.h index 047d3cc..5670130 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/DebuggerThread.h
@@ -1,9 +1,8 @@ //===-- DebuggerThread.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,12 +20,10 @@ namespace lldb_private { -//---------------------------------------------------------------------- // DebuggerThread // // Debugs a single process, notifying listeners as appropriate when interesting // things occur. -//---------------------------------------------------------------------- class DebuggerThread : public std::enable_shared_from_this<DebuggerThread> { public: DebuggerThread(DebugDelegateSP debug_delegate);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ExceptionRecord.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ExceptionRecord.h index 1eec85d..d1692a6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ExceptionRecord.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ExceptionRecord.h
@@ -1,9 +1,8 @@ //===-- ExceptionRecord.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,12 +18,10 @@ namespace lldb_private { -//---------------------------------------------------------------------- // ExceptionRecord // // ExceptionRecord defines an interface which allows implementors to receive // notification of events that happen in a debugged process. -//---------------------------------------------------------------------- class ExceptionRecord { public: ExceptionRecord(const EXCEPTION_RECORD &record, lldb::tid_t thread_id) { @@ -67,6 +64,8 @@ lldb::tid_t GetThreadID() const { return m_thread_id; } + const std::vector<ULONG_PTR>& GetExceptionArguments() const { return m_arguments; } + private: DWORD m_code; bool m_continuable;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ForwardDecl.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ForwardDecl.h index ce2af3c..ed5ab44 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ForwardDecl.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ForwardDecl.h
@@ -1,9 +1,8 @@ //===-- ForwardDecl.h -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/IDebugDelegate.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/IDebugDelegate.h index 73c285f..aff2dd6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/IDebugDelegate.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/IDebugDelegate.h
@@ -1,9 +1,8 @@ //===-- IDebugDelegate.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,12 +18,10 @@ class Status; class HostThread; -//---------------------------------------------------------------------- // IDebugDelegate // // IDebugDelegate defines an interface which allows implementors to receive // notification of events that happen in a debugged process. -//---------------------------------------------------------------------- class IDebugDelegate { public: virtual ~IDebugDelegate() {}
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.cpp index 92aa7e2..3bb0072 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.cpp
@@ -1,9 +1,8 @@ //===-- LocalDebugDelegate.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.h index 2cb479c..7494dbb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/LocalDebugDelegate.h
@@ -1,9 +1,8 @@ //===-- LocalDebugDelegate.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,6 @@ class ProcessWindows; typedef std::shared_ptr<ProcessWindows> ProcessWindowsSP; -//---------------------------------------------------------------------- // LocalDebugDelegate // // LocalDebugDelegate creates a connection between a ProcessWindows and the @@ -40,7 +38,6 @@ // a ProcessSP (which is exactly what we are trying to decouple from the // driver), so this adapter serves as a way to transparently hold the // ProcessSP while still keeping it decoupled from the driver. -//---------------------------------------------------------------------- class LocalDebugDelegate : public IDebugDelegate { public: explicit LocalDebugDelegate(lldb::ProcessWP process);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/NtStructures.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/NtStructures.h index 6826b98..1eb25b2 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/NtStructures.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/NtStructures.h
@@ -1,9 +1,8 @@ //===-- NtStructures.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessDebugger.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessDebugger.cpp new file mode 100644 index 0000000..6ee882f --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessDebugger.cpp
@@ -0,0 +1,582 @@ +//===-- ProcessDebugger.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 "ProcessDebugger.h" + +// Windows includes +#include "lldb/Host/windows/windows.h" +#include <psapi.h> + +#include "lldb/Host/FileSystem.h" +#include "lldb/Host/HostNativeProcessBase.h" +#include "lldb/Host/HostProcess.h" +#include "lldb/Host/HostThread.h" +#include "lldb/Host/ProcessLaunchInfo.h" +#include "lldb/Target/MemoryRegionInfo.h" +#include "lldb/Target/Process.h" +#include "llvm/Support/ConvertUTF.h" +#include "llvm/Support/Error.h" + +#include "DebuggerThread.h" +#include "ExceptionRecord.h" +#include "ProcessWindowsLog.h" + +using namespace lldb; +using namespace lldb_private; + +static DWORD ConvertLldbToWinApiProtect(uint32_t protect) { + // We also can process a read / write permissions here, but if the debugger + // will make later a write into the allocated memory, it will fail. To get + // around it is possible inside DoWriteMemory to remember memory permissions, + // allow write, write and restore permissions, but for now we process only + // the executable permission. + // + // TODO: Process permissions other than executable + if (protect & ePermissionsExecutable) + return PAGE_EXECUTE_READWRITE; + + return PAGE_READWRITE; +} + +// The Windows page protection bits are NOT independent masks that can be +// bitwise-ORed together. For example, PAGE_EXECUTE_READ is not (PAGE_EXECUTE +// | PAGE_READ). To test for an access type, it's necessary to test for any of +// the bits that provide that access type. +static bool IsPageReadable(uint32_t protect) { + return (protect & PAGE_NOACCESS) == 0; +} + +static bool IsPageWritable(uint32_t protect) { + return (protect & (PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY | + PAGE_READWRITE | PAGE_WRITECOPY)) != 0; +} + +static bool IsPageExecutable(uint32_t protect) { + return (protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | + PAGE_EXECUTE_WRITECOPY)) != 0; +} + +namespace lldb_private { + +lldb::pid_t ProcessDebugger::GetDebuggedProcessId() const { + if (m_session_data) + return m_session_data->m_debugger->GetProcess().GetProcessId(); + return LLDB_INVALID_PROCESS_ID; +} + +Status ProcessDebugger::DetachProcess() { + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); + DebuggerThreadSP debugger_thread; + { + // Acquire the lock only long enough to get the DebuggerThread. + // StopDebugging() will trigger a call back into ProcessDebugger which will + // also acquire the lock. Thus we have to release the lock before calling + // StopDebugging(). + llvm::sys::ScopedLock lock(m_mutex); + + if (!m_session_data) { + LLDB_LOG(log, "there is no active session."); + return Status(); + } + + debugger_thread = m_session_data->m_debugger; + } + + Status error; + + LLDB_LOG(log, "detaching from process {0}.", + debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle()); + error = debugger_thread->StopDebugging(false); + + // By the time StopDebugging returns, there is no more debugger thread, so + // we can be assured that no other thread will race for the session data. + m_session_data.reset(); + + return error; +} + +Status ProcessDebugger::LaunchProcess(ProcessLaunchInfo &launch_info, + DebugDelegateSP delegate) { + // Even though m_session_data is accessed here, it is before a debugger + // thread has been kicked off. So there's no race conditions, and it + // shouldn't be necessary to acquire the mutex. + + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); + Status result; + + FileSpec working_dir = launch_info.GetWorkingDirectory(); + namespace fs = llvm::sys::fs; + if (working_dir) { + FileSystem::Instance().Resolve(working_dir); + if (!FileSystem::Instance().IsDirectory(working_dir)) { + result.SetErrorStringWithFormat("No such file or directory: %s", + working_dir.GetCString()); + return result; + } + } + + if (!launch_info.GetFlags().Test(eLaunchFlagDebug)) { + StreamString stream; + stream.Printf("ProcessDebugger unable to launch '%s'. ProcessDebugger can " + "only be used for debug launches.", + launch_info.GetExecutableFile().GetPath().c_str()); + std::string message = stream.GetString(); + result.SetErrorString(message.c_str()); + + LLDB_LOG(log, "error: {0}", message); + return result; + } + + bool stop_at_entry = launch_info.GetFlags().Test(eLaunchFlagStopAtEntry); + m_session_data.reset(new ProcessWindowsData(stop_at_entry)); + m_session_data->m_debugger.reset(new DebuggerThread(delegate)); + DebuggerThreadSP debugger = m_session_data->m_debugger; + + // Kick off the DebugLaunch asynchronously and wait for it to complete. + result = debugger->DebugLaunch(launch_info); + if (result.Fail()) { + LLDB_LOG(log, "failed launching '{0}'. {1}", + launch_info.GetExecutableFile().GetPath(), result); + return result; + } + + HostProcess process; + Status error = WaitForDebuggerConnection(debugger, process); + if (error.Fail()) { + LLDB_LOG(log, "failed launching '{0}'. {1}", + launch_info.GetExecutableFile().GetPath(), error); + return error; + } + + LLDB_LOG(log, "successfully launched '{0}'", + launch_info.GetExecutableFile().GetPath()); + + // We've hit the initial stop. If eLaunchFlagsStopAtEntry was specified, the + // private state should already be set to eStateStopped as a result of + // hitting the initial breakpoint. If it was not set, the breakpoint should + // have already been resumed from and the private state should already be + // eStateRunning. + launch_info.SetProcessID(process.GetProcessId()); + + return result; +} + +Status ProcessDebugger::AttachProcess(lldb::pid_t pid, + const ProcessAttachInfo &attach_info, + DebugDelegateSP delegate) { + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); + m_session_data.reset( + new ProcessWindowsData(!attach_info.GetContinueOnceAttached())); + DebuggerThreadSP debugger(new DebuggerThread(delegate)); + + m_session_data->m_debugger = debugger; + + DWORD process_id = static_cast<DWORD>(pid); + Status error = debugger->DebugAttach(process_id, attach_info); + if (error.Fail()) { + LLDB_LOG( + log, + "encountered an error occurred initiating the asynchronous attach. {0}", + error); + return error; + } + + HostProcess process; + error = WaitForDebuggerConnection(debugger, process); + if (error.Fail()) { + LLDB_LOG(log, + "encountered an error waiting for the debugger to connect. {0}", + error); + return error; + } + + LLDB_LOG(log, "successfully attached to process with pid={0}", process_id); + + // We've hit the initial stop. If eLaunchFlagsStopAtEntry was specified, the + // private state should already be set to eStateStopped as a result of + // hitting the initial breakpoint. If it was not set, the breakpoint should + // have already been resumed from and the private state should already be + // eStateRunning. + + return error; +} + +Status ProcessDebugger::DestroyProcess(const lldb::StateType state) { + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); + DebuggerThreadSP debugger_thread; + { + // Acquire this lock inside an inner scope, only long enough to get the + // DebuggerThread. StopDebugging() will trigger a call back into + // ProcessDebugger which will acquire the lock again, so we need to not + // deadlock. + llvm::sys::ScopedLock lock(m_mutex); + + if (!m_session_data) { + LLDB_LOG(log, "warning: state = {0}, but there is no active session.", + state); + return Status(); + } + + debugger_thread = m_session_data->m_debugger; + } + + Status error; + if (state != eStateExited && state != eStateDetached) { + LLDB_LOG( + log, "Shutting down process {0}.", + debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle()); + error = debugger_thread->StopDebugging(true); + + // By the time StopDebugging returns, there is no more debugger thread, so + // we can be assured that no other thread will race for the session data. + m_session_data.reset(); + } else { + error.SetErrorStringWithFormat("cannot destroy process %" PRIx64 + " while state = %d", + GetDebuggedProcessId(), state); + LLDB_LOG(log, "error: {0}", error); + } + return error; +} + +Status ProcessDebugger::HaltProcess(bool &caused_stop) { + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); + Status error; + llvm::sys::ScopedLock lock(m_mutex); + caused_stop = ::DebugBreakProcess(m_session_data->m_debugger->GetProcess() + .GetNativeProcess() + .GetSystemHandle()); + if (!caused_stop) { + error.SetError(::GetLastError(), eErrorTypeWin32); + LLDB_LOG(log, "DebugBreakProcess failed with error {0}", error); + } + + return error; +} + +Status ProcessDebugger::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, + size_t &bytes_read) { + Status error; + bytes_read = 0; + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); + llvm::sys::ScopedLock lock(m_mutex); + + if (!m_session_data) { + error.SetErrorString( + "cannot read, there is no active debugger connection."); + LLDB_LOG(log, "error: {0}", error); + return error; + } + + LLDB_LOG(log, "attempting to read {0} bytes from address {1:x}", size, + vm_addr); + + HostProcess process = m_session_data->m_debugger->GetProcess(); + void *addr = reinterpret_cast<void *>(vm_addr); + SIZE_T num_of_bytes_read = 0; + if (!::ReadProcessMemory(process.GetNativeProcess().GetSystemHandle(), addr, + buf, size, &num_of_bytes_read)) { + // Reading from the process can fail for a number of reasons - set the + // error code and make sure that the number of bytes read is set back to 0 + // because in some scenarios the value of bytes_read returned from the API + // is garbage. + error.SetError(GetLastError(), eErrorTypeWin32); + LLDB_LOG(log, "reading failed with error: {0}", error); + } else { + bytes_read = num_of_bytes_read; + } + return error; +} + +Status ProcessDebugger::WriteMemory(lldb::addr_t vm_addr, const void *buf, + size_t size, size_t &bytes_written) { + Status error; + bytes_written = 0; + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); + llvm::sys::ScopedLock lock(m_mutex); + LLDB_LOG(log, "attempting to write {0} bytes into address {1:x}", size, + vm_addr); + + if (!m_session_data) { + error.SetErrorString( + "cannot write, there is no active debugger connection."); + LLDB_LOG(log, "error: {0}", error); + return error; + } + + HostProcess process = m_session_data->m_debugger->GetProcess(); + void *addr = reinterpret_cast<void *>(vm_addr); + SIZE_T num_of_bytes_written = 0; + lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); + if (::WriteProcessMemory(handle, addr, buf, size, &num_of_bytes_written)) { + FlushInstructionCache(handle, addr, num_of_bytes_written); + bytes_written = num_of_bytes_written; + } else { + error.SetError(GetLastError(), eErrorTypeWin32); + LLDB_LOG(log, "writing failed with error: {0}", error); + } + return error; +} + +Status ProcessDebugger::AllocateMemory(size_t size, uint32_t permissions, + lldb::addr_t &addr) { + Status error; + addr = LLDB_INVALID_ADDRESS; + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); + llvm::sys::ScopedLock lock(m_mutex); + LLDB_LOG(log, "attempting to allocate {0} bytes with permissions {1}", size, + permissions); + + if (!m_session_data) { + error.SetErrorString( + "cannot allocate, there is no active debugger connection"); + LLDB_LOG(log, "error: {0}", error); + return error; + } + + HostProcess process = m_session_data->m_debugger->GetProcess(); + lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); + auto protect = ConvertLldbToWinApiProtect(permissions); + auto result = ::VirtualAllocEx(handle, nullptr, size, MEM_COMMIT, protect); + if (!result) { + error.SetError(GetLastError(), eErrorTypeWin32); + LLDB_LOG(log, "allocating failed with error: {0}", error); + } else { + addr = reinterpret_cast<addr_t>(result); + } + return error; +} + +Status ProcessDebugger::DeallocateMemory(lldb::addr_t vm_addr) { + Status result; + + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); + llvm::sys::ScopedLock lock(m_mutex); + LLDB_LOG(log, "attempting to deallocate bytes at address {0}", vm_addr); + + if (!m_session_data) { + result.SetErrorString( + "cannot deallocate, there is no active debugger connection"); + LLDB_LOG(log, "error: {0}", result); + return result; + } + + HostProcess process = m_session_data->m_debugger->GetProcess(); + lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); + if (!::VirtualFreeEx(handle, reinterpret_cast<LPVOID>(vm_addr), 0, + MEM_RELEASE)) { + result.SetError(GetLastError(), eErrorTypeWin32); + LLDB_LOG(log, "deallocating failed with error: {0}", result); + } + + return result; +} + +Status ProcessDebugger::GetMemoryRegionInfo(lldb::addr_t vm_addr, + MemoryRegionInfo &info) { + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); + Status error; + llvm::sys::ScopedLock lock(m_mutex); + info.Clear(); + + if (!m_session_data) { + error.SetErrorString( + "GetMemoryRegionInfo called with no debugging session."); + LLDB_LOG(log, "error: {0}", error); + return error; + } + HostProcess process = m_session_data->m_debugger->GetProcess(); + lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); + if (handle == nullptr || handle == LLDB_INVALID_PROCESS) { + error.SetErrorString( + "GetMemoryRegionInfo called with an invalid target process."); + LLDB_LOG(log, "error: {0}", error); + return error; + } + + LLDB_LOG(log, "getting info for address {0:x}", vm_addr); + + void *addr = reinterpret_cast<void *>(vm_addr); + MEMORY_BASIC_INFORMATION mem_info = {}; + SIZE_T result = ::VirtualQueryEx(handle, addr, &mem_info, sizeof(mem_info)); + if (result == 0) { + if (::GetLastError() == ERROR_INVALID_PARAMETER) { + // ERROR_INVALID_PARAMETER is returned if VirtualQueryEx is called with + // an address past the highest accessible address. We should return a + // range from the vm_addr to LLDB_INVALID_ADDRESS + info.GetRange().SetRangeBase(vm_addr); + info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); + info.SetReadable(MemoryRegionInfo::eNo); + info.SetExecutable(MemoryRegionInfo::eNo); + info.SetWritable(MemoryRegionInfo::eNo); + info.SetMapped(MemoryRegionInfo::eNo); + return error; + } else { + error.SetError(::GetLastError(), eErrorTypeWin32); + LLDB_LOG(log, + "VirtualQueryEx returned error {0} while getting memory " + "region info for address {1:x}", + error, vm_addr); + return error; + } + } + + // Protect bits are only valid for MEM_COMMIT regions. + if (mem_info.State == MEM_COMMIT) { + const bool readable = IsPageReadable(mem_info.Protect); + const bool executable = IsPageExecutable(mem_info.Protect); + const bool writable = IsPageWritable(mem_info.Protect); + info.SetReadable(readable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo); + info.SetExecutable(executable ? MemoryRegionInfo::eYes + : MemoryRegionInfo::eNo); + info.SetWritable(writable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo); + } else { + info.SetReadable(MemoryRegionInfo::eNo); + info.SetExecutable(MemoryRegionInfo::eNo); + info.SetWritable(MemoryRegionInfo::eNo); + } + + // AllocationBase is defined for MEM_COMMIT and MEM_RESERVE but not MEM_FREE. + if (mem_info.State != MEM_FREE) { + info.GetRange().SetRangeBase( + reinterpret_cast<addr_t>(mem_info.AllocationBase)); + info.GetRange().SetRangeEnd(reinterpret_cast<addr_t>(mem_info.BaseAddress) + + mem_info.RegionSize); + info.SetMapped(MemoryRegionInfo::eYes); + } else { + // In the unmapped case we need to return the distance to the next block of + // memory. VirtualQueryEx nearly does that except that it gives the + // distance from the start of the page containing vm_addr. + SYSTEM_INFO data; + ::GetSystemInfo(&data); + DWORD page_offset = vm_addr % data.dwPageSize; + info.GetRange().SetRangeBase(vm_addr); + info.GetRange().SetByteSize(mem_info.RegionSize - page_offset); + info.SetMapped(MemoryRegionInfo::eNo); + } + + error.SetError(::GetLastError(), eErrorTypeWin32); + LLDB_LOGV(log, + "Memory region info for address {0}: readable={1}, " + "executable={2}, writable={3}", + vm_addr, info.GetReadable(), info.GetExecutable(), + info.GetWritable()); + return error; +} + +void ProcessDebugger::OnExitProcess(uint32_t exit_code) { + // If the process exits before any initial stop then notify the debugger + // of the error otherwise WaitForDebuggerConnection() will be blocked. + // An example of this issue is when a process fails to load a dependent DLL. + if (m_session_data && !m_session_data->m_initial_stop_received) { + Status error(exit_code, eErrorTypeWin32); + OnDebuggerError(error, 0); + } +} + +void ProcessDebugger::OnDebuggerConnected(lldb::addr_t image_base) {} + +ExceptionResult +ProcessDebugger::OnDebugException(bool first_chance, + const ExceptionRecord &record) { + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION); + llvm::sys::ScopedLock lock(m_mutex); + // FIXME: Without this check, occasionally when running the test suite + // there is an issue where m_session_data can be null. It's not clear how + // this could happen but it only surfaces while running the test suite. In + // order to properly diagnose this, we probably need to first figure allow the + // test suite to print out full lldb logs, and then add logging to the process + // plugin. + if (!m_session_data) { + LLDB_LOG(log, + "Debugger thread reported exception {0:x} at address {1:x}, but " + "there is no session.", + record.GetExceptionCode(), record.GetExceptionAddress()); + return ExceptionResult::SendToApplication; + } + + ExceptionResult result = ExceptionResult::SendToApplication; + if ((record.GetExceptionCode() == EXCEPTION_BREAKPOINT || + record.GetExceptionCode() == + 0x4000001FL /*WOW64 STATUS_WX86_BREAKPOINT*/) && + !m_session_data->m_initial_stop_received) { + // Handle breakpoints at the first chance. + result = ExceptionResult::BreakInDebugger; + LLDB_LOG( + log, + "Hit loader breakpoint at address {0:x}, setting initial stop event.", + record.GetExceptionAddress()); + m_session_data->m_initial_stop_received = true; + ::SetEvent(m_session_data->m_initial_stop_event); + } + return result; +} + +void ProcessDebugger::OnCreateThread(const HostThread &thread) { + // Do nothing by default +} + +void ProcessDebugger::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) { + // Do nothing by default +} + +void ProcessDebugger::OnLoadDll(const ModuleSpec &module_spec, + lldb::addr_t module_addr) { + // Do nothing by default +} + +void ProcessDebugger::OnUnloadDll(lldb::addr_t module_addr) { + // Do nothing by default +} + +void ProcessDebugger::OnDebugString(const std::string &string) {} + +void ProcessDebugger::OnDebuggerError(const Status &error, uint32_t type) { + llvm::sys::ScopedLock lock(m_mutex); + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); + + if (m_session_data->m_initial_stop_received) { + // This happened while debugging. Do we shutdown the debugging session, + // try to continue, or do something else? + LLDB_LOG(log, + "Error {0} occurred during debugging. Unexpected behavior " + "may result. {1}", + error.GetError(), error); + } else { + // If we haven't actually launched the process yet, this was an error + // launching the process. Set the internal error and signal the initial + // stop event so that the DoLaunch method wakes up and returns a failure. + m_session_data->m_launch_error = error; + ::SetEvent(m_session_data->m_initial_stop_event); + LLDB_LOG(log, + "Error {0} occurred launching the process before the initial " + "stop. {1}", + error.GetError(), error); + return; + } +} + +Status ProcessDebugger::WaitForDebuggerConnection(DebuggerThreadSP debugger, + HostProcess &process) { + Status result; + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS | + WINDOWS_LOG_BREAKPOINTS); + LLDB_LOG(log, "Waiting for loader breakpoint."); + + // Block this function until we receive the initial stop from the process. + if (::WaitForSingleObject(m_session_data->m_initial_stop_event, INFINITE) == + WAIT_OBJECT_0) { + LLDB_LOG(log, "hit loader breakpoint, returning."); + + process = debugger->GetProcess(); + return m_session_data->m_launch_error; + } else + return Status(::GetLastError(), eErrorTypeWin32); +} + +} // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessDebugger.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessDebugger.h new file mode 100644 index 0000000..fd0b0e5 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessDebugger.h
@@ -0,0 +1,101 @@ +//===-- ProcessDebugger.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 liblldb_ProcessDebugger_h_ +#define liblldb_ProcessDebugger_h_ + +#include "lldb/Host/windows/windows.h" + +#include "lldb/Utility/Status.h" +#include "lldb/lldb-forward.h" +#include "lldb/lldb-types.h" +#include "llvm/Support/Mutex.h" + +#include "ForwardDecl.h" +#include <map> +#include <set> + +namespace lldb_private { + +class HostProcess; +class HostThread; +class ProcessLaunchInfo; +class ProcessAttachInfo; + +class ProcessWindowsData { +public: + ProcessWindowsData(bool stop_at_entry) : m_stop_at_entry(stop_at_entry) { + m_initial_stop_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr); + } + + ~ProcessWindowsData() { ::CloseHandle(m_initial_stop_event); } + + Status m_launch_error; + DebuggerThreadSP m_debugger; + // StopInfoSP m_pending_stop_info; + HANDLE m_initial_stop_event = nullptr; + bool m_initial_stop_received = false; + bool m_stop_at_entry; + std::map<lldb::tid_t, HostThread> m_new_threads; + std::set<lldb::tid_t> m_exited_threads; +}; + +class ProcessDebugger { + +public: + virtual void OnExitProcess(uint32_t exit_code); + virtual void OnDebuggerConnected(lldb::addr_t image_base); + virtual ExceptionResult OnDebugException(bool first_chance, + const ExceptionRecord &record); + virtual void OnCreateThread(const HostThread &thread); + virtual void OnExitThread(lldb::tid_t thread_id, uint32_t exit_code); + virtual void OnLoadDll(const ModuleSpec &module_spec, + lldb::addr_t module_addr); + virtual void OnUnloadDll(lldb::addr_t module_addr); + virtual void OnDebugString(const std::string &string); + virtual void OnDebuggerError(const Status &error, uint32_t type); + +protected: + Status DetachProcess(); + + Status LaunchProcess(ProcessLaunchInfo &launch_info, + DebugDelegateSP delegate); + + Status AttachProcess(lldb::pid_t pid, const ProcessAttachInfo &attach_info, + DebugDelegateSP delegate); + + Status DestroyProcess(lldb::StateType process_state); + + Status HaltProcess(bool &caused_stop); + + Status GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info); + + Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, + size_t &bytes_read); + + Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, + size_t &bytes_written); + + Status AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr); + + Status DeallocateMemory(lldb::addr_t addr); + + lldb::pid_t GetDebuggedProcessId() const; + + Status WaitForDebuggerConnection(DebuggerThreadSP debugger, + HostProcess &process); + +protected: + llvm::sys::Mutex m_mutex; + std::unique_ptr<ProcessWindowsData> m_session_data; +}; + +} // namespace lldb_private + +#endif // #ifndef liblldb_ProcessDebugger_h_
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.cpp index 3fe5ab7..49801fe 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.cpp
@@ -1,9 +1,8 @@ //===-- ProcessWindows.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -71,46 +70,10 @@ } return file_name; } - -DWORD ConvertLldbToWinApiProtect(uint32_t protect) { - // We also can process a read / write permissions here, but if the debugger - // will make later a write into the allocated memory, it will fail. To get - // around it is possible inside DoWriteMemory to remember memory permissions, - // allow write, write and restore permissions, but for now we process only - // the executable permission. - // - // TODO: Process permissions other than executable - if (protect & ePermissionsExecutable) - return PAGE_EXECUTE_READWRITE; - - return PAGE_READWRITE; -} - } // anonymous namespace namespace lldb_private { -// We store a pointer to this class in the ProcessWindows, so that we don't -// expose Windows-specific types and implementation details from a public -// header file. -class ProcessWindowsData { -public: - ProcessWindowsData(bool stop_at_entry) : m_stop_at_entry(stop_at_entry) { - m_initial_stop_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr); - } - - ~ProcessWindowsData() { ::CloseHandle(m_initial_stop_event); } - - Status m_launch_error; - DebuggerThreadSP m_debugger; - StopInfoSP m_pending_stop_info; - HANDLE m_initial_stop_event = nullptr; - bool m_initial_stop_received = false; - bool m_stop_at_entry; - std::map<lldb::tid_t, HostThread> m_new_threads; - std::set<lldb::tid_t> m_exited_threads; -}; - ProcessSP ProcessWindows::CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *) { @@ -137,7 +100,6 @@ return "Process plugin for Windows"; } -//------------------------------------------------------------------------------ // Constructors and destructors. ProcessWindows::ProcessWindows(lldb::TargetSP target_sp, @@ -162,7 +124,6 @@ return 0; } -//------------------------------------------------------------------------------ // ProcessInterface protocol. lldb_private::ConstString ProcessWindows::GetPluginName() { @@ -195,159 +156,41 @@ } Status ProcessWindows::DoDetach(bool keep_stopped) { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); - DebuggerThreadSP debugger_thread; - StateType private_state; - { - // Acquire the lock only long enough to get the DebuggerThread. - // StopDebugging() will trigger a call back into ProcessWindows which will - // also acquire the lock. Thus we have to release the lock before calling - // StopDebugging(). - llvm::sys::ScopedLock lock(m_mutex); - - private_state = GetPrivateState(); - - if (!m_session_data) { - LLDB_LOG(log, "state = {0}, but there is no active session.", - private_state); - return Status(); - } - - debugger_thread = m_session_data->m_debugger; - } - Status error; + Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); + StateType private_state = GetPrivateState(); if (private_state != eStateExited && private_state != eStateDetached) { - LLDB_LOG(log, "detaching from process {0} while state = {1}.", - debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(), - private_state); - error = debugger_thread->StopDebugging(false); - if (error.Success()) { + error = DetachProcess(); + if (error.Success()) SetPrivateState(eStateDetached); - } - - // By the time StopDebugging returns, there is no more debugger thread, so - // we can be assured that no other thread will race for the session data. - m_session_data.reset(); + else + LLDB_LOG(log, "Detaching process error: {0}", error); } else { - LLDB_LOG( - log, - "error: process {0} in state = {1}, but cannot destroy in this state.", - debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(), - private_state); + error.SetErrorStringWithFormat("error: process {0} in state = {1}, but " + "cannot detach it in this state.", + GetID(), private_state); + LLDB_LOG(log, "error: {0}", error); } - return error; } Status ProcessWindows::DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) { - // Even though m_session_data is accessed here, it is before a debugger - // thread has been kicked off. So there's no race conditions, and it - // shouldn't be necessary to acquire the mutex. - - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); - Status result; - - FileSpec working_dir = launch_info.GetWorkingDirectory(); - namespace fs = llvm::sys::fs; - if (working_dir) { - FileSystem::Instance().Resolve(working_dir); - if (!FileSystem::Instance().IsDirectory(working_dir)) { - result.SetErrorStringWithFormat("No such file or directory: %s", - working_dir.GetCString()); - return result; - } - } - - if (!launch_info.GetFlags().Test(eLaunchFlagDebug)) { - StreamString stream; - stream.Printf("ProcessWindows unable to launch '%s'. ProcessWindows can " - "only be used for debug launches.", - launch_info.GetExecutableFile().GetPath().c_str()); - std::string message = stream.GetString(); - result.SetErrorString(message.c_str()); - - LLDB_LOG(log, "error: {0}", message); - return result; - } - - bool stop_at_entry = launch_info.GetFlags().Test(eLaunchFlagStopAtEntry); - m_session_data.reset(new ProcessWindowsData(stop_at_entry)); - + Status error; DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this())); - m_session_data->m_debugger.reset(new DebuggerThread(delegate)); - DebuggerThreadSP debugger = m_session_data->m_debugger; - - // Kick off the DebugLaunch asynchronously and wait for it to complete. - result = debugger->DebugLaunch(launch_info); - if (result.Fail()) { - LLDB_LOG(log, "failed launching '{0}'. {1}", - launch_info.GetExecutableFile().GetPath(), result); - return result; - } - - HostProcess process; - Status error = WaitForDebuggerConnection(debugger, process); - if (error.Fail()) { - LLDB_LOG(log, "failed launching '{0}'. {1}", - launch_info.GetExecutableFile().GetPath(), error); - return error; - } - - LLDB_LOG(log, "successfully launched '{0}'", - launch_info.GetExecutableFile().GetPath()); - - // We've hit the initial stop. If eLaunchFlagsStopAtEntry was specified, the - // private state should already be set to eStateStopped as a result of - // hitting the initial breakpoint. If it was not set, the breakpoint should - // have already been resumed from and the private state should already be - // eStateRunning. - launch_info.SetProcessID(process.GetProcessId()); - SetID(process.GetProcessId()); - - return result; + error = LaunchProcess(launch_info, delegate); + if (error.Success()) + SetID(launch_info.GetProcessID()); + return error; } Status ProcessWindows::DoAttachToProcessWithID(lldb::pid_t pid, const ProcessAttachInfo &attach_info) { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); - m_session_data.reset( - new ProcessWindowsData(!attach_info.GetContinueOnceAttached())); - DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this())); - DebuggerThreadSP debugger(new DebuggerThread(delegate)); - - m_session_data->m_debugger = debugger; - - DWORD process_id = static_cast<DWORD>(pid); - Status error = debugger->DebugAttach(process_id, attach_info); - if (error.Fail()) { - LLDB_LOG( - log, - "encountered an error occurred initiating the asynchronous attach. {0}", - error); - return error; - } - - HostProcess process; - error = WaitForDebuggerConnection(debugger, process); - if (error.Fail()) { - LLDB_LOG(log, - "encountered an error waiting for the debugger to connect. {0}", - error); - return error; - } - - LLDB_LOG(log, "successfully attached to process with pid={0}", process_id); - - // We've hit the initial stop. If eLaunchFlagsStopAtEntry was specified, the - // private state should already be set to eStateStopped as a result of - // hitting the initial breakpoint. If it was not set, the breakpoint should - // have already been resumed from and the private state should already be - // eStateRunning. - SetID(process.GetProcessId()); + Status error = AttachProcess(pid, attach_info, delegate); + if (error.Success()) + SetID(GetDebuggedProcessId()); return error; } @@ -403,63 +246,16 @@ } Status ProcessWindows::DoDestroy() { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); - DebuggerThreadSP debugger_thread; - StateType private_state; - { - // Acquire this lock inside an inner scope, only long enough to get the - // DebuggerThread. StopDebugging() will trigger a call back into - // ProcessWindows which will acquire the lock again, so we need to not - // deadlock. - llvm::sys::ScopedLock lock(m_mutex); - - private_state = GetPrivateState(); - - if (!m_session_data) { - LLDB_LOG(log, "warning: state = {0}, but there is no active session.", - private_state); - return Status(); - } - - debugger_thread = m_session_data->m_debugger; - } - - Status error; - if (private_state != eStateExited && private_state != eStateDetached) { - LLDB_LOG(log, "Shutting down process {0} while state = {1}.", - debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(), - private_state); - error = debugger_thread->StopDebugging(true); - - // By the time StopDebugging returns, there is no more debugger thread, so - // we can be assured that no other thread will race for the session data. - m_session_data.reset(); - } else { - LLDB_LOG(log, "cannot destroy process {0} while state = {1}", - debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(), - private_state); - } - - return error; + StateType private_state = GetPrivateState(); + return DestroyProcess(private_state); } Status ProcessWindows::DoHalt(bool &caused_stop) { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); - Status error; StateType state = GetPrivateState(); - if (state == eStateStopped) - caused_stop = false; - else { - llvm::sys::ScopedLock lock(m_mutex); - caused_stop = ::DebugBreakProcess(m_session_data->m_debugger->GetProcess() - .GetNativeProcess() - .GetSystemHandle()); - if (!caused_stop) { - error.SetError(::GetLastError(), eErrorTypeWin32); - LLDB_LOG(log, "DebugBreakProcess failed with error {0}", error); - } - } - return error; + if (state != eStateStopped) + return HaltProcess(caused_stop); + caused_stop = false; + return Status(); } void ProcessWindows::DidLaunch() { @@ -477,6 +273,74 @@ RefreshStateAfterStop(); } +static void +DumpAdditionalExceptionInformation(llvm::raw_ostream &stream, + const ExceptionRecordSP &exception) { + // Decode additional exception information for specific exception types based + // on + // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_exception_record + + const int addr_min_width = 2 + 8; // "0x" + 4 address bytes + + const std::vector<ULONG_PTR> &args = exception->GetExceptionArguments(); + switch (exception->GetExceptionCode()) { + case EXCEPTION_ACCESS_VIOLATION: { + if (args.size() < 2) + break; + + stream << ": "; + const int access_violation_code = args[0]; + const lldb::addr_t access_violation_address = args[1]; + switch (access_violation_code) { + case 0: + stream << "Access violation reading"; + break; + case 1: + stream << "Access violation writing"; + break; + case 8: + stream << "User-mode data execution prevention (DEP) violation at"; + break; + default: + stream << "Unknown access violation (code " << access_violation_code + << ") at"; + break; + } + stream << " location " + << llvm::format_hex(access_violation_address, addr_min_width); + break; + } + case EXCEPTION_IN_PAGE_ERROR: { + if (args.size() < 3) + break; + + stream << ": "; + const int page_load_error_code = args[0]; + const lldb::addr_t page_load_error_address = args[1]; + const DWORD underlying_code = args[2]; + switch (page_load_error_code) { + case 0: + stream << "In page error reading"; + break; + case 1: + stream << "In page error writing"; + break; + case 8: + stream << "User-mode data execution prevention (DEP) violation at"; + break; + default: + stream << "Unknown page loading error (code " << page_load_error_code + << ") at"; + break; + } + stream << " location " + << llvm::format_hex(page_load_error_address, addr_min_width) + << " (status code " << llvm::format_hex(underlying_code, 8) << ")"; + break; + } + } +} + void ProcessWindows::RefreshStateAfterStop() { Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION); llvm::sys::ScopedLock lock(m_mutex); @@ -566,6 +430,7 @@ "Creating stop info with the exception."); // FALLTHROUGH: We'll treat this as a generic exception record in the // default case. + LLVM_FALLTHROUGH; } } @@ -576,6 +441,8 @@ << llvm::format_hex(active_exception->GetExceptionCode(), 8) << " encountered at address " << llvm::format_hex(active_exception->GetExceptionAddress(), 8); + DumpAdditionalExceptionInformation(desc_stream, active_exception); + stop_info = StopInfo::CreateStopReasonWithException( *stop_thread, desc_stream.str().c_str()); stop_thread->SetStopInfo(stop_info); @@ -661,198 +528,32 @@ size_t ProcessWindows::DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error) { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); - llvm::sys::ScopedLock lock(m_mutex); - - if (!m_session_data) - return 0; - - LLDB_LOG(log, "attempting to read {0} bytes from address {1:x}", size, - vm_addr); - - HostProcess process = m_session_data->m_debugger->GetProcess(); - void *addr = reinterpret_cast<void *>(vm_addr); - SIZE_T bytes_read = 0; - if (!ReadProcessMemory(process.GetNativeProcess().GetSystemHandle(), addr, - buf, size, &bytes_read)) { - // Reading from the process can fail for a number of reasons - set the - // error code and make sure that the number of bytes read is set back to 0 - // because in some scenarios the value of bytes_read returned from the API - // is garbage. - error.SetError(GetLastError(), eErrorTypeWin32); - LLDB_LOG(log, "reading failed with error: {0}", error); - bytes_read = 0; - } + size_t bytes_read = 0; + error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read); return bytes_read; } size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error) { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); - llvm::sys::ScopedLock lock(m_mutex); - LLDB_LOG(log, "attempting to write {0} bytes into address {1:x}", size, - vm_addr); - - if (!m_session_data) { - LLDB_LOG(log, "cannot write, there is no active debugger connection."); - return 0; - } - - HostProcess process = m_session_data->m_debugger->GetProcess(); - void *addr = reinterpret_cast<void *>(vm_addr); - SIZE_T bytes_written = 0; - lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); - if (WriteProcessMemory(handle, addr, buf, size, &bytes_written)) - FlushInstructionCache(handle, addr, bytes_written); - else { - error.SetError(GetLastError(), eErrorTypeWin32); - LLDB_LOG(log, "writing failed with error: {0}", error); - } + size_t bytes_written = 0; + error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written); return bytes_written; } lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions, Status &error) { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); - llvm::sys::ScopedLock lock(m_mutex); - LLDB_LOG(log, "attempting to allocate {0} bytes with permissions {1}", size, - permissions); - - if (!m_session_data) { - LLDB_LOG(log, "cannot allocate, there is no active debugger connection."); - error.SetErrorString( - "cannot allocate, there is no active debugger connection"); - return LLDB_INVALID_ADDRESS; - } - - HostProcess process = m_session_data->m_debugger->GetProcess(); - lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); - auto protect = ConvertLldbToWinApiProtect(permissions); - auto result = VirtualAllocEx(handle, nullptr, size, MEM_COMMIT, protect); - if (!result) { - error.SetError(GetLastError(), eErrorTypeWin32); - LLDB_LOG(log, "allocating failed with error: {0}", error); - return LLDB_INVALID_ADDRESS; - } - - return reinterpret_cast<addr_t>(result); + lldb::addr_t vm_addr = LLDB_INVALID_ADDRESS; + error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr); + return vm_addr; } Status ProcessWindows::DoDeallocateMemory(lldb::addr_t ptr) { - Status result; - - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); - llvm::sys::ScopedLock lock(m_mutex); - LLDB_LOG(log, "attempting to deallocate bytes at address {0}", ptr); - - if (!m_session_data) { - LLDB_LOG(log, "cannot deallocate, there is no active debugger connection."); - result.SetErrorString( - "cannot deallocate, there is no active debugger connection"); - return result; - } - - HostProcess process = m_session_data->m_debugger->GetProcess(); - lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); - if (!VirtualFreeEx(handle, reinterpret_cast<LPVOID>(ptr), 0, MEM_RELEASE)) { - result.SetError(GetLastError(), eErrorTypeWin32); - LLDB_LOG(log, "deallocating failed with error: {0}", result); - return result; - } - - return result; + return ProcessDebugger::DeallocateMemory(ptr); } Status ProcessWindows::GetMemoryRegionInfo(lldb::addr_t vm_addr, MemoryRegionInfo &info) { - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); - Status error; - llvm::sys::ScopedLock lock(m_mutex); - info.Clear(); - - if (!m_session_data) { - error.SetErrorString( - "GetMemoryRegionInfo called with no debugging session."); - LLDB_LOG(log, "error: {0}", error); - return error; - } - HostProcess process = m_session_data->m_debugger->GetProcess(); - lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); - if (handle == nullptr || handle == LLDB_INVALID_PROCESS) { - error.SetErrorString( - "GetMemoryRegionInfo called with an invalid target process."); - LLDB_LOG(log, "error: {0}", error); - return error; - } - - LLDB_LOG(log, "getting info for address {0:x}", vm_addr); - - void *addr = reinterpret_cast<void *>(vm_addr); - MEMORY_BASIC_INFORMATION mem_info = {}; - SIZE_T result = ::VirtualQueryEx(handle, addr, &mem_info, sizeof(mem_info)); - if (result == 0) { - if (::GetLastError() == ERROR_INVALID_PARAMETER) { - // ERROR_INVALID_PARAMETER is returned if VirtualQueryEx is called with - // an address past the highest accessible address. We should return a - // range from the vm_addr to LLDB_INVALID_ADDRESS - info.GetRange().SetRangeBase(vm_addr); - info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); - info.SetReadable(MemoryRegionInfo::eNo); - info.SetExecutable(MemoryRegionInfo::eNo); - info.SetWritable(MemoryRegionInfo::eNo); - info.SetMapped(MemoryRegionInfo::eNo); - return error; - } else { - error.SetError(::GetLastError(), eErrorTypeWin32); - LLDB_LOG(log, - "VirtualQueryEx returned error {0} while getting memory " - "region info for address {1:x}", - error, vm_addr); - return error; - } - } - - // Protect bits are only valid for MEM_COMMIT regions. - if (mem_info.State == MEM_COMMIT) { - const bool readable = IsPageReadable(mem_info.Protect); - const bool executable = IsPageExecutable(mem_info.Protect); - const bool writable = IsPageWritable(mem_info.Protect); - info.SetReadable(readable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo); - info.SetExecutable(executable ? MemoryRegionInfo::eYes - : MemoryRegionInfo::eNo); - info.SetWritable(writable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo); - } else { - info.SetReadable(MemoryRegionInfo::eNo); - info.SetExecutable(MemoryRegionInfo::eNo); - info.SetWritable(MemoryRegionInfo::eNo); - } - - // AllocationBase is defined for MEM_COMMIT and MEM_RESERVE but not MEM_FREE. - if (mem_info.State != MEM_FREE) { - info.GetRange().SetRangeBase( - reinterpret_cast<addr_t>(mem_info.AllocationBase)); - info.GetRange().SetRangeEnd(reinterpret_cast<addr_t>(mem_info.BaseAddress) + - mem_info.RegionSize); - info.SetMapped(MemoryRegionInfo::eYes); - } else { - // In the unmapped case we need to return the distance to the next block of - // memory. VirtualQueryEx nearly does that except that it gives the - // distance from the start of the page containing vm_addr. - SYSTEM_INFO data; - GetSystemInfo(&data); - DWORD page_offset = vm_addr % data.dwPageSize; - info.GetRange().SetRangeBase(vm_addr); - info.GetRange().SetByteSize(mem_info.RegionSize - page_offset); - info.SetMapped(MemoryRegionInfo::eNo); - } - - error.SetError(::GetLastError(), eErrorTypeWin32); - LLDB_LOGV(log, - "Memory region info for address {0}: readable={1}, " - "executable={2}, writable={3}", - vm_addr, info.GetReadable(), info.GetExecutable(), - info.GetWritable()); - return error; + return ProcessDebugger::GetMemoryRegionInfo(vm_addr, info); } lldb::addr_t ProcessWindows::GetImageInfoAddress() { @@ -865,6 +566,13 @@ return LLDB_INVALID_ADDRESS; } +DynamicLoaderWindowsDYLD *ProcessWindows::GetDynamicLoader() { + if (m_dyld_up.get() == NULL) + m_dyld_up.reset(DynamicLoader::FindPlugin( + this, DynamicLoaderWindowsDYLD::GetPluginNameStatic().GetCString())); + return static_cast<DynamicLoaderWindowsDYLD *>(m_dyld_up.get()); +} + void ProcessWindows::OnExitProcess(uint32_t exit_code) { // No need to acquire the lock since m_session_data isn't accessed. Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); @@ -888,6 +596,9 @@ Status error(exit_code, eErrorTypeWin32); OnDebuggerError(error, 0); } + + // Reset the session. + m_session_data.reset(); } void ProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) { @@ -909,7 +620,8 @@ FileSystem::Instance().Resolve(executable_file); ModuleSpec module_spec(executable_file); Status error; - module = GetTarget().GetSharedModule(module_spec, &error); + module = GetTarget().GetOrCreateModule(module_spec, + true /* notify */, &error); if (!module) { return; } @@ -917,12 +629,8 @@ GetTarget().SetExecutableModule(module, eLoadDependentsNo); } - bool load_addr_changed; - module->SetLoadAddress(GetTarget(), image_base, false, load_addr_changed); - - ModuleList loaded_modules; - loaded_modules.Append(module); - GetTarget().ModulesDidLoad(loaded_modules); + if (auto dyld = GetDynamicLoader()) + dyld->OnLoadModule(module, ModuleSpec(), image_base); // Add the main executable module to the list of pending module loads. We // can't call GetTarget().ModulesDidLoad() here because we still haven't @@ -1028,29 +736,13 @@ void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec, lldb::addr_t module_addr) { - // Confusingly, there is no Target::AddSharedModule. Instead, calling - // GetSharedModule() with a new module will add it to the module list and - // return a corresponding ModuleSP. - Status error; - ModuleSP module = GetTarget().GetSharedModule(module_spec, &error); - bool load_addr_changed = false; - module->SetLoadAddress(GetTarget(), module_addr, false, load_addr_changed); - - ModuleList loaded_modules; - loaded_modules.Append(module); - GetTarget().ModulesDidLoad(loaded_modules); + if (auto dyld = GetDynamicLoader()) + dyld->OnLoadModule(nullptr, module_spec, module_addr); } void ProcessWindows::OnUnloadDll(lldb::addr_t module_addr) { - Address resolved_addr; - if (GetTarget().ResolveLoadAddress(module_addr, resolved_addr)) { - ModuleSP module = resolved_addr.GetModule(); - if (module) { - ModuleList unloaded_modules; - unloaded_modules.Append(module); - GetTarget().ModulesDidUnload(unloaded_modules, false); - } - } + if (auto dyld = GetDynamicLoader()) + dyld->OnUnloadModule(module_addr); } void ProcessWindows::OnDebugString(const std::string &string) {} @@ -1079,41 +771,4 @@ return; } } - -Status ProcessWindows::WaitForDebuggerConnection(DebuggerThreadSP debugger, - HostProcess &process) { - Status result; - Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS | - WINDOWS_LOG_BREAKPOINTS); - LLDB_LOG(log, "Waiting for loader breakpoint."); - - // Block this function until we receive the initial stop from the process. - if (::WaitForSingleObject(m_session_data->m_initial_stop_event, INFINITE) == - WAIT_OBJECT_0) { - LLDB_LOG(log, "hit loader breakpoint, returning."); - - process = debugger->GetProcess(); - return m_session_data->m_launch_error; - } else - return Status(::GetLastError(), eErrorTypeWin32); -} - -// The Windows page protection bits are NOT independent masks that can be -// bitwise-ORed together. For example, PAGE_EXECUTE_READ is not (PAGE_EXECUTE -// | PAGE_READ). To test for an access type, it's necessary to test for any of -// the bits that provide that access type. -bool ProcessWindows::IsPageReadable(uint32_t protect) { - return (protect & PAGE_NOACCESS) == 0; -} - -bool ProcessWindows::IsPageWritable(uint32_t protect) { - return (protect & (PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY | - PAGE_READWRITE | PAGE_WRITECOPY)) != 0; -} - -bool ProcessWindows::IsPageExecutable(uint32_t protect) { - return (protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | - PAGE_EXECUTE_WRITECOPY)) != 0; -} - } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.h index 00e384f..8d5134a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindows.h
@@ -1,9 +1,8 @@ //===-- ProcessWindows.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,20 +13,16 @@ #include "lldb/Utility/Status.h" #include "lldb/lldb-forward.h" -#include "llvm/Support/Mutex.h" - -#include "IDebugDelegate.h" +#include "Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h" +#include "ProcessDebugger.h" namespace lldb_private { class HostProcess; -class ProcessWindowsData; -class ProcessWindows : public Process, public IDebugDelegate { +class ProcessWindows : public Process, public ProcessDebugger { public: - //------------------------------------------------------------------ // Static functions. - //------------------------------------------------------------------ static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *); @@ -40,9 +35,7 @@ static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // Constructors and destructors - //------------------------------------------------------------------ ProcessWindows(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp); ~ProcessWindows(); @@ -91,6 +84,8 @@ lldb::addr_t GetImageInfoAddress() override; + DynamicLoaderWindowsDYLD *GetDynamicLoader() override; + // IDebugDelegate overrides. void OnExitProcess(uint32_t exit_code) override; void OnDebuggerConnected(lldb::addr_t image_base) override; @@ -103,19 +98,7 @@ void OnUnloadDll(lldb::addr_t module_addr) override; void OnDebugString(const std::string &string) override; void OnDebuggerError(const Status &error, uint32_t type) override; - -private: - Status WaitForDebuggerConnection(DebuggerThreadSP debugger, - HostProcess &process); - - // These decode the page protection bits. - static bool IsPageReadable(uint32_t protect); - static bool IsPageWritable(uint32_t protect); - static bool IsPageExecutable(uint32_t protect); - - llvm::sys::Mutex m_mutex; - std::unique_ptr<ProcessWindowsData> m_session_data; }; -} +} // namespace lldb_private #endif // liblldb_Plugins_Process_Windows_Common_ProcessWindows_H_
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.cpp index 386e9a5..8af9f39 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.cpp
@@ -1,9 +1,8 @@ //===-- ProcessWindowsLog.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.h index b7f59c7..66ba245 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/ProcessWindowsLog.h
@@ -1,9 +1,8 @@ //===-- ProcessWindowsLog.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.cpp index 90d43b2..5231838 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextWindows.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,11 +21,9 @@ using namespace lldb; using namespace lldb_private; -const DWORD kWinContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; +const DWORD kWinContextFlags = CONTEXT_ALL; -//------------------------------------------------------------------ // Constructors and Destructors -//------------------------------------------------------------------ RegisterContextWindows::RegisterContextWindows(Thread &thread, uint32_t concrete_frame_idx) : RegisterContext(thread, concrete_frame_idx), m_context(), @@ -79,9 +76,7 @@ return LLDB_INVALID_REGNUM; } -//------------------------------------------------------------------ // Subclasses can these functions if desired -//------------------------------------------------------------------ uint32_t RegisterContextWindows::NumSupportedHardwareBreakpoints() { // Support for hardware breakpoints not yet implemented. return 0; @@ -119,8 +114,18 @@ return true; TargetThreadWindows &wthread = static_cast<TargetThreadWindows &>(m_thread); - memset(&m_context, 0, sizeof(m_context)); - m_context.ContextFlags = kWinContextFlags; + uint8_t buffer[2048]; + memset(buffer, 0, sizeof(buffer)); + PCONTEXT tmpContext = NULL; + DWORD contextLength = (DWORD)sizeof(buffer); + if (!::InitializeContext(buffer, kWinContextFlags, &tmpContext, + &contextLength)) { + return false; + } + memcpy(&m_context, tmpContext, sizeof(m_context)); + if (!::SuspendThread(wthread.GetHostThread().GetNativeThread().GetSystemHandle())) { + return false; + } if (!::GetThreadContext( wthread.GetHostThread().GetNativeThread().GetSystemHandle(), &m_context)) { @@ -130,6 +135,9 @@ ::GetLastError()); return false; } + if (!::ResumeThread(wthread.GetHostThread().GetNativeThread().GetSystemHandle())) { + return false; + } LLDB_LOG(log, "successfully updated the register values."); m_context_stale = false; return true;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.h index bd09295..916f9f3 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/RegisterContextWindows.h
@@ -1,9 +1,8 @@ //===-- RegisterContextWindows.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,16 +18,12 @@ class RegisterContextWindows : public lldb_private::RegisterContext { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ RegisterContextWindows(Thread &thread, uint32_t concrete_frame_idx); virtual ~RegisterContextWindows(); - //------------------------------------------------------------------ // Subclasses must override these functions - //------------------------------------------------------------------ void InvalidateAllRegisters() override; bool ReadAllRegisterValues(lldb::DataBufferSP &data_sp) override; @@ -38,9 +33,7 @@ uint32_t ConvertRegisterKindToRegisterNumber(lldb::RegisterKind kind, uint32_t num) override; - //------------------------------------------------------------------ // Subclasses can override these functions if desired - //------------------------------------------------------------------ uint32_t NumSupportedHardwareBreakpoints() override; uint32_t SetHardwareBreakpoint(lldb::addr_t addr, size_t size) override;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.cpp index b121dc7..0af0b56 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.cpp
@@ -1,9 +1,8 @@ //===-- TargetThreadWindows.cpp----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,9 +20,10 @@ #include "ProcessWindowsLog.h" #include "TargetThreadWindows.h" -#if defined(_WIN64) +// TODO support _M_ARM and _M_ARM64 +#if defined(_M_AMD64) #include "x64/RegisterContextWindows_x64.h" -#else +#elif defined(_M_IX86) #include "x86/RegisterContextWindows_x86.h" #endif @@ -67,23 +67,33 @@ if (!m_thread_reg_ctx_sp) { ArchSpec arch = HostInfo::GetArchitecture(); switch (arch.GetMachine()) { + case llvm::Triple::arm: + case llvm::Triple::thumb: + LLDB_LOG(log, "debugging ARM (NT) targets is currently unsupported"); + break; + + case llvm::Triple::aarch64: + LLDB_LOG(log, "debugging ARM64 targets is currently unsupported"); + break; + case llvm::Triple::x86: -#if defined(_WIN64) - // FIXME: This is a Wow64 process, create a RegisterContextWindows_Wow64 - LLDB_LOG(log, "This is a Wow64 process, we should create a " - "RegisterContextWindows_Wow64, but we don't."); -#else +#if defined(_M_IX86) m_thread_reg_ctx_sp.reset( new RegisterContextWindows_x86(*this, concrete_frame_idx)); +#else + LLDB_LOG(log, "debugging foreign targets is currently unsupported"); #endif break; + case llvm::Triple::x86_64: -#if defined(_WIN64) +#if defined(_M_AMD64) m_thread_reg_ctx_sp.reset( new RegisterContextWindows_x64(*this, concrete_frame_idx)); #else - LLDB_LOG(log, "LLDB is 32-bit, but the target process is 64-bit."); + LLDB_LOG(log, "debugging foreign targets is currently unsupported"); #endif + break; + default: break; } @@ -106,9 +116,9 @@ Unwind *TargetThreadWindows::GetUnwinder() { // FIXME: Implement an unwinder based on the Windows unwinder exposed through // DIA SDK. - if (!m_unwinder_ap) - m_unwinder_ap.reset(new UnwindLLDB(*this)); - return m_unwinder_ap.get(); + if (!m_unwinder_up) + m_unwinder_up.reset(new UnwindLLDB(*this)); + return m_unwinder_up.get(); } Status TargetThreadWindows::DoResume() {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.h index 952c0f5..fc68cb7 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/TargetThreadWindows.h
@@ -1,9 +1,8 @@ //===-- TargetThreadWindows.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.cpp index 584136a..11f72c0 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.cpp
@@ -1,12 +1,13 @@ //===-- RegisterContextWindows_x64.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// +#if defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) || defined(_M_AMD64) + #include "lldb/Host/windows/HostThreadWindows.h" #include "lldb/Host/windows/windows.h" #include "lldb/Utility/RegisterValue.h" @@ -25,6 +26,11 @@ #define DEFINE_GPR(reg, alt) #reg, alt, 8, 0, eEncodingUint, eFormatHexUppercase #define DEFINE_GPR_BIN(reg, alt) #reg, alt, 8, 0, eEncodingUint, eFormatBinary +#define DEFINE_FPU_XMM(reg) \ + #reg, NULL, 16, 0, eEncodingUint, eFormatVectorOfUInt64, \ + {dwarf_##reg##_x86_64, dwarf_##reg##_x86_64, LLDB_INVALID_REGNUM, \ + LLDB_INVALID_REGNUM, lldb_##reg##_x86_64}, \ + nullptr, nullptr, nullptr, 0 namespace { @@ -52,7 +58,24 @@ eRegisterIndexR14, eRegisterIndexR15, eRegisterIndexRip, - eRegisterIndexRflags + eRegisterIndexRflags, + + eRegisterIndexXmm0, + eRegisterIndexXmm1, + eRegisterIndexXmm2, + eRegisterIndexXmm3, + eRegisterIndexXmm4, + eRegisterIndexXmm5, + eRegisterIndexXmm6, + eRegisterIndexXmm7, + eRegisterIndexXmm8, + eRegisterIndexXmm9, + eRegisterIndexXmm10, + eRegisterIndexXmm11, + eRegisterIndexXmm12, + eRegisterIndexXmm13, + eRegisterIndexXmm14, + eRegisterIndexXmm15 }; // Array of all register information supported by Windows x86 @@ -67,92 +90,144 @@ {dwarf_rax_x86_64, dwarf_rax_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_rax_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rbx, nullptr), {dwarf_rbx_x86_64, dwarf_rbx_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_rbx_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rcx, nullptr), {dwarf_rcx_x86_64, dwarf_rcx_x86_64, LLDB_REGNUM_GENERIC_ARG1, LLDB_INVALID_REGNUM, lldb_rcx_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rdx, nullptr), {dwarf_rdx_x86_64, dwarf_rdx_x86_64, LLDB_REGNUM_GENERIC_ARG2, LLDB_INVALID_REGNUM, lldb_rdx_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rdi, nullptr), {dwarf_rdi_x86_64, dwarf_rdi_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_rdi_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rsi, nullptr), {dwarf_rsi_x86_64, dwarf_rsi_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_rsi_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rbp, "fp"), {dwarf_rbp_x86_64, dwarf_rbp_x86_64, LLDB_REGNUM_GENERIC_FP, LLDB_INVALID_REGNUM, lldb_rbp_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rsp, "sp"), {dwarf_rsp_x86_64, dwarf_rsp_x86_64, LLDB_REGNUM_GENERIC_SP, LLDB_INVALID_REGNUM, lldb_rsp_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r8, nullptr), {dwarf_r8_x86_64, dwarf_r8_x86_64, LLDB_REGNUM_GENERIC_ARG3, LLDB_INVALID_REGNUM, lldb_r8_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r9, nullptr), {dwarf_r9_x86_64, dwarf_r9_x86_64, LLDB_REGNUM_GENERIC_ARG4, LLDB_INVALID_REGNUM, lldb_r9_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r10, nullptr), - {dwarf_r10_x86_64, dwarf_r10_x86_64, LLDB_REGNUM_GENERIC_ARG5, + {dwarf_r10_x86_64, dwarf_r10_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_r10_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r11, nullptr), - {dwarf_r11_x86_64, dwarf_r11_x86_64, LLDB_REGNUM_GENERIC_ARG6, + {dwarf_r11_x86_64, dwarf_r11_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_r11_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r12, nullptr), {dwarf_r12_x86_64, dwarf_r12_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_r12_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r13, nullptr), {dwarf_r13_x86_64, dwarf_r13_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_r13_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r14, nullptr), {dwarf_r14_x86_64, dwarf_r14_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_r14_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(r15, nullptr), {dwarf_r15_x86_64, dwarf_r15_x86_64, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, lldb_r15_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR(rip, "pc"), {dwarf_rip_x86_64, dwarf_rip_x86_64, LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM, lldb_rip_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, {DEFINE_GPR_BIN(eflags, "flags"), {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_REGNUM_GENERIC_FLAGS, LLDB_INVALID_REGNUM, lldb_rflags_x86_64}, nullptr, - nullptr}, + nullptr, + nullptr, + 0}, + {DEFINE_FPU_XMM(xmm0)}, + {DEFINE_FPU_XMM(xmm1)}, + {DEFINE_FPU_XMM(xmm2)}, + {DEFINE_FPU_XMM(xmm3)}, + {DEFINE_FPU_XMM(xmm4)}, + {DEFINE_FPU_XMM(xmm5)}, + {DEFINE_FPU_XMM(xmm6)}, + {DEFINE_FPU_XMM(xmm7)}, + {DEFINE_FPU_XMM(xmm8)}, + {DEFINE_FPU_XMM(xmm9)}, + {DEFINE_FPU_XMM(xmm10)}, + {DEFINE_FPU_XMM(xmm11)}, + {DEFINE_FPU_XMM(xmm12)}, + {DEFINE_FPU_XMM(xmm13)}, + {DEFINE_FPU_XMM(xmm14)}, + {DEFINE_FPU_XMM(xmm15)} }; static size_t k_num_register_infos = llvm::array_lengthof(g_register_infos); @@ -167,15 +242,23 @@ eRegisterIndexR12, eRegisterIndexR13, eRegisterIndexR14, eRegisterIndexR15, eRegisterIndexRip, eRegisterIndexRflags}; +uint32_t g_fpu_reg_indices[] = { + eRegisterIndexXmm0, eRegisterIndexXmm1, eRegisterIndexXmm2, + eRegisterIndexXmm3, eRegisterIndexXmm4, eRegisterIndexXmm5, + eRegisterIndexXmm6, eRegisterIndexXmm7, eRegisterIndexXmm8, + eRegisterIndexXmm9, eRegisterIndexXmm10, eRegisterIndexXmm11, + eRegisterIndexXmm12, eRegisterIndexXmm13, eRegisterIndexXmm14, + eRegisterIndexXmm15 +}; + RegisterSet g_register_sets[] = { {"General Purpose Registers", "gpr", llvm::array_lengthof(g_gpr_reg_indices), g_gpr_reg_indices}, -}; + {"Floating Point Registers", "fpu", + llvm::array_lengthof(g_fpu_reg_indices), g_fpu_reg_indices}}; } -//------------------------------------------------------------------ // Constructors and Destructors -//------------------------------------------------------------------ RegisterContextWindows_x64::RegisterContextWindows_x64( Thread &thread, uint32_t concrete_frame_idx) : RegisterContextWindows(thread, concrete_frame_idx) {} @@ -209,7 +292,9 @@ if (reg_info == nullptr) return false; - switch (reg_info->kinds[eRegisterKindLLDB]) { + const uint32_t reg = reg_info->kinds[eRegisterKindLLDB]; + + switch (reg) { case lldb_rax_x86_64: reg_value.SetUInt64(m_context.Rax); break; @@ -264,6 +349,70 @@ case lldb_rflags_x86_64: reg_value.SetUInt64(m_context.EFlags); break; + case lldb_xmm0_x86_64: + reg_value.SetBytes(&m_context.Xmm0, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm1_x86_64: + reg_value.SetBytes(&m_context.Xmm1, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm2_x86_64: + reg_value.SetBytes(&m_context.Xmm2, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm3_x86_64: + reg_value.SetBytes(&m_context.Xmm3, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm4_x86_64: + reg_value.SetBytes(&m_context.Xmm4, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm5_x86_64: + reg_value.SetBytes(&m_context.Xmm5, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm6_x86_64: + reg_value.SetBytes(&m_context.Xmm6, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm7_x86_64: + reg_value.SetBytes(&m_context.Xmm7, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm8_x86_64: + reg_value.SetBytes(&m_context.Xmm8, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm9_x86_64: + reg_value.SetBytes(&m_context.Xmm9, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm10_x86_64: + reg_value.SetBytes(&m_context.Xmm10, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm11_x86_64: + reg_value.SetBytes(&m_context.Xmm11, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm12_x86_64: + reg_value.SetBytes(&m_context.Xmm12, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm13_x86_64: + reg_value.SetBytes(&m_context.Xmm13, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm14_x86_64: + reg_value.SetBytes(&m_context.Xmm14, + reg_info->byte_size, endian::InlHostByteOrder()); + break; + case lldb_xmm15_x86_64: + reg_value.SetBytes(&m_context.Xmm15, + reg_info->byte_size, endian::InlHostByteOrder()); + break; } return true; } @@ -332,6 +481,54 @@ case lldb_rflags_x86_64: m_context.EFlags = reg_value.GetAsUInt64(); break; + case lldb_xmm0_x86_64: + memcpy(&m_context.Xmm0, reg_value.GetBytes(), 16); + break; + case lldb_xmm1_x86_64: + memcpy(&m_context.Xmm1, reg_value.GetBytes(), 16); + break; + case lldb_xmm2_x86_64: + memcpy(&m_context.Xmm2, reg_value.GetBytes(), 16); + break; + case lldb_xmm3_x86_64: + memcpy(&m_context.Xmm3, reg_value.GetBytes(), 16); + break; + case lldb_xmm4_x86_64: + memcpy(&m_context.Xmm4, reg_value.GetBytes(), 16); + break; + case lldb_xmm5_x86_64: + memcpy(&m_context.Xmm5, reg_value.GetBytes(), 16); + break; + case lldb_xmm6_x86_64: + memcpy(&m_context.Xmm6, reg_value.GetBytes(), 16); + break; + case lldb_xmm7_x86_64: + memcpy(&m_context.Xmm7, reg_value.GetBytes(), 16); + break; + case lldb_xmm8_x86_64: + memcpy(&m_context.Xmm8, reg_value.GetBytes(), 16); + break; + case lldb_xmm9_x86_64: + memcpy(&m_context.Xmm9, reg_value.GetBytes(), 16); + break; + case lldb_xmm10_x86_64: + memcpy(&m_context.Xmm10, reg_value.GetBytes(), 16); + break; + case lldb_xmm11_x86_64: + memcpy(&m_context.Xmm11, reg_value.GetBytes(), 16); + break; + case lldb_xmm12_x86_64: + memcpy(&m_context.Xmm12, reg_value.GetBytes(), 16); + break; + case lldb_xmm13_x86_64: + memcpy(&m_context.Xmm13, reg_value.GetBytes(), 16); + break; + case lldb_xmm14_x86_64: + memcpy(&m_context.Xmm14, reg_value.GetBytes(), 16); + break; + case lldb_xmm15_x86_64: + memcpy(&m_context.Xmm15, reg_value.GetBytes(), 16); + break; } // Physically update the registers in the target process. @@ -339,3 +536,5 @@ return ::SetThreadContext( wthread.GetHostThread().GetNativeThread().GetSystemHandle(), &m_context); } + +#endif // defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) || defined(_M_AMD64)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.h index 62cedc8f..20d2cb9 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x64/RegisterContextWindows_x64.h
@@ -1,15 +1,16 @@ //===-- RegisterContextWindows_x64.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 liblldb_RegisterContextWindows_x64_H_ #define liblldb_RegisterContextWindows_x64_H_ +#if defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) || defined(_M_AMD64) + #include "RegisterContextWindows.h" #include "lldb/lldb-forward.h" @@ -19,16 +20,12 @@ class RegisterContextWindows_x64 : public RegisterContextWindows { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ RegisterContextWindows_x64(Thread &thread, uint32_t concrete_frame_idx); virtual ~RegisterContextWindows_x64(); - //------------------------------------------------------------------ // Subclasses must override these functions - //------------------------------------------------------------------ size_t GetRegisterCount() override; const RegisterInfo *GetRegisterInfoAtIndex(size_t reg) override; @@ -45,4 +42,6 @@ }; } +#endif // defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) || defined(_M_AMD64) + #endif // #ifndef liblldb_RegisterContextWindows_x64_H_
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.cpp b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.cpp index e012f91..b8f7bb4 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.cpp
@@ -1,12 +1,13 @@ //===-- RegisterContextWindows_x86.cpp --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// +#if defined(__i386__) || defined(_M_IX86) + #include "lldb/Host/windows/HostThreadWindows.h" #include "lldb/Host/windows/windows.h" #include "lldb/Utility/RegisterValue.h" @@ -143,9 +144,7 @@ }; } -//------------------------------------------------------------------ // Constructors and Destructors -//------------------------------------------------------------------ RegisterContextWindows_x86::RegisterContextWindows_x86( Thread &thread, uint32_t concrete_frame_idx) : RegisterContextWindows(thread, concrete_frame_idx) {} @@ -285,3 +284,5 @@ reg_value.SetUInt32(value); return true; } + +#endif // defined(__i386__) || defined(_M_IX86)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.h b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.h index aae645f..6517de0 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.h +++ b/src/llvm-project/lldb/source/Plugins/Process/Windows/Common/x86/RegisterContextWindows_x86.h
@@ -1,15 +1,16 @@ //===-- RegisterContextWindows_x86.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 liblldb_RegisterContextWindows_x86_H_ #define liblldb_RegisterContextWindows_x86_H_ +#if defined(__i386__) || defined(_M_IX86) + #include "RegisterContextWindows.h" #include "lldb/lldb-forward.h" @@ -19,16 +20,12 @@ class RegisterContextWindows_x86 : public RegisterContextWindows { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ RegisterContextWindows_x86(Thread &thread, uint32_t concrete_frame_idx); virtual ~RegisterContextWindows_x86(); - //------------------------------------------------------------------ // Subclasses must override these functions - //------------------------------------------------------------------ size_t GetRegisterCount() override; const RegisterInfo *GetRegisterInfoAtIndex(size_t reg) override; @@ -49,4 +46,6 @@ }; } +#endif // defined(__i386__) || defined(_M_IX86) + #endif // #ifndef liblldb_RegisterContextWindows_x86_H_
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp index 7d66461..980169e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp
@@ -1,14 +1,14 @@ //===-- ProcessElfCore.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <stdlib.h> +#include <memory> #include <mutex> #include "lldb/Core/Module.h" @@ -66,8 +66,8 @@ lldb::offset_t data_offset = 0; if (elf_header.Parse(data, &data_offset)) { if (elf_header.e_type == llvm::ELF::ET_CORE) - process_sp.reset( - new ProcessElfCore(target_sp, listener_sp, *crash_file)); + process_sp = std::make_shared<ProcessElfCore>(target_sp, listener_sp, + *crash_file); } } } @@ -80,7 +80,7 @@ if (!m_core_module_sp && FileSystem::Instance().Exists(m_core_file)) { ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture()); Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp, - NULL, NULL, NULL)); + nullptr, nullptr, nullptr)); if (m_core_module_sp) { ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile) @@ -90,17 +90,13 @@ return false; } -//---------------------------------------------------------------------- // ProcessElfCore constructor -//---------------------------------------------------------------------- ProcessElfCore::ProcessElfCore(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec &core_file) : Process(target_sp, listener_sp), m_core_file(core_file) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ProcessElfCore::~ProcessElfCore() { Clear(); // We need to call finalize on the process before destroying ourselves to @@ -110,9 +106,7 @@ Finalize(); } -//---------------------------------------------------------------------- // PluginInterface -//---------------------------------------------------------------------- ConstString ProcessElfCore::GetPluginName() { return GetPluginNameStatic(); } uint32_t ProcessElfCore::GetPluginVersion() { return 1; } @@ -146,9 +140,7 @@ return addr; } -//---------------------------------------------------------------------- // Process Control -//---------------------------------------------------------------------- Status ProcessElfCore::DoLoadCore() { Status error; if (!m_core_module_sp) { @@ -157,7 +149,7 @@ } ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile()); - if (core == NULL) { + if (core == nullptr) { error.SetErrorString("invalid core object file"); return error; } @@ -244,7 +236,8 @@ exe_module_spec.GetFileSpec().SetFile( m_nt_file_entries[0].path.GetCString(), FileSpec::Style::native); if (exe_module_spec.GetFileSpec()) { - exe_module_sp = GetTarget().GetSharedModule(exe_module_spec); + exe_module_sp = GetTarget().GetOrCreateModule(exe_module_spec, + true /* notify */); if (exe_module_sp) GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsNo); } @@ -254,10 +247,10 @@ } lldb_private::DynamicLoader *ProcessElfCore::GetDynamicLoader() { - if (m_dyld_ap.get() == NULL) - m_dyld_ap.reset(DynamicLoader::FindPlugin( + if (m_dyld_up.get() == nullptr) + m_dyld_up.reset(DynamicLoader::FindPlugin( this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString())); - return m_dyld_ap.get(); + return m_dyld_up.get(); } bool ProcessElfCore::UpdateThreadList(ThreadList &old_thread_list, @@ -278,15 +271,11 @@ Status ProcessElfCore::DoDestroy() { return Status(); } -//------------------------------------------------------------------ // Process Queries -//------------------------------------------------------------------ bool ProcessElfCore::IsAlive() { return true; } -//------------------------------------------------------------------ // Process Memory -//------------------------------------------------------------------ size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size, Status &error) { // Don't allow the caching that lldb_private::Process::ReadMemory does since @@ -338,13 +327,13 @@ Status &error) { ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); - if (core_objfile == NULL) + if (core_objfile == nullptr) return 0; // Get the address range const VMRangeToFileOffset::Entry *address_range = m_core_aranges.FindEntryThatContains(addr); - if (address_range == NULL || address_range->GetRangeEnd() < addr) { + if (address_range == nullptr || address_range->GetRangeEnd() < addr) { error.SetErrorStringWithFormat("core file does not contain 0x%" PRIx64, addr); return 0; @@ -446,16 +435,48 @@ thread_data.gpregset = DataExtractor(data, offset, len); } -static void ParseNetBSDProcInfo(ThreadData &thread_data, - const DataExtractor &data) { +static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data, + uint32_t &cpi_nlwps, + uint32_t &cpi_signo, + uint32_t &cpi_siglwp, + uint32_t &cpi_pid) { lldb::offset_t offset = 0; - int version = data.GetU32(&offset); + uint32_t version = data.GetU32(&offset); if (version != 1) - return; + return llvm::make_error<llvm::StringError>( + "Error parsing NetBSD core(5) notes: Unsupported procinfo version", + llvm::inconvertibleErrorCode()); - offset += 4; - thread_data.signo = data.GetU32(&offset); + uint32_t cpisize = data.GetU32(&offset); + if (cpisize != NETBSD::NT_PROCINFO_SIZE) + return llvm::make_error<llvm::StringError>( + "Error parsing NetBSD core(5) notes: Unsupported procinfo size", + llvm::inconvertibleErrorCode()); + + cpi_signo = data.GetU32(&offset); /* killing signal */ + + offset += NETBSD::NT_PROCINFO_CPI_SIGCODE_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_SIGPEND_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_SIGMASK_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_SIGIGNORE_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_SIGCATCH_SIZE; + cpi_pid = data.GetU32(&offset); + offset += NETBSD::NT_PROCINFO_CPI_PPID_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_PGRP_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_SID_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_RUID_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_EUID_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_SVUID_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_RGID_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_EGID_SIZE; + offset += NETBSD::NT_PROCINFO_CPI_SVGID_SIZE; + cpi_nlwps = data.GetU32(&offset); /* number of LWPs */ + + offset += NETBSD::NT_PROCINFO_CPI_NAME_SIZE; + cpi_siglwp = data.GetU32(&offset); /* LWP target of killing signal */ + + return llvm::Error::success(); } static void ParseOpenBSDProcInfo(ThreadData &thread_data, @@ -541,37 +562,159 @@ return llvm::Error::success(); } +/// NetBSD specific Thread context from PT_NOTE segment +/// +/// NetBSD ELF core files use notes to provide information about +/// the process's state. The note name is "NetBSD-CORE" for +/// information that is global to the process, and "NetBSD-CORE@nn", +/// where "nn" is the lwpid of the LWP that the information belongs +/// to (such as register state). +/// +/// NetBSD uses the following note identifiers: +/// +/// ELF_NOTE_NETBSD_CORE_PROCINFO (value 1) +/// Note is a "netbsd_elfcore_procinfo" structure. +/// ELF_NOTE_NETBSD_CORE_AUXV (value 2; since NetBSD 8.0) +/// Note is an array of AuxInfo structures. +/// +/// NetBSD also uses ptrace(2) request numbers (the ones that exist in +/// machine-dependent space) to identify register info notes. The +/// info in such notes is in the same format that ptrace(2) would +/// export that information. +/// +/// For more information see /usr/include/sys/exec_elf.h +/// llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) { ThreadData thread_data; + bool had_nt_regs = false; + + // To be extracted from struct netbsd_elfcore_procinfo + // Used to sanity check of the LWPs of the process + uint32_t nlwps = 0; + uint32_t signo; // killing signal + uint32_t siglwp; // LWP target of killing signal + uint32_t pr_pid; + for (const auto ¬e : notes) { - // NetBSD per-thread information is stored in notes named "NetBSD-CORE@nnn" - // so match on the initial part of the string. - if (!llvm::StringRef(note.info.n_name).startswith("NetBSD-CORE")) - continue; + llvm::StringRef name = note.info.n_name; - switch (note.info.n_type) { - case NETBSD::NT_PROCINFO: - ParseNetBSDProcInfo(thread_data, note.data); - break; - case NETBSD::NT_AUXV: - m_auxv = note.data; - break; + if (name == "NetBSD-CORE") { + if (note.info.n_type == NETBSD::NT_PROCINFO) { + llvm::Error error = ParseNetBSDProcInfo(note.data, nlwps, signo, + siglwp, pr_pid); + if (error) + return error; + SetID(pr_pid); + } else if (note.info.n_type == NETBSD::NT_AUXV) { + m_auxv = note.data; + } + } else if (name.consume_front("NetBSD-CORE@")) { + lldb::tid_t tid; + if (name.getAsInteger(10, tid)) + return llvm::make_error<llvm::StringError>( + "Error parsing NetBSD core(5) notes: Cannot convert LWP ID " + "to integer", + llvm::inconvertibleErrorCode()); - case NETBSD::NT_AMD64_REGS: - if (GetArchitecture().GetMachine() == llvm::Triple::x86_64) - thread_data.gpregset = note.data; - break; - default: - thread_data.notes.push_back(note); - break; + switch (GetArchitecture().GetMachine()) { + case llvm::Triple::aarch64: { + // Assume order PT_GETREGS, PT_GETFPREGS + if (note.info.n_type == NETBSD::AARCH64::NT_REGS) { + // If this is the next thread, push the previous one first. + if (had_nt_regs) { + m_thread_data.push_back(thread_data); + thread_data = ThreadData(); + had_nt_regs = false; + } + + thread_data.gpregset = note.data; + thread_data.tid = tid; + if (thread_data.gpregset.GetByteSize() == 0) + return llvm::make_error<llvm::StringError>( + "Could not find general purpose registers note in core file.", + llvm::inconvertibleErrorCode()); + had_nt_regs = true; + } else if (note.info.n_type == NETBSD::AARCH64::NT_FPREGS) { + if (!had_nt_regs || tid != thread_data.tid) + return llvm::make_error<llvm::StringError>( + "Error parsing NetBSD core(5) notes: Unexpected order " + "of NOTEs PT_GETFPREG before PT_GETREG", + llvm::inconvertibleErrorCode()); + thread_data.notes.push_back(note); + } + } break; + case llvm::Triple::x86_64: { + // Assume order PT_GETREGS, PT_GETFPREGS + if (note.info.n_type == NETBSD::AMD64::NT_REGS) { + // If this is the next thread, push the previous one first. + if (had_nt_regs) { + m_thread_data.push_back(thread_data); + thread_data = ThreadData(); + had_nt_regs = false; + } + + thread_data.gpregset = note.data; + thread_data.tid = tid; + if (thread_data.gpregset.GetByteSize() == 0) + return llvm::make_error<llvm::StringError>( + "Could not find general purpose registers note in core file.", + llvm::inconvertibleErrorCode()); + had_nt_regs = true; + } else if (note.info.n_type == NETBSD::AMD64::NT_FPREGS) { + if (!had_nt_regs || tid != thread_data.tid) + return llvm::make_error<llvm::StringError>( + "Error parsing NetBSD core(5) notes: Unexpected order " + "of NOTEs PT_GETFPREG before PT_GETREG", + llvm::inconvertibleErrorCode()); + thread_data.notes.push_back(note); + } + } break; + default: + break; + } } } - if (thread_data.gpregset.GetByteSize() == 0) { + + // Push the last thread. + if (had_nt_regs) + m_thread_data.push_back(thread_data); + + if (m_thread_data.empty()) return llvm::make_error<llvm::StringError>( - "Could not find general purpose registers note in core file.", + "Error parsing NetBSD core(5) notes: No threads information " + "specified in notes", llvm::inconvertibleErrorCode()); + + if (m_thread_data.size() != nlwps) + return llvm::make_error<llvm::StringError>( + "Error parsing NetBSD core(5) notes: Mismatch between the number " + "of LWPs in netbsd_elfcore_procinfo and the number of LWPs specified " + "by MD notes", + llvm::inconvertibleErrorCode()); + + // Signal targeted at the whole process. + if (siglwp == 0) { + for (auto &data : m_thread_data) + data.signo = signo; } - m_thread_data.push_back(thread_data); + // Signal destined for a particular LWP. + else { + bool passed = false; + + for (auto &data : m_thread_data) { + if (data.tid == siglwp) { + data.signo = signo; + passed = true; + break; + } + } + + if (!passed) + return llvm::make_error<llvm::StringError>( + "Error parsing NetBSD core(5) notes: Signal passed to unknown LWP", + llvm::inconvertibleErrorCode()); + } + return llvm::Error::success(); } @@ -751,11 +894,11 @@ return arch; } -const lldb::DataBufferSP ProcessElfCore::GetAuxvData() { +DataExtractor ProcessElfCore::GetAuxvData() { const uint8_t *start = m_auxv.GetDataStart(); size_t len = m_auxv.GetByteSize(); lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len)); - return buffer; + return DataExtractor(buffer, GetByteOrder(), GetAddressByteSize()); } bool ProcessElfCore::GetProcessInfo(ProcessInstanceInfo &info) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h index 2c72686..829fe9a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h
@@ -1,9 +1,8 @@ //===-- ProcessElfCore.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // // Notes about Linux Process core dumps: // 1) Linux core dump is stored as ELF file. @@ -31,9 +30,7 @@ class ProcessElfCore : public lldb_private::Process { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const lldb_private::FileSpec *crash_file_path); @@ -46,37 +43,27 @@ static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ ProcessElfCore(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const lldb_private::FileSpec &core_file); ~ProcessElfCore() override; - //------------------------------------------------------------------ // Check if a given Process - //------------------------------------------------------------------ bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override; - //------------------------------------------------------------------ // Creating a new process, or attaching to an existing one - //------------------------------------------------------------------ lldb_private::Status DoLoadCore() override; lldb_private::DynamicLoader *GetDynamicLoader() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - //------------------------------------------------------------------ // Process Control - //------------------------------------------------------------------ lldb_private::Status DoDestroy() override; void RefreshStateAfterStop() override; @@ -89,16 +76,12 @@ return error; } - //------------------------------------------------------------------ // Process Queries - //------------------------------------------------------------------ bool IsAlive() override; bool WarnBeforeDetach() const override { return false; } - //------------------------------------------------------------------ // Process Memory - //------------------------------------------------------------------ size_t ReadMemory(lldb::addr_t addr, void *buf, size_t size, lldb_private::Status &error) override; @@ -114,7 +97,7 @@ lldb_private::ArchSpec GetArchitecture(); // Returns AUXV structure found in the core file - const lldb::DataBufferSP GetAuxvData() override; + lldb_private::DataExtractor GetAuxvData() override; bool GetProcessInfo(lldb_private::ProcessInstanceInfo &info) override; @@ -132,9 +115,7 @@ lldb_private::ConstString path; }; - //------------------------------------------------------------------ // For ProcessElfCore only - //------------------------------------------------------------------ typedef lldb_private::Range<lldb::addr_t, lldb::addr_t> FileRange; typedef lldb_private::RangeDataVector<lldb::addr_t, lldb::addr_t, FileRange> VMRangeToFileOffset;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.cpp index 80c6c02..fa05c45 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_arm.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,14 +11,16 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/RegisterValue.h" +#include <memory> + using namespace lldb_private; RegisterContextCorePOSIX_arm::RegisterContextCorePOSIX_arm( Thread &thread, RegisterInfoInterface *register_info, const DataExtractor &gpregset, llvm::ArrayRef<CoreNote> notes) : RegisterContextPOSIX_arm(thread, 0, register_info) { - m_gpr_buffer.reset( - new DataBufferHeap(gpregset.GetDataStart(), gpregset.GetByteSize())); + m_gpr_buffer = std::make_shared<DataBufferHeap>(gpregset.GetDataStart(), + gpregset.GetByteSize()); m_gpr.SetData(m_gpr_buffer); m_gpr.SetByteOrder(gpregset.GetByteOrder()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.h index a98d64c..adda43e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_arm.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.cpp index 017646b..e477c43 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.cpp
@@ -1,25 +1,27 @@ //===-- RegisterContextPOSIXCore_arm64.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "RegisterContextPOSIXCore_arm64.h" + #include "Plugins/Process/elf-core/RegisterUtilities.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/RegisterValue.h" +#include <memory> + using namespace lldb_private; RegisterContextCorePOSIX_arm64::RegisterContextCorePOSIX_arm64( Thread &thread, RegisterInfoInterface *register_info, const DataExtractor &gpregset, llvm::ArrayRef<CoreNote> notes) : RegisterContextPOSIX_arm64(thread, 0, register_info) { - m_gpr_buffer.reset( - new DataBufferHeap(gpregset.GetDataStart(), gpregset.GetByteSize())); + m_gpr_buffer = std::make_shared<DataBufferHeap>(gpregset.GetDataStart(), + gpregset.GetByteSize()); m_gpr.SetData(m_gpr_buffer); m_gpr.SetByteOrder(gpregset.GetByteOrder()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.h index c519b15..de6d819 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_arm64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_arm64.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.cpp index beeb9b6..3601f3b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_mips64.cpp ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,21 +11,23 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/RegisterValue.h" +#include <memory> + using namespace lldb_private; RegisterContextCorePOSIX_mips64::RegisterContextCorePOSIX_mips64( Thread &thread, RegisterInfoInterface *register_info, const DataExtractor &gpregset, llvm::ArrayRef<CoreNote> notes) : RegisterContextPOSIX_mips64(thread, 0, register_info) { - m_gpr_buffer.reset( - new DataBufferHeap(gpregset.GetDataStart(), gpregset.GetByteSize())); + m_gpr_buffer = std::make_shared<DataBufferHeap>(gpregset.GetDataStart(), + gpregset.GetByteSize()); m_gpr.SetData(m_gpr_buffer); m_gpr.SetByteOrder(gpregset.GetByteOrder()); DataExtractor fpregset = getRegset( notes, register_info->GetTargetArchitecture().GetTriple(), FPR_Desc); - m_fpr_buffer.reset( - new DataBufferHeap(fpregset.GetDataStart(), fpregset.GetByteSize())); + m_fpr_buffer = std::make_shared<DataBufferHeap>(fpregset.GetDataStart(), + fpregset.GetByteSize()); m_fpr.SetData(m_fpr_buffer); m_fpr.SetByteOrder(fpregset.GetByteOrder()); } @@ -51,7 +52,7 @@ RegisterValue &value) { lldb::offset_t offset = reg_info->byte_offset; - lldb_private::ArchSpec arch = m_register_info_ap->GetTargetArchitecture(); + lldb_private::ArchSpec arch = m_register_info_up->GetTargetArchitecture(); uint64_t v; if (IsGPR(reg_info->kinds[lldb::eRegisterKindLLDB])) { if (reg_info->byte_size == 4 && !(arch.GetMachine() == llvm::Triple::mips64el))
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.h index cf1d8a5..999c945 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_mips64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_mips64.h -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.cpp index d4f86b3..6984bf4 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_powerpc.cpp --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,27 +12,29 @@ #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/RegisterValue.h" +#include <memory> + using namespace lldb_private; RegisterContextCorePOSIX_powerpc::RegisterContextCorePOSIX_powerpc( Thread &thread, RegisterInfoInterface *register_info, const DataExtractor &gpregset, llvm::ArrayRef<CoreNote> notes) : RegisterContextPOSIX_powerpc(thread, 0, register_info) { - m_gpr_buffer.reset( - new DataBufferHeap(gpregset.GetDataStart(), gpregset.GetByteSize())); + m_gpr_buffer = std::make_shared<DataBufferHeap>(gpregset.GetDataStart(), + gpregset.GetByteSize()); m_gpr.SetData(m_gpr_buffer); m_gpr.SetByteOrder(gpregset.GetByteOrder()); ArchSpec arch = register_info->GetTargetArchitecture(); DataExtractor fpregset = getRegset(notes, arch.GetTriple(), FPR_Desc); - m_fpr_buffer.reset( - new DataBufferHeap(fpregset.GetDataStart(), fpregset.GetByteSize())); + m_fpr_buffer = std::make_shared<DataBufferHeap>(fpregset.GetDataStart(), + fpregset.GetByteSize()); m_fpr.SetData(m_fpr_buffer); m_fpr.SetByteOrder(fpregset.GetByteOrder()); DataExtractor vregset = getRegset(notes, arch.GetTriple(), PPC_VMX_Desc); - m_vec_buffer.reset( - new DataBufferHeap(vregset.GetDataStart(), vregset.GetByteSize())); + m_vec_buffer = std::make_shared<DataBufferHeap>(vregset.GetDataStart(), + vregset.GetByteSize()); m_vec.SetData(m_vec_buffer); m_vec.SetByteOrder(vregset.GetByteOrder()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.h index c352ab5..7684c0b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_powerpc.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_powerpc.h ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.cpp index 8116a1c..0eebf47 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_ppc64le.cpp --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,33 +15,35 @@ #include "Plugins/Process/Utility/lldb-ppc64le-register-enums.h" #include "Plugins/Process/elf-core/RegisterUtilities.h" +#include <memory> + using namespace lldb_private; RegisterContextCorePOSIX_ppc64le::RegisterContextCorePOSIX_ppc64le( Thread &thread, RegisterInfoInterface *register_info, const DataExtractor &gpregset, llvm::ArrayRef<CoreNote> notes) : RegisterContextPOSIX_ppc64le(thread, 0, register_info) { - m_gpr_buffer.reset( - new DataBufferHeap(gpregset.GetDataStart(), gpregset.GetByteSize())); + m_gpr_buffer = std::make_shared<DataBufferHeap>(gpregset.GetDataStart(), + gpregset.GetByteSize()); m_gpr.SetData(m_gpr_buffer); m_gpr.SetByteOrder(gpregset.GetByteOrder()); ArchSpec arch = register_info->GetTargetArchitecture(); DataExtractor fpregset = getRegset(notes, arch.GetTriple(), FPR_Desc); - m_fpr_buffer.reset( - new DataBufferHeap(fpregset.GetDataStart(), fpregset.GetByteSize())); + m_fpr_buffer = std::make_shared<DataBufferHeap>(fpregset.GetDataStart(), + fpregset.GetByteSize()); m_fpr.SetData(m_fpr_buffer); m_fpr.SetByteOrder(fpregset.GetByteOrder()); DataExtractor vmxregset = getRegset(notes, arch.GetTriple(), PPC_VMX_Desc); - m_vmx_buffer.reset( - new DataBufferHeap(vmxregset.GetDataStart(), vmxregset.GetByteSize())); + m_vmx_buffer = std::make_shared<DataBufferHeap>(vmxregset.GetDataStart(), + vmxregset.GetByteSize()); m_vmx.SetData(m_vmx_buffer); m_vmx.SetByteOrder(vmxregset.GetByteOrder()); DataExtractor vsxregset = getRegset(notes, arch.GetTriple(), PPC_VSX_Desc); - m_vsx_buffer.reset( - new DataBufferHeap(vsxregset.GetDataStart(), vsxregset.GetByteSize())); + m_vsx_buffer = std::make_shared<DataBufferHeap>(vsxregset.GetDataStart(), + vsxregset.GetByteSize()); m_vsx.SetData(m_vsx_buffer); m_vsx.SetByteOrder(vsxregset.GetByteOrder()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.h index c860781..6e01d23 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_ppc64le.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_ppc64le.h ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.cpp index 875bb16..d84fc3e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_s390x.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,21 +12,23 @@ #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/RegisterValue.h" +#include <memory> + using namespace lldb_private; RegisterContextCorePOSIX_s390x::RegisterContextCorePOSIX_s390x( Thread &thread, RegisterInfoInterface *register_info, const DataExtractor &gpregset, llvm::ArrayRef<CoreNote> notes) : RegisterContextPOSIX_s390x(thread, 0, register_info) { - m_gpr_buffer.reset( - new DataBufferHeap(gpregset.GetDataStart(), gpregset.GetByteSize())); + m_gpr_buffer = std::make_shared<DataBufferHeap>(gpregset.GetDataStart(), + gpregset.GetByteSize()); m_gpr.SetData(m_gpr_buffer); m_gpr.SetByteOrder(gpregset.GetByteOrder()); DataExtractor fpregset = getRegset( notes, register_info->GetTargetArchitecture().GetTriple(), FPR_Desc); - m_fpr_buffer.reset( - new DataBufferHeap(fpregset.GetDataStart(), fpregset.GetByteSize())); + m_fpr_buffer = std::make_shared<DataBufferHeap>(fpregset.GetDataStart(), + fpregset.GetByteSize()); m_fpr.SetData(m_fpr_buffer); m_fpr.SetByteOrder(fpregset.GetByteOrder()); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.h index 0df1363..7296176 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_s390x.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_s390x.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp index 2729549..4454857 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_x86_64.cpp ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.h index 5096241..f41991c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextPOSIXCore_x86_64.h -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.cpp index 3837aba..c8829d6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.cpp
@@ -1,9 +1,8 @@ //===-- RegisterUtilities.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.h index 9170d94..d3b3373 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/RegisterUtilities.h
@@ -1,9 +1,8 @@ //===-- RegisterUtilities.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,9 +27,46 @@ } namespace NETBSD { -enum { NT_PROCINFO = 1, NT_AUXV, NT_AMD64_REGS = 33, NT_AMD64_FPREGS = 35 }; +enum { NT_PROCINFO = 1, NT_AUXV = 2 }; + +/* Size in bytes */ +enum { NT_PROCINFO_SIZE = 160 }; + +/* Size in bytes */ +enum { + NT_PROCINFO_CPI_VERSION_SIZE = 4, + NT_PROCINFO_CPI_CPISIZE_SIZE = 4, + NT_PROCINFO_CPI_SIGNO_SIZE = 4, + NT_PROCINFO_CPI_SIGCODE_SIZE = 4, + NT_PROCINFO_CPI_SIGPEND_SIZE = 16, + NT_PROCINFO_CPI_SIGMASK_SIZE = 16, + NT_PROCINFO_CPI_SIGIGNORE_SIZE = 16, + NT_PROCINFO_CPI_SIGCATCH_SIZE = 16, + NT_PROCINFO_CPI_PID_SIZE = 4, + NT_PROCINFO_CPI_PPID_SIZE = 4, + NT_PROCINFO_CPI_PGRP_SIZE = 4, + NT_PROCINFO_CPI_SID_SIZE = 4, + NT_PROCINFO_CPI_RUID_SIZE = 4, + NT_PROCINFO_CPI_EUID_SIZE = 4, + NT_PROCINFO_CPI_SVUID_SIZE = 4, + NT_PROCINFO_CPI_RGID_SIZE = 4, + NT_PROCINFO_CPI_EGID_SIZE = 4, + NT_PROCINFO_CPI_SVGID_SIZE = 4, + NT_PROCINFO_CPI_NLWPS_SIZE = 4, + NT_PROCINFO_CPI_NAME_SIZE = 32, + NT_PROCINFO_CPI_SIGLWP_SIZE = 4, +}; + +namespace AARCH64 { +enum { NT_REGS = 32, NT_FPREGS = 34 }; } +namespace AMD64 { +enum { NT_REGS = 33, NT_FPREGS = 35 }; +} + +} // namespace NETBSD + namespace OPENBSD { enum { NT_PROCINFO = 10, @@ -92,7 +128,8 @@ // The result from FXSAVE is in NT_PRXFPREG for i386 core files {llvm::Triple::Linux, llvm::Triple::x86, LINUX::NT_PRXFPREG}, {llvm::Triple::Linux, llvm::Triple::UnknownArch, LINUX::NT_FPREGSET}, - {llvm::Triple::NetBSD, llvm::Triple::x86_64, NETBSD::NT_AMD64_FPREGS}, + {llvm::Triple::NetBSD, llvm::Triple::aarch64, NETBSD::AARCH64::NT_FPREGS}, + {llvm::Triple::NetBSD, llvm::Triple::x86_64, NETBSD::AMD64::NT_FPREGS}, {llvm::Triple::OpenBSD, llvm::Triple::UnknownArch, OPENBSD::NT_FPREGS}, };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp index d9b90c8..a5d1fc4 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp
@@ -1,9 +1,8 @@ //===-- ThreadElfCore.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -39,12 +38,12 @@ #include "RegisterContextPOSIXCore_x86_64.h" #include "ThreadElfCore.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Construct a Thread object with given data -//---------------------------------------------------------------------- ThreadElfCore::ThreadElfCore(Process &process, const ThreadData &td) : Thread(process, td.tid), m_thread_name(td.name), m_thread_reg_ctx_sp(), m_signo(td.signo), m_gpregset_data(td.gpregset), m_notes(td.notes) {} @@ -111,6 +110,9 @@ case llvm::Triple::NetBSD: { switch (arch.GetMachine()) { + case llvm::Triple::aarch64: + reg_interface = new RegisterInfoPOSIX_arm64(arch); + break; case llvm::Triple::x86_64: reg_interface = new RegisterContextNetBSD_x86_64(arch); break; @@ -187,40 +189,40 @@ switch (arch.GetMachine()) { case llvm::Triple::aarch64: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_arm64( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_arm64>( + *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::arm: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_arm( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_arm>( + *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::mipsel: case llvm::Triple::mips: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_mips64( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_mips64>( + *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::mips64: case llvm::Triple::mips64el: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_mips64( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_mips64>( + *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::ppc: case llvm::Triple::ppc64: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_powerpc( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_powerpc>( + *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::ppc64le: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_ppc64le( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_ppc64le>( + *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::systemz: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_s390x( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_s390x>( + *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::x86: case llvm::Triple::x86_64: - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_x86_64( - *this, reg_interface, m_gpregset_data, m_notes)); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_x86_64>( + *this, reg_interface, m_gpregset_data, m_notes); break; default: break; @@ -244,9 +246,7 @@ return false; } -//---------------------------------------------------------------- // Parse PRSTATUS from NOTE entry -//---------------------------------------------------------------- ELFLinuxPrStatus::ELFLinuxPrStatus() { memset(this, 0, sizeof(ELFLinuxPrStatus)); } @@ -254,6 +254,7 @@ size_t ELFLinuxPrStatus::GetSize(const lldb_private::ArchSpec &arch) { constexpr size_t mips_linux_pr_status_size_o32 = 96; constexpr size_t mips_linux_pr_status_size_n32 = 72; + constexpr size_t num_ptr_size_members = 10; if (arch.IsMIPS()) { std::string abi = arch.GetTargetABI(); assert(!abi.empty() && "ABI is not set"); @@ -265,15 +266,14 @@ return mips_linux_pr_status_size_n32; } switch (arch.GetCore()) { - case lldb_private::ArchSpec::eCore_s390x_generic: - case lldb_private::ArchSpec::eCore_x86_64_x86_64: - case lldb_private::ArchSpec::eCore_ppc64le_generic: - return sizeof(ELFLinuxPrStatus); case lldb_private::ArchSpec::eCore_x86_32_i386: case lldb_private::ArchSpec::eCore_x86_32_i486: return 72; default: - return 0; + if (arch.GetAddressByteSize() == 8) + return sizeof(ELFLinuxPrStatus); + else + return sizeof(ELFLinuxPrStatus) - num_ptr_size_members * 4; } } @@ -320,9 +320,7 @@ return error; } -//---------------------------------------------------------------- // Parse PRPSINFO from NOTE entry -//---------------------------------------------------------------- ELFLinuxPrPsInfo::ELFLinuxPrPsInfo() { memset(this, 0, sizeof(ELFLinuxPrPsInfo)); } @@ -398,9 +396,7 @@ return error; } -//---------------------------------------------------------------- // Parse SIGINFO from NOTE entry -//---------------------------------------------------------------- ELFLinuxSigInfo::ELFLinuxSigInfo() { memset(this, 0, sizeof(ELFLinuxSigInfo)); } size_t ELFLinuxSigInfo::GetSize(const lldb_private::ArchSpec &arch) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h index 167fd6e..ddcf350 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h +++ b/src/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h
@@ -1,9 +1,8 @@ //===-- ThreadElfCore.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -150,7 +149,7 @@ const char *GetName() override { if (m_thread_name.empty()) - return NULL; + return nullptr; return m_thread_name.c_str(); } @@ -162,9 +161,7 @@ } protected: - //------------------------------------------------------------------ // Member variables. - //------------------------------------------------------------------ std::string m_thread_name; lldb::RegisterContextSP m_thread_reg_ctx_sp;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp index a3a4aa0..fe7ef6b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteClientBase.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,7 +10,6 @@ #include "llvm/ADT/StringExtras.h" -#include "lldb/Target/Process.h" #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/LLDBAssert.h" @@ -287,7 +285,7 @@ void GDBRemoteClientBase::OnRunPacketSent(bool first) { if (first) - BroadcastEvent(eBroadcastBitRunPacketSent, NULL); + BroadcastEvent(eBroadcastBitRunPacketSent, nullptr); } /////////////////////////////////////// @@ -367,7 +365,7 @@ // packet. Let's interrupt it. const char ctrl_c = '\x03'; ConnectionStatus status = eConnectionStatusSuccess; - size_t bytes_written = m_comm.Write(&ctrl_c, 1, status, NULL); + size_t bytes_written = m_comm.Write(&ctrl_c, 1, status, nullptr); if (bytes_written == 0) { --m_comm.m_async_count; if (log)
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h index 3d84ce0..54f69e8 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteClientBase.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,7 +27,7 @@ // ========================================================================= /// Process asynchronously-received structured data. /// - /// @param[in] data + /// \param[in] data /// The complete data packet, expected to start with JSON-async. // ========================================================================= virtual void HandleAsyncStructuredDataPacket(llvm::StringRef data) = 0;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp index 72c1314..11052ef 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,13 +19,14 @@ #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Host/Pipe.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/Host/Socket.h" #include "lldb/Host/StringConvert.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Host/common/TCPSocket.h" #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" #include "lldb/Target/Platform.h" -#include "lldb/Target/Process.h" +#include "lldb/Utility/Event.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/RegularExpression.h" @@ -42,8 +42,7 @@ #define DEBUGSERVER_BASENAME "lldb-server" #endif -#if defined(__APPLE__) -#define HAVE_LIBCOMPRESSION +#if defined(HAVE_LIBCOMPRESSION) #include <compression.h> #endif @@ -55,9 +54,7 @@ using namespace lldb_private; using namespace lldb_private::process_gdb_remote; -//---------------------------------------------------------------------- // GDBRemoteCommunication constructor -//---------------------------------------------------------------------- GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name, const char *listener_name) : Communication(comm_name), @@ -68,22 +65,19 @@ #endif m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512), m_send_acks(true), m_compression_type(CompressionType::None), - m_listen_url(), m_decompression_scratch_type(CompressionType::None), - m_decompression_scratch(nullptr) { - // Unused unless HAVE_LIBCOMPRESSION is defined. - (void)m_decompression_scratch_type; + m_listen_url() { } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- GDBRemoteCommunication::~GDBRemoteCommunication() { if (IsConnected()) { Disconnect(); } +#if defined(HAVE_LIBCOMPRESSION) if (m_decompression_scratch) free (m_decompression_scratch); +#endif // Stop the communications read thread which is used to parse all incoming // packets. This function will block until the read thread returns. @@ -104,7 +98,7 @@ Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS)); ConnectionStatus status = eConnectionStatusSuccess; char ch = '+'; - const size_t bytes_written = Write(&ch, 1, status, NULL); + const size_t bytes_written = Write(&ch, 1, status, nullptr); if (log) log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch); m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend, @@ -116,7 +110,7 @@ Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS)); ConnectionStatus status = eConnectionStatusSuccess; char ch = '-'; - const size_t bytes_written = Write(&ch, 1, status, NULL); + const size_t bytes_written = Write(&ch, 1, status, nullptr); if (log) log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch); m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend, @@ -126,14 +120,14 @@ GDBRemoteCommunication::PacketResult GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) { - StreamString packet(0, 4, eByteOrderBig); - packet.PutChar('$'); - packet.Write(payload.data(), payload.size()); - packet.PutChar('#'); - packet.PutHex8(CalculcateChecksum(payload)); - std::string packet_str = packet.GetString(); + StreamString packet(0, 4, eByteOrderBig); + packet.PutChar('$'); + packet.Write(payload.data(), payload.size()); + packet.PutChar('#'); + packet.PutHex8(CalculcateChecksum(payload)); + std::string packet_str = packet.GetString(); - return SendRawPacketNoLock(packet_str); + return SendRawPacketNoLock(packet_str); } GDBRemoteCommunication::PacketResult @@ -144,7 +138,7 @@ ConnectionStatus status = eConnectionStatusSuccess; const char *packet_data = packet.data(); const size_t packet_length = packet.size(); - size_t bytes_written = Write(packet_data, packet_length, status, NULL); + size_t bytes_written = Write(packet_data, packet_length, status, nullptr); if (log) { size_t binary_start_offset = 0; if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == @@ -280,7 +274,7 @@ Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS)); // Check for a packet from our cache first without trying any reading... - if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid) + if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid) return PacketResult::Success; bool timed_out = false; @@ -303,7 +297,6 @@ case eConnectionStatusTimedOut: case eConnectionStatusInterrupted: if (sync_on_timeout) { - //------------------------------------------------------------------ /// Sync the remote GDB server and make sure we get a response that /// corresponds to what we send. /// @@ -326,7 +319,6 @@ /// packets. So if we timeout, we need to ensure that we can get /// back on track. If we can't get back on track, we must /// disconnect. - //------------------------------------------------------------------ bool sync_success = false; bool got_actual_response = false; // We timed out, we need to sync back up with the @@ -478,7 +470,7 @@ content_length = hash_mark_idx - content_start; std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1); errno = 0; - decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10); + decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10); if (errno != 0 || decompressed_bufsize == ULONG_MAX) { m_bytes.erase(0, size_of_first_packet); return false; @@ -491,7 +483,7 @@ packet_checksum_cstr[0] = m_bytes[checksum_idx]; packet_checksum_cstr[1] = m_bytes[checksum_idx + 1]; packet_checksum_cstr[2] = '\0'; - long packet_checksum = strtol(packet_checksum_cstr, NULL, 16); + long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16); long actual_checksum = CalculcateChecksum( llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1)); @@ -549,7 +541,7 @@ #if defined(HAVE_LIBCOMPRESSION) if (m_compression_type == CompressionType::ZlibDeflate || m_compression_type == CompressionType::LZFSE || - m_compression_type == CompressionType::LZ4 || + m_compression_type == CompressionType::LZ4 || m_compression_type == CompressionType::LZMA) { compression_algorithm compression_type; if (m_compression_type == CompressionType::LZFSE) @@ -586,7 +578,7 @@ if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) { decompressed_bytes = compression_decode_buffer( decompressed_buffer, decompressed_bufsize, - (uint8_t *)unescaped_content.data(), unescaped_content.size(), + (uint8_t *)unescaped_content.data(), unescaped_content.size(), m_decompression_scratch, compression_type); } } @@ -856,7 +848,7 @@ ::isxdigit(m_bytes[checksum_idx + 1])) { if (GetSendAcks()) { const char *packet_checksum_cstr = &m_bytes[checksum_idx]; - char packet_checksum = strtol(packet_checksum_cstr, NULL, 16); + char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16); char actual_checksum = CalculcateChecksum( llvm::StringRef(m_bytes).slice(content_start, content_end)); success = packet_checksum == actual_checksum; @@ -896,22 +888,23 @@ Status GDBRemoteCommunication::StartListenThread(const char *hostname, uint16_t port) { - Status error; - if (m_listen_thread.IsJoinable()) { - error.SetErrorString("listen thread already running"); - } else { - char listen_url[512]; - if (hostname && hostname[0]) - snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, - port); - else - snprintf(listen_url, sizeof(listen_url), "listen://%i", port); - m_listen_url = listen_url; - SetConnection(new ConnectionFileDescriptor()); - m_listen_thread = ThreadLauncher::LaunchThread( - listen_url, GDBRemoteCommunication::ListenThread, this, &error); - } - return error; + if (m_listen_thread.IsJoinable()) + return Status("listen thread already running"); + + char listen_url[512]; + if (hostname && hostname[0]) + snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port); + else + snprintf(listen_url, sizeof(listen_url), "listen://%i", port); + m_listen_url = listen_url; + SetConnection(new ConnectionFileDescriptor()); + llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread( + listen_url, GDBRemoteCommunication::ListenThread, this); + if (!listen_thread) + return Status(listen_thread.takeError()); + m_listen_thread = *listen_thread; + + return Status(); } bool GDBRemoteCommunication::JoinListenThread() { @@ -931,9 +924,9 @@ // Do the listen on another thread so we can continue on... if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess) - comm->SetConnection(NULL); + comm->SetConnection(nullptr); } - return NULL; + return {}; } Status GDBRemoteCommunication::StartDebugserverProcess( @@ -952,16 +945,18 @@ char debugserver_path[PATH_MAX]; FileSpec &debugserver_file_spec = launch_info.GetExecutableFile(); + Environment host_env = Host::GetEnvironment(); + // Always check to see if we have an environment override for the path to the // debugserver to use and use it if we do. - const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); - if (env_debugserver_path) { + std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH"); + if (!env_debugserver_path.empty()) { debugserver_file_spec.SetFile(env_debugserver_path, FileSpec::Style::native); if (log) log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set " "from environment variable: %s", - __FUNCTION__, env_debugserver_path); + __FUNCTION__, env_debugserver_path.c_str()); } else debugserver_file_spec = g_debugserver_file_spec; bool debugserver_exists = @@ -980,8 +975,11 @@ g_debugserver_file_spec = debugserver_file_spec; } else { - debugserver_file_spec = - platform->LocateExecutable(DEBUGSERVER_BASENAME); + if (platform) + debugserver_file_spec = + platform->LocateExecutable(DEBUGSERVER_BASENAME); + else + debugserver_file_spec.Clear(); if (debugserver_file_spec) { // Platform::LocateExecutable() wouldn't return a path if it doesn't // exist @@ -1004,7 +1002,6 @@ Args &debugserver_args = launch_info.GetArguments(); debugserver_args.Clear(); - char arg_cstr[PATH_MAX]; // Start args with "debugserver /file/path -r --" debugserver_args.AppendArgument(llvm::StringRef(debugserver_path)); @@ -1114,29 +1111,27 @@ } } } - - const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); - if (env_debugserver_log_file) { - ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s", - env_debugserver_log_file); - debugserver_args.AppendArgument(llvm::StringRef(arg_cstr)); + std::string env_debugserver_log_file = + host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE"); + if (!env_debugserver_log_file.empty()) { + debugserver_args.AppendArgument( + llvm::formatv("--log-file={0}", env_debugserver_log_file).str()); } #if defined(__APPLE__) const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); if (env_debugserver_log_flags) { - ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s", - env_debugserver_log_flags); - debugserver_args.AppendArgument(llvm::StringRef(arg_cstr)); + debugserver_args.AppendArgument( + llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str()); } #else - const char *env_debugserver_log_channels = - getenv("LLDB_SERVER_LOG_CHANNELS"); - if (env_debugserver_log_channels) { - ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s", - env_debugserver_log_channels); - debugserver_args.AppendArgument(llvm::StringRef(arg_cstr)); + std::string env_debugserver_log_channels = + host_env.lookup("LLDB_SERVER_LOG_CHANNELS"); + if (!env_debugserver_log_channels.empty()) { + debugserver_args.AppendArgument( + llvm::formatv("--log-channels={0}", env_debugserver_log_channels) + .str()); } #endif @@ -1148,15 +1143,15 @@ char env_var_name[64]; snprintf(env_var_name, sizeof(env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++); - const char *extra_arg = getenv(env_var_name); - has_env_var = extra_arg != nullptr; + std::string extra_arg = host_env.lookup(env_var_name); + has_env_var = !extra_arg.empty(); if (has_env_var) { debugserver_args.AppendArgument(llvm::StringRef(extra_arg)); if (log) log->Printf("GDBRemoteCommunication::%s adding env var %s contents " "to stub command line (%s)", - __FUNCTION__, env_var_name, extra_arg); + __FUNCTION__, env_var_name, extra_arg.c_str()); } } while (has_env_var); @@ -1166,7 +1161,7 @@ } // Copy the current environment to the gdbserver/debugserver instance - launch_info.GetEnvironment() = Host::GetEnvironment(); + launch_info.GetEnvironment() = host_env; // Close STDIN, STDOUT and STDERR. launch_info.AppendCloseFileAction(STDIN_FILENO); @@ -1266,7 +1261,7 @@ void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) { m_history.SetStream(strm); -}; +} llvm::Error GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client, @@ -1284,13 +1279,14 @@ llvm::SmallString<32> remote_addr; llvm::raw_svector_ostream(remote_addr) - << "connect://localhost:" << listen_socket.GetLocalPortNumber(); + << "connect://127.0.0.1:" << listen_socket.GetLocalPortNumber(); std::unique_ptr<ConnectionFileDescriptor> conn_up( new ConnectionFileDescriptor()); - if (conn_up->Connect(remote_addr, nullptr) != lldb::eConnectionStatusSuccess) - return llvm::make_error<llvm::StringError>("Unable to connect", - llvm::inconvertibleErrorCode()); + Status status; + if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess) + return llvm::createStringError(llvm::inconvertibleErrorCode(), + "Unable to connect: %s", status.AsCString()); client.SetConnection(conn_up.release()); if (llvm::Error error = accept_status.get().ToError()) @@ -1302,14 +1298,14 @@ GDBRemoteCommunication::ScopedTimeout::ScopedTimeout( GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout) - : m_gdb_comm(gdb_comm), m_timeout_modified(false) { - auto curr_timeout = gdb_comm.GetPacketTimeout(); - // Only update the timeout if the timeout is greater than the current - // timeout. If the current timeout is larger, then just use that. - if (curr_timeout < timeout) { - m_timeout_modified = true; - m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout); - } + : m_gdb_comm(gdb_comm), m_timeout_modified(false) { + auto curr_timeout = gdb_comm.GetPacketTimeout(); + // Only update the timeout if the timeout is greater than the current + // timeout. If the current timeout is larger, then just use that. + if (curr_timeout < timeout) { + m_timeout_modified = true; + m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout); + } } GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h index 369eb25..bb777a5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunication.h --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,6 +18,7 @@ #include <vector> #include "lldb/Core/Communication.h" +#include "lldb/Host/Config.h" #include "lldb/Host/HostThread.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/Listener.h" @@ -29,14 +29,14 @@ namespace lldb_private { namespace process_gdb_remote { -typedef enum { +enum GDBStoppointType { eStoppointInvalid = -1, eBreakpointSoftware = 0, eBreakpointHardware, eWatchpointWrite, eWatchpointRead, eWatchpointReadWrite -} GDBStoppointType; +}; enum class CompressionType { None = 0, // no compression @@ -109,13 +109,11 @@ bool GetSendAcks() { return m_send_acks; } - //------------------------------------------------------------------ // Set the global packet timeout. // // For clients, this is the timeout that gets used when sending // packets and waiting for responses. For servers, this is used when waiting // for ACKs. - //------------------------------------------------------------------ std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout) { const auto old_packet_timeout = m_packet_timeout; m_packet_timeout = packet_timeout; @@ -124,10 +122,8 @@ std::chrono::seconds GetPacketTimeout() const { return m_packet_timeout; } - //------------------------------------------------------------------ // Start a debugserver instance on the current host using the // supplied connection URL. - //------------------------------------------------------------------ Status StartDebugserverProcess( const char *url, Platform *platform, // If non nullptr, then check with the platform for @@ -218,8 +214,10 @@ HostThread m_listen_thread; std::string m_listen_url; - CompressionType m_decompression_scratch_type; - void *m_decompression_scratch; +#if defined(HAVE_LIBCOMPRESSION) + CompressionType m_decompression_scratch_type = CompressionType::None; + void *m_decompression_scratch = nullptr; +#endif DISALLOW_COPY_AND_ASSIGN(GDBRemoteCommunication); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp index 1e12ea6..9797184 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -38,7 +37,9 @@ #include "llvm/ADT/StringSwitch.h" #if defined(__APPLE__) +#ifndef HAVE_LIBCOMPRESSION #define HAVE_LIBCOMPRESSION +#endif #include <compression.h> #endif @@ -47,9 +48,7 @@ using namespace lldb_private::process_gdb_remote; using namespace std::chrono; -//---------------------------------------------------------------------- // GDBRemoteCommunicationClient constructor -//---------------------------------------------------------------------- GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"), m_supports_not_sending_acks(eLazyBoolCalculate), @@ -104,9 +103,7 @@ m_supported_async_json_packets_sp(), m_qXfer_memory_map(), m_qXfer_memory_map_loaded(false) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() { if (IsConnected()) Disconnect(); @@ -389,14 +386,14 @@ std::vector<std::string> supported_compressions; compressions += sizeof("SupportedCompressions=") - 1; const char *end_of_compressions = strchr(compressions, ';'); - if (end_of_compressions == NULL) { + if (end_of_compressions == nullptr) { end_of_compressions = strchr(compressions, '\0'); } const char *current_compression = compressions; while (current_compression < end_of_compressions) { const char *next_compression_name = strchr(current_compression, ','); const char *end_of_this_word = next_compression_name; - if (next_compression_name == NULL || + if (next_compression_name == nullptr || end_of_compressions < next_compression_name) { end_of_this_word = end_of_compressions; } @@ -778,7 +775,7 @@ std::vector<const char *> argv; FileSpec exe_file = launch_info.GetExecutableFile(); std::string exe_path; - const char *arg = NULL; + const char *arg = nullptr; const Args &launch_args = launch_info.GetArguments(); if (exe_file) exe_path = exe_file.GetPath(false); @@ -789,7 +786,7 @@ } if (!exe_path.empty()) { argv.push_back(exe_path.c_str()); - for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; + for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != nullptr; ++i) { if (arg) argv.push_back(arg); @@ -1097,7 +1094,7 @@ if (!m_gdb_server_name.empty()) return m_gdb_server_name.c_str(); } - return NULL; + return nullptr; } uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() { @@ -1714,28 +1711,22 @@ GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction( bool &after, const ArchSpec &arch) { Status error; - llvm::Triple::ArchType atype = arch.GetMachine(); + llvm::Triple triple = arch.GetTriple(); // we assume watchpoints will happen after running the relevant opcode and we // only want to override this behavior if we have explicitly received a // qHostInfo telling us otherwise if (m_qHostInfo_is_valid != eLazyBoolYes) { - // On targets like MIPS and ppc64le, watchpoint exceptions are always + // On targets like MIPS and ppc64, watchpoint exceptions are always // generated before the instruction is executed. The connected target may // not support qHostInfo or qWatchpointSupportInfo packets. - after = - !(atype == llvm::Triple::mips || atype == llvm::Triple::mipsel || - atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el || - atype == llvm::Triple::ppc64le); + after = !(triple.isMIPS() || triple.isPPC64()); } else { - // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to + // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to // eLazyBoolNo if it is not calculated before. - if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate && - (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel || - atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) || - atype == llvm::Triple::ppc64le) { + if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate && + (triple.isMIPS() || triple.isPPC64())) m_watchpoints_trigger_after_instruction = eLazyBoolNo; - } after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); } @@ -1747,7 +1738,7 @@ std::string path{file_spec.GetPath(false)}; StreamString packet; packet.PutCString("QSetSTDIN:"); - packet.PutCStringAsRawHex8(path.c_str()); + packet.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == @@ -1767,7 +1758,7 @@ std::string path{file_spec.GetPath(false)}; StreamString packet; packet.PutCString("QSetSTDOUT:"); - packet.PutCStringAsRawHex8(path.c_str()); + packet.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == @@ -1787,7 +1778,7 @@ std::string path{file_spec.GetPath(false)}; StreamString packet; packet.PutCString("QSetSTDERR:"); - packet.PutCStringAsRawHex8(path.c_str()); + packet.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == @@ -1823,7 +1814,7 @@ std::string path{working_dir.GetPath(false)}; StreamString packet; packet.PutCString("QSetWorkingDir:"); - packet.PutCStringAsRawHex8(path.c_str()); + packet.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == @@ -2060,6 +2051,7 @@ assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat); assert(triple.getObjectFormat() != llvm::Triple::Wasm); + assert(triple.getObjectFormat() != llvm::Triple::XCOFF); switch (triple.getObjectFormat()) { case llvm::Triple::MachO: m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub); @@ -2071,6 +2063,7 @@ m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub); break; case llvm::Triple::Wasm: + case llvm::Triple::XCOFF: if (log) log->Printf("error: not supported target architecture"); return false; @@ -2793,7 +2786,7 @@ if (working_dir) { std::string path{working_dir.GetPath(false)}; stream.PutChar(','); - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); } StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == @@ -2830,7 +2823,7 @@ stream.PutCString("qPlatform_mkdir:"); stream.PutHex32(file_permissions); stream.PutChar(','); - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); llvm::StringRef packet = stream.GetString(); StringExtractorGDBRemote response; @@ -2852,7 +2845,7 @@ stream.PutCString("qPlatform_chmod:"); stream.PutHex32(file_permissions); stream.PutChar(','); - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); llvm::StringRef packet = stream.GetString(); StringExtractorGDBRemote response; @@ -2893,7 +2886,7 @@ stream.PutCString("vFile:open:"); if (path.empty()) return UINT64_MAX; - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); stream.PutChar(','); stream.PutHex32(flags); stream.PutChar(','); @@ -2924,7 +2917,7 @@ std::string path(file_spec.GetPath(false)); lldb_private::StreamString stream; stream.PutCString("vFile:size:"); - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success) { @@ -2943,7 +2936,7 @@ Status error; lldb_private::StreamString stream; stream.PutCString("vFile:mode:"); - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success) { @@ -3045,9 +3038,9 @@ stream.PutCString("vFile:symlink:"); // the unix symlink() command reverses its parameters where the dst if first, // so we follow suit here - stream.PutCStringAsRawHex8(dst_path.c_str()); + stream.PutStringAsRawHex8(dst_path); stream.PutChar(','); - stream.PutCStringAsRawHex8(src_path.c_str()); + stream.PutStringAsRawHex8(src_path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success) { @@ -3078,7 +3071,7 @@ stream.PutCString("vFile:unlink:"); // the unix symlink() command reverses its parameters where the dst if first, // so we follow suit here - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success) { @@ -3108,7 +3101,7 @@ std::string path(file_spec.GetPath(false)); lldb_private::StreamString stream; stream.PutCString("vFile:exists:"); - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success) { @@ -3127,7 +3120,7 @@ std::string path(file_spec.GetPath(false)); lldb_private::StreamString stream; stream.PutCString("vFile:MD5:"); - stream.PutCStringAsRawHex8(path.c_str()); + stream.PutStringAsRawHex8(path); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success) { @@ -3508,10 +3501,10 @@ StreamString packet; packet.PutCString("qModuleInfo:"); - packet.PutCStringAsRawHex8(module_path.c_str()); + packet.PutStringAsRawHex8(module_path); packet.PutCString(";"); const auto &triple = arch_spec.GetTriple().getTriple(); - packet.PutCStringAsRawHex8(triple.c_str()); + packet.PutStringAsRawHex8(triple); StringExtractorGDBRemote response; if (SendPacketAndWaitForResponse(packet.GetString(), response, false) != @@ -3955,7 +3948,7 @@ } Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( - const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { + ConstString type_name, const StructuredData::ObjectSP &config_sp) { Status error; if (type_name.GetLength() == 0) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h index 37d53ab..de85c9f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationClient.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,12 +17,15 @@ #include <string> #include <vector> -#include "lldb/Target/Process.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/StreamGDBRemote.h" #include "lldb/Utility/StructuredData.h" +#if defined(_WIN32) +#include "lldb/Host/windows/PosixApi.h" +#endif #include "llvm/ADT/Optional.h" +#include "llvm/Support/VersionTuple.h" namespace lldb_private { namespace process_gdb_remote { @@ -34,10 +36,8 @@ ~GDBRemoteCommunicationClient() override; - //------------------------------------------------------------------ // After connecting, send the handshake to the server to make sure // we are communicating with it. - //------------------------------------------------------------------ bool HandshakeWithServer(Status *error_ptr); // For packets which specify a range of output to be returned, @@ -85,39 +85,35 @@ bool KillSpawnedProcess(lldb::pid_t pid); - //------------------------------------------------------------------ /// Sends a GDB remote protocol 'A' packet that delivers program /// arguments to the remote server. /// - /// @param[in] argv + /// \param[in] argv /// A NULL terminated array of const C strings to use as the /// arguments. /// - /// @return + /// \return /// Zero if the response was "OK", a positive value if the /// the response was "Exx" where xx are two hex digits, or /// -1 if the call is unsupported or any other unexpected /// response was received. - //------------------------------------------------------------------ int SendArgumentsPacket(const ProcessLaunchInfo &launch_info); - //------------------------------------------------------------------ /// Sends a "QEnvironment:NAME=VALUE" packet that will build up the /// environment that will get used when launching an application /// in conjunction with the 'A' packet. This function can be called /// multiple times in a row in order to pass on the desired /// environment that the inferior should be launched with. /// - /// @param[in] name_equal_value + /// \param[in] name_equal_value /// A NULL terminated C string that contains a single environment /// in the format "NAME=VALUE". /// - /// @return + /// \return /// Zero if the response was "OK", a positive value if the /// the response was "Exx" where xx are two hex digits, or /// -1 if the call is unsupported or any other unexpected /// response was received. - //------------------------------------------------------------------ int SendEnvironmentPacket(char const *name_equal_value); int SendEnvironment(const Environment &env); @@ -126,102 +122,88 @@ int SendLaunchEventDataPacket(const char *data, bool *was_supported = nullptr); - //------------------------------------------------------------------ /// Sends a "vAttach:PID" where PID is in hex. /// - /// @param[in] pid + /// \param[in] pid /// A process ID for the remote gdb server to attach to. /// - /// @param[out] response + /// \param[out] response /// The response received from the gdb server. If the return /// value is zero, \a response will contain a stop reply /// packet. /// - /// @return + /// \return /// Zero if the attach was successful, or an error indicating /// an error code. - //------------------------------------------------------------------ int SendAttach(lldb::pid_t pid, StringExtractorGDBRemote &response); - //------------------------------------------------------------------ /// Sends a GDB remote protocol 'I' packet that delivers stdin /// data to the remote process. /// - /// @param[in] data + /// \param[in] data /// A pointer to stdin data. /// - /// @param[in] data_len + /// \param[in] data_len /// The number of bytes available at \a data. /// - /// @return + /// \return /// Zero if the attach was successful, or an error indicating /// an error code. - //------------------------------------------------------------------ int SendStdinNotification(const char *data, size_t data_len); - //------------------------------------------------------------------ /// Sets the path to use for stdin/out/err for a process /// that will be launched with the 'A' packet. /// - /// @param[in] path + /// \param[in] path /// The path to use for stdin/out/err /// - /// @return + /// \return /// Zero if the for success, or an error code for failure. - //------------------------------------------------------------------ int SetSTDIN(const FileSpec &file_spec); int SetSTDOUT(const FileSpec &file_spec); int SetSTDERR(const FileSpec &file_spec); - //------------------------------------------------------------------ /// Sets the disable ASLR flag to \a enable for a process that will /// be launched with the 'A' packet. /// - /// @param[in] enable + /// \param[in] enable /// A boolean value indicating whether to disable ASLR or not. /// - /// @return + /// \return /// Zero if the for success, or an error code for failure. - //------------------------------------------------------------------ int SetDisableASLR(bool enable); - //------------------------------------------------------------------ /// Sets the DetachOnError flag to \a enable for the process controlled by the /// stub. /// - /// @param[in] enable + /// \param[in] enable /// A boolean value indicating whether to detach on error or not. /// - /// @return + /// \return /// Zero if the for success, or an error code for failure. - //------------------------------------------------------------------ int SetDetachOnError(bool enable); - //------------------------------------------------------------------ /// Sets the working directory to \a path for a process that will /// be launched with the 'A' packet for non platform based /// connections. If this packet is sent to a GDB server that /// implements the platform, it will change the current working /// directory for the platform process. /// - /// @param[in] working_dir + /// \param[in] working_dir /// The path to a directory to use when launching our process /// - /// @return + /// \return /// Zero if the for success, or an error code for failure. - //------------------------------------------------------------------ int SetWorkingDir(const FileSpec &working_dir); - //------------------------------------------------------------------ /// Gets the current working directory of a remote platform GDB /// server. /// - /// @param[out] working_dir + /// \param[out] working_dir /// The current working directory on the remote platform. /// - /// @return + /// \return /// Boolean for success - //------------------------------------------------------------------ bool GetWorkingDir(FileSpec &working_dir); lldb::addr_t AllocateMemory(size_t size, uint32_t permissions); @@ -456,21 +438,18 @@ // Sends QPassSignals packet to the server with given signals to ignore. Status SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals); - //------------------------------------------------------------------ /// Return the feature set supported by the gdb-remote server. /// /// This method returns the remote side's response to the qSupported /// packet. The response is the complete string payload returned /// to the client. /// - /// @return + /// \return /// The string returned by the server to the qSupported query. - //------------------------------------------------------------------ const std::string &GetServerSupportedFeatures() const { return m_qSupported_response; } - //------------------------------------------------------------------ /// Return the array of async JSON packet types supported by the remote. /// /// This method returns the remote side's array of supported JSON @@ -486,18 +465,15 @@ /// A plugin indicates whether it knows how to handle a type_name. /// If so, it can be used to process the async JSON packet. /// - /// @return + /// \return /// The string returned by the server to the qSupported query. - //------------------------------------------------------------------ lldb_private::StructuredData::Array *GetSupportedStructuredDataPlugins(); - //------------------------------------------------------------------ /// Configure a StructuredData feature on the remote end. /// - /// @see \b Process::ConfigureStructuredData(...) for details. - //------------------------------------------------------------------ + /// \see \b Process::ConfigureStructuredData(...) for details. Status - ConfigureRemoteStructuredData(const ConstString &type_name, + ConfigureRemoteStructuredData(ConstString type_name, const StructuredData::ObjectSP &config_sp); lldb::user_id_t SendStartTracePacket(const TraceOptions &options,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.cpp index 69b13f2..bcddb4f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationHistory.cpp -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -46,7 +45,7 @@ m_packets[idx].bytes_transmitted = bytes_transmitted; m_packets[idx].packet_idx = m_total_packet_count; m_packets[idx].tid = llvm::get_threadid(); - if (m_stream && type == ePacketTypeRecv) + if (m_stream) m_packets[idx].Serialize(*m_stream); } @@ -63,7 +62,7 @@ m_packets[idx].bytes_transmitted = bytes_transmitted; m_packets[idx].packet_idx = m_total_packet_count; m_packets[idx].tid = llvm::get_threadid(); - if (m_stream && type == ePacketTypeRecv) + if (m_stream) m_packets[idx].Serialize(*m_stream); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.h index d0ca6a0..85f112b 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationHistory.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationHistory.h--------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp index 6a78eb2..417f573 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationReplayServer.cpp ------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,12 +30,49 @@ using namespace lldb_private; using namespace lldb_private::process_gdb_remote; +/// Check if the given expected packet matches the actual packet. +static bool unexpected(llvm::StringRef expected, llvm::StringRef actual) { + // The 'expected' string contains the raw data, including the leading $ and + // trailing checksum. The 'actual' string contains only the packet's content. + if (expected.contains(actual)) + return false; + // Contains a PID which might be different. + if (expected.contains("vAttach")) + return false; + // Contains a ascii-hex-path. + if (expected.contains("QSetSTD")) + return false; + // Contains environment values. + if (expected.contains("QEnvironment")) + return false; + + return true; +} + +/// Check if we should reply to the given packet. +static bool skip(llvm::StringRef data) { + assert(!data.empty() && "Empty packet?"); + + // We've already acknowledge the '+' packet so we're done here. + if (data == "+") + return true; + + /// Don't 't reply to ^C. We need this because of stop reply packets, which + /// are only returned when the target halts. Reproducers synchronize these + /// 'asynchronous' replies, by recording them as a regular replies to the + /// previous packet (e.g. vCont). As a result, we should ignore real + /// asynchronous requests. + if (data.data()[0] == 0x03) + return true; + + return false; +} + GDBRemoteCommunicationReplayServer::GDBRemoteCommunicationReplayServer() - : GDBRemoteCommunication("gdb-remote.server", - "gdb-remote.server.rx_packet"), - m_async_broadcaster(nullptr, "lldb.gdb-remote.server.async-broadcaster"), + : GDBRemoteCommunication("gdb-replay", "gdb-replay.rx_packet"), + m_async_broadcaster(nullptr, "lldb.gdb-replay.async-broadcaster"), m_async_listener_sp( - Listener::MakeListener("lldb.gdb-remote.server.async-listener")), + Listener::MakeListener("lldb.gdb-replay.async-listener")), m_async_thread_state_mutex(), m_skip_acks(false) { m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, "async thread continue"); @@ -56,6 +92,8 @@ GDBRemoteCommunication::PacketResult GDBRemoteCommunicationReplayServer::GetPacketAndSendResponse( Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) { + std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); + StringExtractorGDBRemote packet; PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false); @@ -71,32 +109,65 @@ m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); - if (m_skip_acks) { - const StringExtractorGDBRemote::ServerPacketType packet_type = - packet.GetServerPacketType(); - switch (packet_type) { - case StringExtractorGDBRemote::eServerPacketType_nack: - case StringExtractorGDBRemote::eServerPacketType_ack: - return PacketResult::Success; - default: - break; - } - } else if (packet.GetStringRef() == "QStartNoAckMode") { - m_skip_acks = true; - m_send_acks = false; - } + // Check if we should reply to this packet. + if (skip(packet.GetStringRef())) + return PacketResult::Success; + // This completes the handshake. Since m_send_acks was true, we can unset it + // already. + if (packet.GetStringRef() == "QStartNoAckMode") + m_send_acks = false; + + // A QEnvironment packet is sent for every environment variable. If the + // number of environment variables is different during replay, the replies + // become out of sync. + if (packet.GetStringRef().find("QEnvironment") == 0) + return SendRawPacketNoLock("$OK#9a"); + + Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); while (!m_packet_history.empty()) { // Pop last packet from the history. GDBRemoteCommunicationHistory::Entry entry = m_packet_history.back(); m_packet_history.pop_back(); - // We only care about what we received from the server. Skip everything - // the client sent. - if (entry.type != GDBRemoteCommunicationHistory::ePacketTypeRecv) + // We've handled the handshake implicitly before. Skip the packet and move + // on. + if (entry.packet.data == "+") continue; - return SendRawPacketNoLock(entry.packet.data, true); + if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeSend) { + if (unexpected(entry.packet.data, packet.GetStringRef())) { + LLDB_LOG(log, + "GDBRemoteCommunicationReplayServer expected packet: '{0}'", + entry.packet.data); + LLDB_LOG(log, "GDBRemoteCommunicationReplayServer actual packet: '{0}'", + packet.GetStringRef()); + assert(false && "Encountered unexpected packet during replay"); + return PacketResult::ErrorSendFailed; + } + + // Ignore QEnvironment packets as they're handled earlier. + if (entry.packet.data.find("QEnvironment") == 1) { + assert(m_packet_history.back().type == + GDBRemoteCommunicationHistory::ePacketTypeRecv); + m_packet_history.pop_back(); + } + + continue; + } + + if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeInvalid) { + LLDB_LOG( + log, + "GDBRemoteCommunicationReplayServer skipped invalid packet: '{0}'", + packet.GetStringRef()); + continue; + } + + LLDB_LOG(log, + "GDBRemoteCommunicationReplayServer replied to '{0}' with '{1}'", + packet.GetStringRef(), entry.packet.data); + return SendRawPacketNoLock(entry.packet.data); } quit = true; @@ -132,9 +203,16 @@ if (!m_async_thread.IsJoinable()) { // Create a thread that watches our internal state and controls which // events make it to clients (into the DCProcess event queue). - m_async_thread = ThreadLauncher::LaunchThread( - "<lldb.gdb-remote.server.async>", - GDBRemoteCommunicationReplayServer::AsyncThread, this, nullptr); + llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( + "<lldb.gdb-replay.async>", + GDBRemoteCommunicationReplayServer::AsyncThread, this); + if (!async_thread) { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(async_thread.takeError())); + return false; + } + m_async_thread = *async_thread; } // Wait for handshake.
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.h index 5b840c8..26d65e2 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationReplayServer.h --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp index 026f781..49cbeb0 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServer.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -107,13 +106,29 @@ if (m_send_error_strings) { lldb_private::StreamString packet; packet.Printf("E%2.2x;", static_cast<uint8_t>(error.GetError())); - packet.PutCStringAsRawHex8(error.AsCString()); + packet.PutStringAsRawHex8(error.AsCString()); return SendPacketNoLock(packet.GetString()); } else return SendErrorResponse(error.GetError()); } GDBRemoteCommunication::PacketResult +GDBRemoteCommunicationServer::SendErrorResponse(llvm::Error error) { + std::unique_ptr<llvm::ErrorInfoBase> EIB; + std::unique_ptr<PacketUnimplementedError> PUE; + llvm::handleAllErrors( + std::move(error), + [&](std::unique_ptr<PacketUnimplementedError> E) { PUE = std::move(E); }, + [&](std::unique_ptr<llvm::ErrorInfoBase> E) { EIB = std::move(E); }); + + if (EIB) + return SendErrorResponse(Status(llvm::Error(std::move(EIB)))); + if (PUE) + return SendUnimplementedResponse(PUE->message().c_str()); + return SendErrorResponse(Status("Unknown Error")); +} + +GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServer::Handle_QErrorStringEnable( StringExtractorGDBRemote &packet) { m_send_error_strings = true; @@ -139,3 +154,5 @@ bool GDBRemoteCommunicationServer::HandshakeWithClient() { return GetAck() == PacketResult::Success; } + +char PacketUnimplementedError::ID;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h index 082fb0d..86f0abf 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServer.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,6 +15,9 @@ #include "GDBRemoteCommunication.h" #include "lldb/lldb-private-forward.h" +#include "llvm/Support/Errc.h" +#include "llvm/Support/Error.h" + class StringExtractorGDBRemote; namespace lldb_private { @@ -60,6 +62,8 @@ PacketResult SendErrorResponse(const Status &error); + PacketResult SendErrorResponse(llvm::Error error); + PacketResult SendUnimplementedResponse(const char *packet); PacketResult SendErrorResponse(uint8_t error); @@ -73,6 +77,18 @@ DISALLOW_COPY_AND_ASSIGN(GDBRemoteCommunicationServer); }; +class PacketUnimplementedError + : public llvm::ErrorInfo<PacketUnimplementedError, llvm::StringError> { +public: + static char ID; + using llvm::ErrorInfo<PacketUnimplementedError, + llvm::StringError>::ErrorInfo; // inherit constructors + PacketUnimplementedError(const llvm::Twine &S) + : ErrorInfo(S, llvm::errc::not_supported) {} + + PacketUnimplementedError() : ErrorInfo(llvm::errc::not_supported) {} +}; + } // namespace process_gdb_remote } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp index f11ef4f..d095c7a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServerCommon.cpp ------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,7 +10,6 @@ #include <errno.h> - #ifdef __APPLE__ #include <TargetConditionals.h> #endif @@ -22,20 +20,20 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/Config.h" #include "lldb/Host/File.h" +#include "lldb/Host/FileAction.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Host/SafeMachO.h" #include "lldb/Interpreter/OptionArgParser.h" #include "lldb/Symbol/ObjectFile.h" -#include "lldb/Target/FileAction.h" #include "lldb/Target/Platform.h" -#include "lldb/Target/Process.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/JSON.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamGDBRemote.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/StructuredData.h" #include "llvm/ADT/Triple.h" #include "ProcessGDBRemoteLog.h" @@ -57,9 +55,7 @@ const static uint32_t g_default_packet_timeout_sec = 0; // not specified #endif -//---------------------------------------------------------------------- // GDBRemoteCommunicationServerCommon constructor -//---------------------------------------------------------------------- GDBRemoteCommunicationServerCommon::GDBRemoteCommunicationServerCommon( const char *comm_name, const char *listener_name) : GDBRemoteCommunicationServer(comm_name, listener_name), @@ -178,9 +174,7 @@ &GDBRemoteCommunicationServerCommon::Handle_vFile_unlink); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- GDBRemoteCommunicationServerCommon::~GDBRemoteCommunicationServerCommon() {} GDBRemoteCommunication::PacketResult @@ -193,13 +187,13 @@ ArchSpec host_arch(HostInfo::GetArchitecture()); const llvm::Triple &host_triple = host_arch.GetTriple(); response.PutCString("triple:"); - response.PutCStringAsRawHex8(host_triple.getTriple().c_str()); + response.PutStringAsRawHex8(host_triple.getTriple()); response.Printf(";ptrsize:%u;", host_arch.GetAddressByteSize()); const char *distribution_id = host_arch.GetDistributionId().AsCString(); if (distribution_id) { response.PutCString("distribution_id:"); - response.PutCStringAsRawHex8(distribution_id); + response.PutStringAsRawHex8(distribution_id); response.PutCString(";"); } @@ -215,8 +209,7 @@ if (sub != LLDB_INVALID_CPUTYPE) response.Printf("cpusubtype:%u;", sub); - if (cpu == llvm::MachO::CPU_TYPE_ARM - || cpu == llvm::MachO::CPU_TYPE_ARM64) { + if (cpu == llvm::MachO::CPU_TYPE_ARM || cpu == llvm::MachO::CPU_TYPE_ARM64) { // Indicate the OS type. #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1 response.PutCString("ostype:tvos;"); @@ -240,11 +233,7 @@ if (host_arch.GetMachine() == llvm::Triple::aarch64 || host_arch.GetMachine() == llvm::Triple::aarch64_be || host_arch.GetMachine() == llvm::Triple::arm || - host_arch.GetMachine() == llvm::Triple::armeb || - host_arch.GetMachine() == llvm::Triple::mips64 || - host_arch.GetMachine() == llvm::Triple::mips64el || - host_arch.GetMachine() == llvm::Triple::mips || - host_arch.GetMachine() == llvm::Triple::mipsel) + host_arch.GetMachine() == llvm::Triple::armeb || host_arch.IsMIPS()) response.Printf("watchpoint_exceptions_received:before;"); else response.Printf("watchpoint_exceptions_received:after;"); @@ -274,12 +263,12 @@ std::string s; if (HostInfo::GetOSBuildString(s)) { response.PutCString("os_build:"); - response.PutCStringAsRawHex8(s.c_str()); + response.PutStringAsRawHex8(s); response.PutChar(';'); } if (HostInfo::GetOSKernelDescription(s)) { response.PutCString("os_kernel:"); - response.PutCStringAsRawHex8(s.c_str()); + response.PutStringAsRawHex8(s); response.PutChar(';'); } @@ -290,12 +279,12 @@ // actually have a hostname as far as the remote lldb that is connecting to // this lldb-platform is concerned response.PutCString("hostname:"); - response.PutCStringAsRawHex8("127.0.0.1"); + response.PutStringAsRawHex8("127.0.0.1"); response.PutChar(';'); #else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) if (HostInfo::GetHostname(s)) { response.PutCString("hostname:"); - response.PutCStringAsRawHex8(s.c_str()); + response.PutStringAsRawHex8(s); response.PutChar(';'); } #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) @@ -303,7 +292,7 @@ #else // #if defined(__APPLE__) if (HostInfo::GetHostname(s)) { response.PutCString("hostname:"); - response.PutCStringAsRawHex8(s.c_str()); + response.PutStringAsRawHex8(s); response.PutChar(';'); } #endif // #if defined(__APPLE__) @@ -439,10 +428,10 @@ packet.SetFilePos(::strlen("qUserName:")); uint32_t uid = packet.GetU32(UINT32_MAX); if (uid != UINT32_MAX) { - std::string name; - if (HostInfo::LookupUserName(uid, name)) { + if (llvm::Optional<llvm::StringRef> name = + HostInfo::GetUserIDResolver().GetUserName(uid)) { StreamString response; - response.PutCStringAsRawHex8(name.c_str()); + response.PutStringAsRawHex8(*name); return SendPacketNoLock(response.GetString()); } } @@ -460,10 +449,10 @@ packet.SetFilePos(::strlen("qGroupName:")); uint32_t gid = packet.GetU32(UINT32_MAX); if (gid != UINT32_MAX) { - std::string name; - if (HostInfo::LookupGroupName(gid, name)) { + if (llvm::Optional<llvm::StringRef> name = + HostInfo::GetUserIDResolver().GetGroupName(gid)) { StreamString response; - response.PutCStringAsRawHex8(name.c_str()); + response.PutStringAsRawHex8(*name); return SendPacketNoLock(response.GetString()); } } @@ -511,18 +500,19 @@ packet.GetHexByteStringTerminatedBy(path, ','); if (!path.empty()) { if (packet.GetChar() == ',') { - uint32_t flags = - File::ConvertOpenOptionsForPOSIXOpen(packet.GetHexMaxU32(false, 0)); + uint32_t flags = packet.GetHexMaxU32(false, 0); if (packet.GetChar() == ',') { mode_t mode = packet.GetHexMaxU32(false, 0600); - Status error; FileSpec path_spec(path); FileSystem::Instance().Resolve(path_spec); - int fd = ::open(path_spec.GetCString(), flags, mode); - const int save_errno = fd == -1 ? errno : 0; + File file; + // Do not close fd. + Status error = + FileSystem::Instance().Open(file, path_spec, flags, mode, false); + const int save_errno = error.GetError(); StreamString response; response.PutChar('F'); - response.Printf("%i", fd); + response.Printf("%i", file.GetDescriptor()); if (save_errno) response.Printf(",%i", save_errno); return SendPacketNoLock(response.GetString()); @@ -537,12 +527,13 @@ StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:close:")); int fd = packet.GetS32(-1); - Status error; int err = -1; int save_errno = 0; if (fd >= 0) { - err = close(fd); - save_errno = err == -1 ? errno : 0; + File file(fd, true); + Status error = file.Close(); + err = 0; + save_errno = error.GetError(); } else { save_errno = EINVAL; } @@ -557,26 +548,23 @@ GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_pRead( StringExtractorGDBRemote &packet) { -#ifdef _WIN32 - // Not implemented on Windows - return SendUnimplementedResponse( - "GDBRemoteCommunicationServerCommon::Handle_vFile_pRead() unimplemented"); -#else StreamGDBRemote response; packet.SetFilePos(::strlen("vFile:pread:")); int fd = packet.GetS32(-1); if (packet.GetChar() == ',') { - uint64_t count = packet.GetU64(UINT64_MAX); + size_t count = packet.GetU64(UINT64_MAX); if (packet.GetChar() == ',') { - uint64_t offset = packet.GetU64(UINT32_MAX); + off_t offset = packet.GetU64(UINT32_MAX); if (count == UINT64_MAX) { response.Printf("F-1:%i", EINVAL); return SendPacketNoLock(response.GetString()); } std::string buffer(count, 0); - const ssize_t bytes_read = ::pread(fd, &buffer[0], buffer.size(), offset); - const int save_errno = bytes_read == -1 ? errno : 0; + File file(fd, false); + Status error = file.Read(static_cast<void *>(&buffer[0]), count, offset); + const ssize_t bytes_read = error.Success() ? count : -1; + const int save_errno = error.GetError(); response.PutChar('F'); response.Printf("%zi", bytes_read); if (save_errno) @@ -589,17 +577,11 @@ } } return SendErrorResponse(21); - -#endif } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite( StringExtractorGDBRemote &packet) { -#ifdef _WIN32 - return SendUnimplementedResponse("GDBRemoteCommunicationServerCommon::Handle_" - "vFile_pWrite() unimplemented"); -#else packet.SetFilePos(::strlen("vFile:pwrite:")); StreamGDBRemote response; @@ -611,9 +593,12 @@ if (packet.GetChar() == ',') { std::string buffer; if (packet.GetEscapedBinaryData(buffer)) { - const ssize_t bytes_written = - ::pwrite(fd, buffer.data(), buffer.size(), offset); - const int save_errno = bytes_written == -1 ? errno : 0; + File file(fd, false); + size_t count = buffer.size(); + Status error = + file.Write(static_cast<const void *>(&buffer[0]), count, offset); + const ssize_t bytes_written = error.Success() ? count : -1; + const int save_errno = error.GetError(); response.Printf("%zi", bytes_written); if (save_errno) response.Printf(",%i", save_errno); @@ -624,7 +609,6 @@ } } return SendErrorResponse(27); -#endif } GDBRemoteCommunication::PacketResult @@ -972,7 +956,8 @@ const uint32_t bytes_left = packet.GetBytesLeft(); if (bytes_left > 0) { const char *arch_triple = packet.Peek(); - m_process_launch_info.SetArchitecture(HostInfo::GetAugmentedArchSpec(arch_triple)); + m_process_launch_info.SetArchitecture( + HostInfo::GetAugmentedArchSpec(arch_triple)); return SendOKResponse(); } return SendErrorResponse(13); @@ -1086,24 +1071,25 @@ StreamGDBRemote response; if (uuid_str.empty()) { - auto Result = llvm::sys::fs::md5_contents(matched_module_spec.GetFileSpec().GetPath()); + auto Result = llvm::sys::fs::md5_contents( + matched_module_spec.GetFileSpec().GetPath()); if (!Result) return SendErrorResponse(5); response.PutCString("md5:"); - response.PutCStringAsRawHex8(Result->digest().c_str()); + response.PutStringAsRawHex8(Result->digest()); } else { response.PutCString("uuid:"); - response.PutCStringAsRawHex8(uuid_str.c_str()); + response.PutStringAsRawHex8(uuid_str); } response.PutChar(';'); const auto &module_arch = matched_module_spec.GetArchitecture(); response.PutCString("triple:"); - response.PutCStringAsRawHex8(module_arch.GetTriple().getTriple().c_str()); + response.PutStringAsRawHex8(module_arch.GetTriple().getTriple()); response.PutChar(';'); response.PutCString("file_path:"); - response.PutCStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString()); + response.PutStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString()); response.PutChar(';'); response.PutCString("file_offset:"); response.PutHex64(file_offset); @@ -1181,13 +1167,13 @@ proc_info.GetUserID(), proc_info.GetGroupID(), proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID()); response.PutCString("name:"); - response.PutCStringAsRawHex8(proc_info.GetExecutableFile().GetCString()); + response.PutStringAsRawHex8(proc_info.GetExecutableFile().GetCString()); response.PutChar(';'); const ArchSpec &proc_arch = proc_info.GetArchitecture(); if (proc_arch.IsValid()) { const llvm::Triple &proc_triple = proc_arch.GetTriple(); response.PutCString("triple:"); - response.PutCStringAsRawHex8(proc_triple.getTriple().c_str()); + response.PutStringAsRawHex8(proc_triple.getTriple()); response.PutChar(';'); } } @@ -1221,7 +1207,7 @@ #else // We'll send the triple. response.PutCString("triple:"); - response.PutCStringAsRawHex8(proc_triple.getTriple().c_str()); + response.PutStringAsRawHex8(proc_triple.getTriple()); response.PutChar(';'); #endif std::string ostype = proc_triple.getOSName();
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h index f3825bb..5255463 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServerCommon.h --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,7 +11,7 @@ #include <string> -#include "lldb/Target/Process.h" +#include "lldb/Host/ProcessLaunchInfo.h" #include "lldb/lldb-private-forward.h" #include "GDBRemoteCommunicationServer.h" @@ -132,17 +131,15 @@ }); } - //------------------------------------------------------------------ /// Launch a process with the current launch settings. /// /// This method supports running an lldb-gdbserver or similar /// server in a situation where the startup code has been provided /// with all the information for a child process to be launched. /// - /// @return + /// \return /// An Status object indicating the success or failure of the /// launch. - //------------------------------------------------------------------ virtual Status LaunchProcess() = 0; virtual FileSpec FindModuleFile(const std::string &module_path,
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp index cdb63e7..1966076 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,6 +20,7 @@ #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/Debug.h" #include "lldb/Host/File.h" +#include "lldb/Host/FileAction.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" @@ -28,7 +28,6 @@ #include "lldb/Host/common/NativeProcessProtocol.h" #include "lldb/Host/common/NativeRegisterContext.h" #include "lldb/Host/common/NativeThreadProtocol.h" -#include "lldb/Target/FileAction.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/DataBuffer.h" @@ -52,9 +51,7 @@ using namespace lldb_private::process_gdb_remote; using namespace llvm; -//---------------------------------------------------------------------- // GDBRemote Errors -//---------------------------------------------------------------------- namespace { enum GDBRemoteServerError { @@ -66,9 +63,7 @@ }; } -//---------------------------------------------------------------------- // GDBRemoteCommunicationServerLLGS constructor -//---------------------------------------------------------------------- GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS( MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory) : GDBRemoteCommunicationServerCommon("gdb-remote.server", @@ -149,8 +144,8 @@ StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo, &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo); RegisterMemberFunctionHandler( - StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read, - &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read); + StringExtractorGDBRemote::eServerPacketType_qXfer, + &GDBRemoteCommunicationServerLLGS::Handle_qXfer); RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s, &GDBRemoteCommunicationServerLLGS::Handle_s); RegisterMemberFunctionHandler( @@ -192,6 +187,9 @@ StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead, &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead); + RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g, + &GDBRemoteCommunicationServerLLGS::Handle_g); + RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k, [this](StringExtractorGDBRemote packet, Status &error, bool &interrupt, bool &quit) { @@ -623,7 +621,7 @@ } else { // The thread name contains special chars, send as hex bytes. response.PutCString("hexname:"); - response.PutCStringAsRawHex8(thread_name.c_str()); + response.PutStringAsRawHex8(thread_name); } response.PutChar(';'); } @@ -663,7 +661,7 @@ response.PutCString("jstopinfo:"); StreamString unescaped_response; threads_info_sp->Write(unescaped_response); - response.PutCStringAsRawHex8(unescaped_response.GetData()); + response.PutStringAsRawHex8(unescaped_response.GetData()); response.PutChar(';'); } else LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}", @@ -764,7 +762,7 @@ if (!description.empty()) { // Description may contains special chars, send as hex bytes. response.PutCString("description:"); - response.PutCStringAsRawHex8(description.c_str()); + response.PutStringAsRawHex8(description); response.PutChar(';'); } else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type) { @@ -1341,7 +1339,7 @@ FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()}; if (working_dir) { StreamString response; - response.PutCStringAsRawHex8(working_dir.GetCString()); + response.PutStringAsRawHex8(working_dir.GetCString()); return SendPacketNoLock(response.GetString()); } @@ -1897,6 +1895,61 @@ } GDBRemoteCommunication::PacketResult +GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) { + Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); + + // Move past packet name. + packet.SetFilePos(strlen("g")); + + // Get the thread to use. + NativeThreadProtocol *thread = GetThreadFromSuffix(packet); + if (!thread) { + LLDB_LOG(log, "failed, no thread available"); + return SendErrorResponse(0x15); + } + + // Get the thread's register context. + NativeRegisterContext ®_ctx = thread->GetRegisterContext(); + + std::vector<uint8_t> regs_buffer; + for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount(); + ++reg_num) { + const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num); + + if (reg_info == nullptr) { + LLDB_LOG(log, "failed to get register info for register index {0}", + reg_num); + return SendErrorResponse(0x15); + } + + if (reg_info->value_regs != nullptr) + continue; // skip registers that are contained in other registers + + RegisterValue reg_value; + Status error = reg_ctx.ReadRegister(reg_info, reg_value); + if (error.Fail()) { + LLDB_LOG(log, "failed to read register at index {0}", reg_num); + return SendErrorResponse(0x15); + } + + if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size()) + // Resize the buffer to guarantee it can store the register offsetted + // data. + regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size); + + // Copy the register offsetted data to the buffer. + memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(), + reg_info->byte_size); + } + + // Write the response. + StreamGDBRemote response; + response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size()); + + return SendPacketNoLock(response.GetString()); +} + +GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD)); @@ -2426,7 +2479,7 @@ // Return the error message. response.PutCString("error:"); - response.PutCStringAsRawHex8(error.AsCString()); + response.PutStringAsRawHex8(error.AsCString()); response.PutChar(';'); } else { // Range start and size. @@ -2454,7 +2507,7 @@ ConstString name = region_info.GetName(); if (name) { response.PutCString("name:"); - response.PutCStringAsRawHex8(name.AsCString()); + response.PutStringAsRawHex8(name.AsCString()); response.PutChar(';'); } } @@ -2694,94 +2747,99 @@ return PacketResult::Success; } -GDBRemoteCommunication::PacketResult -GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read( - StringExtractorGDBRemote &packet) { -// *BSD impls should be able to do this too. -#if defined(__linux__) || defined(__NetBSD__) - Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); - - // Parse out the offset. - packet.SetFilePos(strlen("qXfer:auxv:read::")); - if (packet.GetBytesLeft() < 1) - return SendIllFormedResponse(packet, - "qXfer:auxv:read:: packet missing offset"); - - const uint64_t auxv_offset = - packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); - if (auxv_offset == std::numeric_limits<uint64_t>::max()) - return SendIllFormedResponse(packet, - "qXfer:auxv:read:: packet missing offset"); - - // Parse out comma. - if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',') - return SendIllFormedResponse( - packet, "qXfer:auxv:read:: packet missing comma after offset"); - - // Parse out the length. - const uint64_t auxv_length = - packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); - if (auxv_length == std::numeric_limits<uint64_t>::max()) - return SendIllFormedResponse(packet, - "qXfer:auxv:read:: packet missing length"); - - // Grab the auxv data if we need it. - if (!m_active_auxv_buffer_up) { +llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> +GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object, + llvm::StringRef annex) { + if (object == "auxv") { // Make sure we have a valid process. if (!m_debugged_process_up || (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) { - if (log) - log->Printf( - "GDBRemoteCommunicationServerLLGS::%s failed, no process available", - __FUNCTION__); - return SendErrorResponse(0x10); + return llvm::createStringError(llvm::inconvertibleErrorCode(), + "No process available"); } // Grab the auxv data. auto buffer_or_error = m_debugged_process_up->GetAuxvData(); - if (!buffer_or_error) { - std::error_code ec = buffer_or_error.getError(); - LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message()); - return SendErrorResponse(ec.value()); - } - m_active_auxv_buffer_up = std::move(*buffer_or_error); + if (!buffer_or_error) + return llvm::errorCodeToError(buffer_or_error.getError()); + return std::move(*buffer_or_error); } + return llvm::make_error<PacketUnimplementedError>( + "Xfer object not supported"); +} + +GDBRemoteCommunication::PacketResult +GDBRemoteCommunicationServerLLGS::Handle_qXfer( + StringExtractorGDBRemote &packet) { + SmallVector<StringRef, 5> fields; + // The packet format is "qXfer:<object>:<action>:<annex>:offset,length" + StringRef(packet.GetStringRef()).split(fields, ':', 4); + if (fields.size() != 5) + return SendIllFormedResponse(packet, "malformed qXfer packet"); + StringRef &xfer_object = fields[1]; + StringRef &xfer_action = fields[2]; + StringRef &xfer_annex = fields[3]; + StringExtractor offset_data(fields[4]); + if (xfer_action != "read") + return SendUnimplementedResponse("qXfer action not supported"); + // Parse offset. + const uint64_t xfer_offset = + offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); + if (xfer_offset == std::numeric_limits<uint64_t>::max()) + return SendIllFormedResponse(packet, "qXfer packet missing offset"); + // Parse out comma. + if (offset_data.GetChar() != ',') + return SendIllFormedResponse(packet, + "qXfer packet missing comma after offset"); + // Parse out the length. + const uint64_t xfer_length = + offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); + if (xfer_length == std::numeric_limits<uint64_t>::max()) + return SendIllFormedResponse(packet, "qXfer packet missing length"); + + // Get a previously constructed buffer if it exists or create it now. + std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str(); + auto buffer_it = m_xfer_buffer_map.find(buffer_key); + if (buffer_it == m_xfer_buffer_map.end()) { + auto buffer_up = ReadXferObject(xfer_object, xfer_annex); + if (!buffer_up) + return SendErrorResponse(buffer_up.takeError()); + buffer_it = m_xfer_buffer_map + .insert(std::make_pair(buffer_key, std::move(*buffer_up))) + .first; + } + + // Send back the response StreamGDBRemote response; bool done_with_buffer = false; - - llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer(); - if (auxv_offset >= buffer.size()) { + llvm::StringRef buffer = buffer_it->second->getBuffer(); + if (xfer_offset >= buffer.size()) { // We have nothing left to send. Mark the buffer as complete. response.PutChar('l'); done_with_buffer = true; } else { // Figure out how many bytes are available starting at the given offset. - buffer = buffer.drop_front(auxv_offset); - + buffer = buffer.drop_front(xfer_offset); // Mark the response type according to whether we're reading the remainder - // of the auxv data. - if (auxv_length >= buffer.size()) { + // of the data. + if (xfer_length >= buffer.size()) { // There will be nothing left to read after this response.PutChar('l'); done_with_buffer = true; } else { // There will still be bytes to read after this request. response.PutChar('m'); - buffer = buffer.take_front(auxv_length); + buffer = buffer.take_front(xfer_length); } - // Now write the data in encoded binary form. response.PutEscapedBytes(buffer.data(), buffer.size()); } if (done_with_buffer) - m_active_auxv_buffer_up.reset(); + m_xfer_buffer_map.erase(buffer_it); return SendPacketNoLock(response.GetString()); -#else - return SendUnimplementedResponse("not implemented on this platform"); -#endif } GDBRemoteCommunication::PacketResult @@ -3206,8 +3264,8 @@ void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); - LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get()); - m_active_auxv_buffer_up.reset(); + LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size()); + m_xfer_buffer_map.clear(); } FileSpec
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h index a085a3c..068ea52 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServerLLGS.h ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,43 +31,35 @@ : public GDBRemoteCommunicationServerCommon, public NativeProcessProtocol::NativeDelegate { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ GDBRemoteCommunicationServerLLGS( MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory); void SetLaunchInfo(const ProcessLaunchInfo &info); - //------------------------------------------------------------------ /// Launch a process with the current launch settings. /// /// This method supports running an lldb-gdbserver or similar /// server in a situation where the startup code has been provided /// with all the information for a child process to be launched. /// - /// @return + /// \return /// An Status object indicating the success or failure of the /// launch. - //------------------------------------------------------------------ Status LaunchProcess() override; - //------------------------------------------------------------------ /// Attach to a process. /// /// This method supports attaching llgs to a process accessible via the /// configured Platform. /// - /// @return + /// \return /// An Status object indicating the success or failure of the /// attach operation. - //------------------------------------------------------------------ Status AttachToProcess(lldb::pid_t pid); - //------------------------------------------------------------------ // NativeProcessProtocol::NativeDelegate overrides - //------------------------------------------------------------------ void InitializeDelegate(NativeProcessProtocol *process) override; void ProcessStateChanged(NativeProcessProtocol *process, @@ -91,7 +82,7 @@ MainLoop::ReadHandleUP m_stdio_handle_up; lldb::StateType m_inferior_prev_state = lldb::StateType::eStateInvalid; - std::unique_ptr<llvm::MemoryBuffer> m_active_auxv_buffer_up; + llvm::StringMap<std::unique_ptr<llvm::MemoryBuffer>> m_xfer_buffer_map; std::mutex m_saved_registers_mutex; std::unordered_map<uint32_t, lldb::DataBufferSP> m_saved_registers_map; uint32_t m_next_saved_registers_id = 1; @@ -159,7 +150,7 @@ PacketResult Handle_s(StringExtractorGDBRemote &packet); - PacketResult Handle_qXfer_auxv_read(StringExtractorGDBRemote &packet); + PacketResult Handle_qXfer(StringExtractorGDBRemote &packet); PacketResult Handle_QSaveRegisterState(StringExtractorGDBRemote &packet); @@ -187,6 +178,8 @@ PacketResult Handle_QPassSignals(StringExtractorGDBRemote &packet); + PacketResult Handle_g(StringExtractorGDBRemote &packet); + void SetCurrentThreadID(lldb::tid_t tid); lldb::tid_t GetCurrentThreadID() const; @@ -200,6 +193,9 @@ FileSpec FindModuleFile(const std::string &module_path, const ArchSpec &arch) override; + llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> + ReadXferObject(llvm::StringRef object, llvm::StringRef annex); + private: void HandleInferiorState_Exited(NativeProcessProtocol *process); @@ -223,9 +219,7 @@ void StopSTDIOForwarding(); - //------------------------------------------------------------------ // For GDBRemoteCommunicationServerLLGS only - //------------------------------------------------------------------ DISALLOW_COPY_AND_ASSIGN(GDBRemoteCommunicationServerLLGS); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp index 3521dda..6deb75f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServerPlatform.cpp ----------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,11 +21,10 @@ #include "lldb/Host/Config.h" #include "lldb/Host/ConnectionFileDescriptor.h" +#include "lldb/Host/FileAction.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" -#include "lldb/Target/FileAction.h" #include "lldb/Target/Platform.h" -#include "lldb/Target/Process.h" #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/JSON.h" #include "lldb/Utility/Log.h" @@ -41,9 +39,7 @@ using namespace lldb_private; using namespace lldb_private::process_gdb_remote; -//---------------------------------------------------------------------- // GDBRemoteCommunicationServerPlatform constructor -//---------------------------------------------------------------------- GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform( const Socket::SocketProtocol socket_protocol, const char *socket_scheme) : GDBRemoteCommunicationServerCommon("gdb-remote.server", @@ -87,9 +83,7 @@ }); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform() {} Status GDBRemoteCommunicationServerPlatform::LaunchGDBServer( @@ -121,25 +115,24 @@ this, std::placeholders::_1), false); - llvm::StringRef platform_scheme; - llvm::StringRef platform_ip; - int platform_port; - llvm::StringRef platform_path; - std::string platform_uri = GetConnection()->GetURI(); - bool ok = UriParser::Parse(platform_uri, platform_scheme, platform_ip, - platform_port, platform_path); - UNUSED_IF_ASSERT_DISABLED(ok); - assert(ok); - std::ostringstream url; // debugserver does not accept the URL scheme prefix. #if !defined(__APPLE__) url << m_socket_scheme << "://"; #endif uint16_t *port_ptr = &port; - if (m_socket_protocol == Socket::ProtocolTcp) + if (m_socket_protocol == Socket::ProtocolTcp) { + llvm::StringRef platform_scheme; + llvm::StringRef platform_ip; + int platform_port; + llvm::StringRef platform_path; + std::string platform_uri = GetConnection()->GetURI(); + bool ok = UriParser::Parse(platform_uri, platform_scheme, platform_ip, + platform_port, platform_path); + UNUSED_IF_ASSERT_DISABLED(ok); + assert(ok); url << platform_ip.str() << ":" << port; - else { + } else { socket_name = GetDomainSocketPath("gdbserver").GetPath(); url << socket_name; port_ptr = nullptr; @@ -207,7 +200,7 @@ port + m_port_offset); if (!socket_name.empty()) { response.PutCString("socket_name:"); - response.PutCStringAsRawHex8(socket_name.c_str()); + response.PutStringAsRawHex8(socket_name); response.PutChar(';'); } @@ -399,7 +392,7 @@ StringExtractorGDBRemote &packet) { StructuredData::Array signal_array; - const auto &signals = Host::GetUnixSignals(); + lldb::UnixSignalsSP signals = UnixSignals::CreateForHost(); for (auto signo = signals->GetFirstSignalNumber(); signo != LLDB_INVALID_SIGNAL_NUMBER; signo = signals->GetNextSignalNumber(signo)) {
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h index df51e03..eacc99a 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteCommunicationServerPlatform.h ------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,7 +35,6 @@ // a port chosen by the OS. void SetPortMap(PortMap &&port_map); - //---------------------------------------------------------------------- // If we are using a port map where we can only use certain ports, // get the next available port. // @@ -44,7 +42,6 @@ // // If we aren't using a port map, return 0 to indicate we should bind to // port 0 and then figure out which port we used. - //---------------------------------------------------------------------- uint16_t GetNextAvailablePort(); bool AssociatePortWithProcess(uint16_t port, lldb::pid_t pid);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp index e58f47f..a77e659 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp
@@ -1,9 +1,8 @@ //===-- GDBRemoteRegisterContext.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,13 +22,13 @@ #include "Utility/ARM_ehframe_Registers.h" #include "lldb/Utility/StringExtractorGDBRemote.h" +#include <memory> + using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_gdb_remote; -//---------------------------------------------------------------------- // GDBRemoteRegisterContext constructor -//---------------------------------------------------------------------- GDBRemoteRegisterContext::GDBRemoteRegisterContext( ThreadGDBRemote &thread, uint32_t concrete_frame_idx, GDBRemoteDynamicRegisterInfo ®_info, bool read_all_at_once) @@ -47,9 +46,7 @@ m_reg_data.SetByteOrder(thread.GetProcess()->GetByteOrder()); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- GDBRemoteRegisterContext::~GDBRemoteRegisterContext() {} void GDBRemoteRegisterContext::InvalidateAllRegisters() { @@ -101,7 +98,7 @@ bool GDBRemoteRegisterContext::PrivateSetRegisterValue( uint32_t reg, llvm::ArrayRef<uint8_t> data) { const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg); - if (reg_info == NULL) + if (reg_info == nullptr) return false; // Invalidate if needed @@ -125,7 +122,7 @@ bool GDBRemoteRegisterContext::PrivateSetRegisterValue(uint32_t reg, uint64_t new_reg_val) { const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg); - if (reg_info == NULL) + if (reg_info == nullptr) return false; // Early in process startup, we can get a thread that has an invalid byte @@ -151,7 +148,7 @@ uint8_t *dst = const_cast<uint8_t *>( m_reg_data.PeekData(reg_info->byte_offset, reg_info->byte_size)); - if (dst == NULL) + if (dst == nullptr) return false; if (data.CopyByteOrderedData(0, // src offset @@ -186,7 +183,7 @@ Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); - if (process == NULL || thread == NULL) + if (process == nullptr || thread == nullptr) return false; GDBRemoteCommunicationClient &gdb_comm( @@ -206,6 +203,14 @@ if (buffer_sp->GetByteSize() >= m_reg_data.GetByteSize()) { SetAllRegisterValid(true); return true; + } else { + Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_THREAD | + GDBR_LOG_PACKETS)); + if (log) + log->Printf ("error: GDBRemoteRegisterContext::ReadRegisterBytes tried to read the " + "entire register context at once, expected at least %" PRId64 " bytes " + "but only got %" PRId64 " bytes.", m_reg_data.GetByteSize(), + buffer_sp->GetByteSize()); } } return false; @@ -223,7 +228,7 @@ // We have a valid primordial register as our constituent. Grab the // corresponding register info. const RegisterInfo *prim_reg_info = GetRegisterInfoAtIndex(prim_reg); - if (prim_reg_info == NULL) + if (prim_reg_info == nullptr) success = false; else { // Read the containing register if it hasn't already been read @@ -248,10 +253,8 @@ } if (&data != &m_reg_data) { -#if defined(LLDB_CONFIGURATION_DEBUG) assert(m_reg_data.GetByteSize() >= reg_info->byte_offset + reg_info->byte_size); -#endif // If our register context and our register info disagree, which should // never happen, don't read past the end of the buffer. if (m_reg_data.GetByteSize() < reg_info->byte_offset + reg_info->byte_size) @@ -298,16 +301,14 @@ Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); - if (process == NULL || thread == NULL) + if (process == nullptr || thread == nullptr) return false; GDBRemoteCommunicationClient &gdb_comm( ((ProcessGDBRemote *)process)->GetGDBRemote()); -#if defined(LLDB_CONFIGURATION_DEBUG) assert(m_reg_data.GetByteSize() >= reg_info->byte_offset + reg_info->byte_size); -#endif // If our register context and our register info disagree, which should never // happen, don't overwrite past the end of the buffer. @@ -318,7 +319,7 @@ uint8_t *dst = const_cast<uint8_t *>( m_reg_data.PeekData(reg_info->byte_offset, reg_info->byte_size)); - if (dst == NULL) + if (dst == nullptr) return false; if (data.CopyByteOrderedData(data_offset, // src offset @@ -360,7 +361,7 @@ // We have a valid primordial register as our constituent. Grab the // corresponding register info. const RegisterInfo *value_reg_info = GetRegisterInfoAtIndex(reg); - if (value_reg_info == NULL) + if (value_reg_info == nullptr) success = false; else success = SetPrimordialRegister(value_reg_info, gdb_comm); @@ -408,7 +409,7 @@ Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); - if (process == NULL || thread == NULL) + if (process == nullptr || thread == nullptr) return false; GDBRemoteCommunicationClient &gdb_comm( @@ -433,7 +434,7 @@ Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); - if (process == NULL || thread == NULL) + if (process == nullptr || thread == nullptr) return false; GDBRemoteCommunicationClient &gdb_comm( @@ -451,7 +452,7 @@ Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); - if (process == NULL || thread == NULL) + if (process == nullptr || thread == nullptr) return false; GDBRemoteCommunicationClient &gdb_comm( @@ -473,7 +474,8 @@ // individually and store them as binary data in a buffer. const RegisterInfo *reg_info; - for (uint32_t i = 0; (reg_info = GetRegisterInfoAtIndex(i)) != NULL; i++) { + for (uint32_t i = 0; (reg_info = GetRegisterInfoAtIndex(i)) != nullptr; + i++) { if (reg_info ->value_regs) // skip registers that are slices of real registers continue; @@ -481,8 +483,8 @@ // ReadRegisterBytes saves the contents of the register in to the // m_reg_data buffer } - data_sp.reset(new DataBufferHeap(m_reg_data.GetDataStart(), - m_reg_info.GetRegisterDataByteSize())); + data_sp = std::make_shared<DataBufferHeap>( + m_reg_data.GetDataStart(), m_reg_info.GetRegisterDataByteSize()); return true; } else { @@ -507,14 +509,14 @@ bool GDBRemoteRegisterContext::WriteAllRegisterValues( const lldb::DataBufferSP &data_sp) { - if (!data_sp || data_sp->GetBytes() == NULL || data_sp->GetByteSize() == 0) + if (!data_sp || data_sp->GetBytes() == nullptr || data_sp->GetByteSize() == 0) return false; ExecutionContext exe_ctx(CalculateThread()); Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); - if (process == NULL || thread == NULL) + if (process == nullptr || thread == nullptr) return false; GDBRemoteCommunicationClient &gdb_comm( @@ -556,9 +558,9 @@ uint64_t size_by_highest_offset = 0; for (uint32_t reg_idx = 0; - (reg_info = GetRegisterInfoAtIndex(reg_idx)) != NULL; ++reg_idx) { + (reg_info = GetRegisterInfoAtIndex(reg_idx)) != nullptr; ++reg_idx) { size_including_slice_registers += reg_info->byte_size; - if (reg_info->value_regs == NULL) + if (reg_info->value_regs == nullptr) size_not_including_slice_registers += reg_info->byte_size; if (reg_info->byte_offset >= size_by_highest_offset) size_by_highest_offset = reg_info->byte_offset + reg_info->byte_size; @@ -590,7 +592,7 @@ // keep track of the size of each reg & compute offset based on that. uint32_t running_byte_offset = 0; for (uint32_t reg_idx = 0; - (reg_info = GetRegisterInfoAtIndex(reg_idx)) != NULL; + (reg_info = GetRegisterInfoAtIndex(reg_idx)) != nullptr; ++reg_idx, running_byte_offset += reg_info->byte_size) { // Skip composite aka slice registers (e.g. eax is a slice of rax). if (reg_info->value_regs) @@ -636,7 +638,7 @@ } uint32_t num_restored = 0; const RegisterInfo *reg_info; - for (uint32_t i = 0; (reg_info = GetRegisterInfoAtIndex(i)) != NULL; + for (uint32_t i = 0; (reg_info = GetRegisterInfoAtIndex(i)) != nullptr; i++) { if (reg_info->value_regs) // skip registers that are slices of real // registers
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h index 6e8f330..25e9b71 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h
@@ -1,9 +1,8 @@ //===-- GDBRemoteRegisterContext.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp index 797f63d..a6fdd8d 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
@@ -1,9 +1,8 @@ //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,6 +23,7 @@ #include <algorithm> #include <csignal> #include <map> +#include <memory> #include <mutex> #include <sstream> @@ -41,7 +41,6 @@ #include "lldb/Host/PosixApi.h" #include "lldb/Host/PseudoTerminal.h" #include "lldb/Host/StringConvert.h" -#include "lldb/Host/Symbols.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Host/XML.h" #include "lldb/Interpreter/CommandInterpreter.h" @@ -54,6 +53,7 @@ #include "lldb/Interpreter/OptionValueProperties.h" #include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/Property.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/ABI.h" #include "lldb/Target/DynamicLoader.h" @@ -111,12 +111,40 @@ namespace { static constexpr PropertyDefinition g_properties[] = { - {"packet-timeout", OptionValue::eTypeUInt64, true, 1, NULL, {}, + {"packet-timeout", + OptionValue::eTypeUInt64, + true, + 5 +#if defined(__has_feature) +#if __has_feature(address_sanitizer) + * 2 +#endif +#endif + , + nullptr, + {}, "Specify the default packet timeout in seconds."}, - {"target-definition-file", OptionValue::eTypeFileSpec, true, 0, NULL, {}, - "The file that provides the description for remote target registers."}}; + {"target-definition-file", + OptionValue::eTypeFileSpec, + true, + 0, + nullptr, + {}, + "The file that provides the description for remote target registers."}, + {"use-libraries-svr4", + OptionValue::eTypeBoolean, + true, + false, + nullptr, + {}, + "If true, the libraries-svr4 feature will be used to get a hold of the " + "process's loaded modules."}}; -enum { ePropertyPacketTimeout, ePropertyTargetDefinitionFile }; +enum { + ePropertyPacketTimeout, + ePropertyTargetDefinitionFile, + ePropertyUseSVR4 +}; class PluginProperties : public Properties { public: @@ -125,26 +153,32 @@ } PluginProperties() : Properties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); } - virtual ~PluginProperties() {} + ~PluginProperties() override {} uint64_t GetPacketTimeout() { const uint32_t idx = ePropertyPacketTimeout; return m_collection_sp->GetPropertyAtIndexAsUInt64( - NULL, idx, g_properties[idx].default_uint_value); + nullptr, idx, g_properties[idx].default_uint_value); } bool SetPacketTimeout(uint64_t timeout) { const uint32_t idx = ePropertyPacketTimeout; - return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout); + return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout); } FileSpec GetTargetDefinitionFile() const { const uint32_t idx = ePropertyTargetDefinitionFile; - return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx); + return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); + } + + bool GetUseSVR4() const { + const uint32_t idx = ePropertyUseSVR4; + return m_collection_sp->GetPropertyAtIndexAsBoolean( + nullptr, idx, g_properties[idx].default_uint_value != 0); } }; @@ -153,25 +187,27 @@ static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() { static ProcessKDPPropertiesSP g_settings_sp; if (!g_settings_sp) - g_settings_sp.reset(new PluginProperties()); + g_settings_sp = std::make_shared<PluginProperties>(); return g_settings_sp; } class ProcessGDBRemoteProvider : public repro::Provider<ProcessGDBRemoteProvider> { public: + struct Info { + static const char *name; + static const char *file; + }; + ProcessGDBRemoteProvider(const FileSpec &directory) : Provider(directory) { - m_info.name = "gdb-remote"; - m_info.files.push_back("gdb-remote.yaml"); } raw_ostream *GetHistoryStream() { - FileSpec history_file = - GetRoot().CopyByAppendingPathComponent("gdb-remote.yaml"); + FileSpec history_file = GetRoot().CopyByAppendingPathComponent(Info::file); std::error_code EC; m_stream_up = llvm::make_unique<raw_fd_ostream>(history_file.GetPath(), EC, - sys::fs::OpenFlags::F_None); + sys::fs::OpenFlags::F_Text); return m_stream_up.get(); } @@ -191,6 +227,8 @@ }; char ProcessGDBRemoteProvider::ID = 0; +const char *ProcessGDBRemoteProvider::Info::name = "gdb-remote"; +const char *ProcessGDBRemoteProvider::Info::file = "gdb-remote.yaml"; } // namespace @@ -239,8 +277,8 @@ ListenerSP listener_sp, const FileSpec *crash_file_path) { lldb::ProcessSP process_sp; - if (crash_file_path == NULL) - process_sp.reset(new ProcessGDBRemote(target_sp, listener_sp)); + if (crash_file_path == nullptr) + process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp); return process_sp; } @@ -275,15 +313,13 @@ return true; } -//---------------------------------------------------------------------- // ProcessGDBRemote constructor -//---------------------------------------------------------------------- ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, ListenerSP listener_sp) : Process(target_sp, listener_sp), m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(), m_register_info(), - m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"), + m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"), m_async_listener_sp( Listener::MakeListener("lldb.process.gdb-remote.async-listener")), m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(), @@ -340,9 +376,7 @@ m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds)); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ProcessGDBRemote::~ProcessGDBRemote() { // m_mach_process.UnregisterNotificationCallbacks (this); Clear(); @@ -360,9 +394,7 @@ KillDebugserverProcess(); } -//---------------------------------------------------------------------- // PluginInterface -//---------------------------------------------------------------------- ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); } uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; } @@ -370,7 +402,7 @@ bool ProcessGDBRemote::ParsePythonTargetDefinition( const FileSpec &target_definition_fspec) { ScriptInterpreter *interpreter = - GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); + GetTarget().GetDebugger().GetScriptInterpreter(); Status error; StructuredData::ObjectSP module_object_sp( interpreter->LoadPluginModule(target_definition_fspec, error)); @@ -540,8 +572,8 @@ std::vector<uint32_t> invalidate_regs; std::vector<uint8_t> dwarf_opcode_bytes; RegisterInfo reg_info = { - NULL, // Name - NULL, // Alt name + nullptr, // Name + nullptr, // Alt name 0, // byte size reg_offset, // offset eEncodingUint, // encoding @@ -553,10 +585,10 @@ reg_num, // process plugin reg num reg_num // native register number }, - NULL, - NULL, - NULL, // Dwarf expression opcode bytes pointer - 0 // Dwarf expression opcode bytes length + nullptr, + nullptr, + nullptr, // Dwarf expression opcode bytes pointer + 0 // Dwarf expression opcode bytes length }; while (response.GetNameColonValue(name, value)) { @@ -576,7 +608,7 @@ reg_info.encoding = encoding; } else if (name.equals("format")) { Format format = eFormatInvalid; - if (OptionArgParser::ToFormat(value.str().c_str(), format, NULL) + if (OptionArgParser::ToFormat(value.str().c_str(), format, nullptr) .Success()) reg_info.format = format; else { @@ -796,9 +828,7 @@ return error; } -//---------------------------------------------------------------------- // Process Control -//---------------------------------------------------------------------- Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module, ProcessLaunchInfo &launch_info) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); @@ -883,8 +913,8 @@ // since 'O' packets can really slow down debugging if the inferior // does a lot of output. if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) && - pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, NULL, 0)) { - FileSpec slave_name{pty.GetSlaveName(NULL, 0)}; + pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, nullptr, 0)) { + FileSpec slave_name{pty.GetSlaveName(nullptr, 0)}; if (!stdin_file_spec) stdin_file_spec = slave_name; @@ -928,7 +958,7 @@ GetTarget().GetArchitecture().GetArchitectureName()); const char *launch_event_data = launch_info.GetLaunchEventData(); - if (launch_event_data != NULL && *launch_event_data != '\0') + if (launch_event_data != nullptr && *launch_event_data != '\0') m_gdb_comm.SendLaunchEventDataPacket(launch_event_data); if (working_dir) { @@ -1013,14 +1043,14 @@ if (log) log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url.str().c_str()); - std::unique_ptr<ConnectionFileDescriptor> conn_ap( + std::unique_ptr<ConnectionFileDescriptor> conn_up( new ConnectionFileDescriptor()); - if (conn_ap.get()) { + if (conn_up) { const uint32_t max_retry_count = 50; uint32_t retry_count = 0; while (!m_gdb_comm.IsConnected()) { - if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) { - m_gdb_comm.SetConnection(conn_ap.release()); + if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) { + m_gdb_comm.SetConnection(conn_up.release()); break; } else if (error.WasInterrupted()) { // If we were interrupted, don't keep retrying. @@ -1702,7 +1732,7 @@ ThreadSP thread_sp( old_thread_list_copy.RemoveThreadByProtocolID(tid, false)); if (!thread_sp) { - thread_sp.reset(new ThreadGDBRemote(*this, tid)); + thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid); LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.", thread_sp.get(), thread_sp->GetID()); } else { @@ -1818,7 +1848,7 @@ if (!thread_sp) { // Create the thread if we need to - thread_sp.reset(new ThreadGDBRemote(*this, tid)); + thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid); m_thread_list_real.AddThread(thread_sp); } } @@ -1842,7 +1872,7 @@ gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData()); } - thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str()); + thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str()); gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr); // Check if the GDB server was able to provide the queue name, kind and @@ -2421,6 +2451,15 @@ // Scope for the lock { + // Check to see if SetThreadStopInfo() filled in m_thread_ids? + if (m_thread_ids.empty()) { + // No, we need to fetch the thread list manually + UpdateThreadIDList(); + } + // We might set some stop info's so make sure the thread list is up to + // date before we do that or we might overwrite what was computed here. + UpdateThreadListIfNeeded(); + // Lock the thread stack while we access it std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex); // Get the number of stop packets on the stack @@ -2435,13 +2474,7 @@ // Clear the thread stop stack m_stop_packet_stack.clear(); } - - // Check to see if SetThreadStopInfo() filled in m_thread_ids? - if (m_thread_ids.empty()) { - // No, we need to fetch the thread list manually - UpdateThreadIDList(); - } - + // If we have queried for a default thread id if (m_initial_tid != LLDB_INVALID_THREAD_ID) { m_thread_list.SetSelectedThreadByID(m_initial_tid); @@ -2711,9 +2744,7 @@ Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp)); } -//------------------------------------------------------------------ // Process Queries -//------------------------------------------------------------------ bool ProcessGDBRemote::IsAlive() { return m_gdb_comm.IsConnected() && Process::IsAlive(); @@ -2757,9 +2788,7 @@ } } -//------------------------------------------------------------------ // Process Memory -//------------------------------------------------------------------ size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, Status &error) { GetMaxMemorySize(); @@ -3120,14 +3149,12 @@ return error; } -//------------------------------------------------------------------ // Process STDIO -//------------------------------------------------------------------ size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, Status &error) { if (m_stdio_communication.IsConnected()) { ConnectionStatus status; - m_stdio_communication.Write(src, src_len, status, NULL); + m_stdio_communication.Write(src, src_len, status, nullptr); } else if (m_stdin_forward) { m_gdb_comm.SendStdinNotification(src, src_len); } @@ -3136,7 +3163,7 @@ Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { Status error; - assert(bp_site != NULL); + assert(bp_site != nullptr); // Get logging info Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); @@ -3262,7 +3289,7 @@ Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { Status error; - assert(bp_site != NULL); + assert(bp_site != nullptr); addr_t addr = bp_site->GetLoadAddress(); user_id_t site_id = bp_site->GetID(); Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); @@ -3432,16 +3459,10 @@ if (!loader) return Status("No loader provided."); - auto provider_info = loader->GetProviderInfo("gdb-remote"); - if (!provider_info) - return Status("No provider for gdb-remote."); - - if (provider_info->files.empty()) - return Status("Provider for gdb-remote contains no files."); - // Construct replay history path. - FileSpec history_file = loader->GetRoot().CopyByAppendingPathComponent( - provider_info->files.front()); + FileSpec history_file = loader->GetFile<ProcessGDBRemoteProvider::Info>(); + if (!history_file) + return Status("No provider for gdb-remote."); // Enable replay mode. m_replay_mode = true; @@ -3679,9 +3700,15 @@ // Create a thread that watches our internal state and controls which // events make it to clients (into the DCProcess event queue). - m_async_thread = - ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", - ProcessGDBRemote::AsyncThread, this, NULL); + llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( + "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this); + if (!async_thread) { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(async_thread.takeError())); + return false; + } + m_async_thread = *async_thread; } else if (log) log->Printf("ProcessGDBRemote::%s () - Called when Async thread was " "already running.", @@ -3775,7 +3802,7 @@ ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); - if (::strstr(continue_cstr, "vAttach") == NULL) + if (::strstr(continue_cstr, "vAttach") == nullptr) process->SetPrivateState(eStateRunning); StringExtractorGDBRemote response; @@ -3841,11 +3868,11 @@ // the "E87" error code from debugserver -- this indicates that // the process is not debuggable. Return a slightly more // helpful error message about why the attach failed. - if (::strstr(continue_cstr, "vAttach") != NULL && + if (::strstr(continue_cstr, "vAttach") != nullptr && response.GetError() == 0x87) { process->SetExitStatus(-1, "cannot attach to process due to " "System Integrity Protection"); - } else if (::strstr(continue_cstr, "vAttach") != NULL && + } else if (::strstr(continue_cstr, "vAttach") != nullptr && response.GetStatus().Fail()) { process->SetExitStatus(-1, response.GetStatus().AsCString()); } else { @@ -3920,7 +3947,7 @@ ") thread exiting...", __FUNCTION__, arg, process->GetID()); - return NULL; + return {}; } // uint32_t @@ -4016,7 +4043,7 @@ } } } - return m_thread_create_bp_sp.get() != NULL; + return m_thread_create_bp_sp.get() != nullptr; } bool ProcessGDBRemote::StopNoticingNewThreads() { @@ -4031,9 +4058,9 @@ } DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { - if (m_dyld_ap.get() == NULL) - m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL)); - return m_dyld_ap.get(); + if (m_dyld_up.get() == nullptr) + m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); + return m_dyld_up.get(); } Status ProcessGDBRemote::SendEventData(const char *data) { @@ -4053,17 +4080,17 @@ return error; } -const DataBufferSP ProcessGDBRemote::GetAuxvData() { +DataExtractor ProcessGDBRemote::GetAuxvData() { DataBufferSP buf; if (m_gdb_comm.GetQXferAuxvReadSupported()) { std::string response_string; if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success) - buf.reset(new DataBufferHeap(response_string.c_str(), - response_string.length())); + buf = std::make_shared<DataBufferHeap>(response_string.c_str(), + response_string.length()); } - return buf; + return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); } StructuredData::ObjectSP @@ -4212,7 +4239,7 @@ } Status ProcessGDBRemote::ConfigureStructuredData( - const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { + ConstString type_name, const StructuredData::ObjectSP &config_sp) { return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); } @@ -4373,8 +4400,8 @@ bool encoding_set = false; bool format_set = false; RegisterInfo reg_info = { - NULL, // Name - NULL, // Alt name + nullptr, // Name + nullptr, // Alt name 0, // byte size reg_offset, // offset eEncodingUint, // encoding @@ -4386,10 +4413,10 @@ cur_reg_num, // process plugin reg num cur_reg_num // native register number }, - NULL, - NULL, - NULL, // Dwarf Expression opcode bytes pointer - 0 // Dwarf Expression opcode bytes length + nullptr, + nullptr, + nullptr, // Dwarf Expression opcode bytes pointer + 0 // Dwarf Expression opcode bytes length }; reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, @@ -4423,7 +4450,8 @@ } else if (name == "format") { format_set = true; Format format = eFormatInvalid; - if (OptionArgParser::ToFormat(value.data(), format, NULL).Success()) + if (OptionArgParser::ToFormat(value.data(), format, nullptr) + .Success()) reg_info.format = format; else if (value == "vector-sint8") reg_info.format = eFormatVectorOfSInt8; @@ -4499,8 +4527,15 @@ // Only update the register set name if we didn't get a "reg_set" // attribute. "set_name" will be empty if we didn't have a "reg_set" // attribute. - if (!set_name && !gdb_group.empty()) - set_name.SetCString(gdb_group.c_str()); + if (!set_name) { + if (!gdb_group.empty()) { + set_name.SetCString(gdb_group.c_str()); + } else { + // If no register group name provided anywhere, + // we'll create a 'general' register set + set_name.SetCString("general"); + } + } reg_info.byte_offset = reg_offset; assert(reg_info.byte_size != 0); @@ -4525,38 +4560,33 @@ } // namespace -// query the target of gdb-remote for extended target information return: -// 'true' on success -// 'false' on failure -bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { - // Make sure LLDB has an XML parser it can use first - if (!XMLDocument::XMLEnabled()) - return false; - - // redirect libxml2's error handler since the default prints to stdout - - GDBRemoteCommunicationClient &comm = m_gdb_comm; - - // check that we have extended feature read support - if (!comm.GetQXferFeaturesReadSupported()) - return false; - +// This method fetches a register description feature xml file from +// the remote stub and adds registers/register groupsets/architecture +// information to the current process. It will call itself recursively +// for nested register definition files. It returns true if it was able +// to fetch and parse an xml file. +bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use, + std::string xml_filename, + uint32_t &cur_reg_num, + uint32_t ®_offset) { // request the target xml file std::string raw; lldb_private::Status lldberr; - if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"), + if (!m_gdb_comm.ReadExtFeature(ConstString("features"), + ConstString(xml_filename.c_str()), raw, lldberr)) { return false; } XMLDocument xml_document; - if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) { + if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) { GdbServerTargetInfo target_info; + std::vector<XMLNode> feature_nodes; + // The top level feature XML file will start with a <target> tag. XMLNode target_node = xml_document.GetRootElement("target"); if (target_node) { - std::vector<XMLNode> feature_nodes; target_node.ForEachChildElement([&target_info, &feature_nodes]( const XMLNode &node) -> bool { llvm::StringRef name = node.GetName(); @@ -4594,32 +4624,48 @@ } return true; // Keep iterating through all children of the target_node }); + } else { + // In an included XML feature file, we're already "inside" the <target> + // tag of the initial XML file; this included file will likely only have + // a <feature> tag. Need to check for any more included files in this + // <feature> element. + XMLNode feature_node = xml_document.GetRootElement("feature"); + if (feature_node) { + feature_nodes.push_back(feature_node); + feature_node.ForEachChildElement([&target_info]( + const XMLNode &node) -> bool { + llvm::StringRef name = node.GetName(); + if (name == "xi:include" || name == "include") { + llvm::StringRef href = node.GetAttributeValue("href"); + if (!href.empty()) + target_info.includes.push_back(href.str()); + } + return true; + }); + } + } - // If the target.xml includes an architecture entry like - // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) - // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board) - // use that if we don't have anything better. - if (!arch_to_use.IsValid() && !target_info.arch.empty()) { - if (target_info.arch == "i386:x86-64") { - // We don't have any information about vendor or OS. - arch_to_use.SetTriple("x86_64--"); - GetTarget().MergeArchitecture(arch_to_use); - } - - // SEGGER J-Link jtag boards send this very-generic arch name, - // we'll need to use this if we have absolutely nothing better - // to work with or the register definitions won't be accepted. - if (target_info.arch == "arm") { - arch_to_use.SetTriple("arm--"); - GetTarget().MergeArchitecture(arch_to_use); - } + // If the target.xml includes an architecture entry like + // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) + // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board) + // use that if we don't have anything better. + if (!arch_to_use.IsValid() && !target_info.arch.empty()) { + if (target_info.arch == "i386:x86-64") { + // We don't have any information about vendor or OS. + arch_to_use.SetTriple("x86_64--"); + GetTarget().MergeArchitecture(arch_to_use); } - // Initialize these outside of ParseRegisters, since they should not be - // reset inside each include feature - uint32_t cur_reg_num = 0; - uint32_t reg_offset = 0; + // SEGGER J-Link jtag boards send this very-generic arch name, + // we'll need to use this if we have absolutely nothing better + // to work with or the register definitions won't be accepted. + if (target_info.arch == "arm") { + arch_to_use.SetTriple("arm--"); + GetTarget().MergeArchitecture(arch_to_use); + } + } + if (arch_to_use.IsValid()) { // Don't use Process::GetABI, this code gets called from DidAttach, and // in that context we haven't set the Target's architecture yet, so the // ABI is also potentially incorrect. @@ -4630,26 +4676,31 @@ } for (const auto &include : target_info.includes) { - // request register file - std::string xml_data; - if (!comm.ReadExtFeature(ConstString("features"), ConstString(include), - xml_data, lldberr)) - continue; - - XMLDocument include_xml_document; - include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), - include.c_str()); - XMLNode include_feature_node = - include_xml_document.GetRootElement("feature"); - if (include_feature_node) { - ParseRegisters(include_feature_node, target_info, - this->m_register_info, abi_to_use_sp, cur_reg_num, - reg_offset); - } + GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, + cur_reg_num, reg_offset); } - this->m_register_info.Finalize(arch_to_use); } + } else { + return false; } + return true; +} + +// query the target of gdb-remote for extended target information returns +// true on success (got register definitions), false on failure (did not). +bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { + // Make sure LLDB has an XML parser it can use first + if (!XMLDocument::XMLEnabled()) + return false; + + // check that we have extended feature read support + if (!m_gdb_comm.GetQXferFeaturesReadSupported()) + return false; + + uint32_t cur_reg_num = 0; + uint32_t reg_offset = 0; + if (GetGDBServerRegisterInfoXMLAndProcess (arch_to_use, "target.xml", cur_reg_num, reg_offset)) + this->m_register_info.Finalize(arch_to_use); return m_register_info.GetNumRegisters() > 0; } @@ -4664,9 +4715,10 @@ log->Printf("ProcessGDBRemote::%s", __FUNCTION__); GDBRemoteCommunicationClient &comm = m_gdb_comm; + bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4(); // check that we have extended feature read support - if (comm.GetQXferLibrariesSVR4ReadSupported()) { + if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { list.clear(); // request the loaded library list @@ -4929,7 +4981,7 @@ StreamString packet; packet.PutCString("qFileLoadAddress:"); - packet.PutCStringAsRawHex8(file_path.c_str()); + packet.PutStringAsRawHex8(file_path); StringExtractorGDBRemote response; if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, @@ -5140,7 +5192,7 @@ "Tests packet speeds of various sizes to determine " "the performance characteristics of the GDB remote " "connection. ", - NULL), + nullptr), m_option_group(), m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, "The number of packets to send of each varying size " @@ -5165,7 +5217,7 @@ m_option_group.Finalize(); } - ~CommandObjectProcessGDBRemoteSpeedTest() {} + ~CommandObjectProcessGDBRemoteSpeedTest() override {} Options *GetOptions() override { return &m_option_group; } @@ -5214,9 +5266,9 @@ public: CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process plugin packet history", - "Dumps the packet history buffer. ", NULL) {} + "Dumps the packet history buffer. ", nullptr) {} - ~CommandObjectProcessGDBRemotePacketHistory() {} + ~CommandObjectProcessGDBRemotePacketHistory() override {} bool DoExecute(Args &command, CommandReturnObject &result) override { const size_t argc = command.GetArgumentCount(); @@ -5245,9 +5297,9 @@ : CommandObjectParsed( interpreter, "process plugin packet xfer-size", "Maximum size that lldb will try to read/write one one chunk.", - NULL) {} + nullptr) {} - ~CommandObjectProcessGDBRemotePacketXferSize() {} + ~CommandObjectProcessGDBRemotePacketXferSize() override {} bool DoExecute(Args &command, CommandReturnObject &result) override { const size_t argc = command.GetArgumentCount(); @@ -5265,7 +5317,7 @@ if (process) { const char *packet_size = command.GetArgumentAtIndex(0); errno = 0; - uint64_t user_specified_max = strtoul(packet_size, NULL, 10); + uint64_t user_specified_max = strtoul(packet_size, nullptr, 10); if (errno == 0 && user_specified_max != 0) { process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); result.SetStatus(eReturnStatusSuccessFinishResult); @@ -5287,9 +5339,9 @@ "The packet header and footer will automatically " "be added to the packet prior to sending and " "stripped from the result.", - NULL) {} + nullptr) {} - ~CommandObjectProcessGDBRemotePacketSend() {} + ~CommandObjectProcessGDBRemotePacketSend() override {} bool DoExecute(Args &command, CommandReturnObject &result) override { const size_t argc = command.GetArgumentCount(); @@ -5315,7 +5367,7 @@ output_strm.Printf(" packet: %s\n", packet_cstr); std::string &response_str = response.GetStringRef(); - if (strstr(packet_cstr, "qGetProfileData") != NULL) { + if (strstr(packet_cstr, "qGetProfileData") != nullptr) { response_str = process->HarmonizeThreadIdsForProfileData(response); } @@ -5340,7 +5392,7 @@ "encoded into a valid 'qRcmd' packet, sent and the " "response will be printed.") {} - ~CommandObjectProcessGDBRemotePacketMonitor() {} + ~CommandObjectProcessGDBRemotePacketMonitor() override {} bool DoExecute(llvm::StringRef command, CommandReturnObject &result) override { @@ -5383,7 +5435,7 @@ CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "process plugin packet", "Commands that deal with GDB remote packets.", - NULL) { + nullptr) { LoadSubCommand( "history", CommandObjectSP( @@ -5404,7 +5456,7 @@ interpreter))); } - ~CommandObjectProcessGDBRemotePacket() {} + ~CommandObjectProcessGDBRemotePacket() override {} }; class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { @@ -5419,12 +5471,12 @@ CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); } - ~CommandObjectMultiwordProcessGDBRemote() {} + ~CommandObjectMultiwordProcessGDBRemote() override {} }; CommandObject *ProcessGDBRemote::GetPluginCommandObject() { if (!m_command_sp) - m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote( - GetTarget().GetDebugger().GetCommandInterpreter())); + m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( + GetTarget().GetDebugger().GetCommandInterpreter()); return m_command_sp.get(); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h index 14a5237..9c41fc2 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
@@ -1,9 +1,8 @@ //===-- ProcessGDBRemote.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -68,17 +67,13 @@ static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // Check if a given Process - //------------------------------------------------------------------ bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override; CommandObject *GetPluginCommandObject() override; - //------------------------------------------------------------------ // Creating a new process, or attaching to an existing one - //------------------------------------------------------------------ Status WillLaunch(Module *module) override; Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override; @@ -103,16 +98,12 @@ void DidAttach(ArchSpec &process_arch) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - //------------------------------------------------------------------ // Process Control - //------------------------------------------------------------------ Status WillResume() override; Status DoResume() override; @@ -131,18 +122,14 @@ void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp); - //------------------------------------------------------------------ // Process Queries - //------------------------------------------------------------------ bool IsAlive() override; lldb::addr_t GetImageInfoAddress() override; void WillPublicStop() override; - //------------------------------------------------------------------ // Process Memory - //------------------------------------------------------------------ size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, Status &error) override; @@ -160,21 +147,15 @@ Status DoDeallocateMemory(lldb::addr_t ptr) override; - //------------------------------------------------------------------ // Process STDIO - //------------------------------------------------------------------ size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override; - //---------------------------------------------------------------------- // Process Breakpoints - //---------------------------------------------------------------------- Status EnableBreakpointSite(BreakpointSite *bp_site) override; Status DisableBreakpointSite(BreakpointSite *bp_site) override; - //---------------------------------------------------------------------- // Process Watchpoints - //---------------------------------------------------------------------- Status EnableWatchpoint(Watchpoint *wp, bool notify = true) override; Status DisableWatchpoint(Watchpoint *wp, bool notify = true) override; @@ -206,9 +187,7 @@ Status SendEventData(const char *data) override; - //---------------------------------------------------------------------- // Override DidExit so we can disconnect from the remote GDB server - //---------------------------------------------------------------------- void DidExit() override; void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max); @@ -235,7 +214,7 @@ lldb::addr_t image_count) override; Status - ConfigureStructuredData(const ConstString &type_name, + ConfigureStructuredData(ConstString type_name, const StructuredData::ObjectSP &config_sp) override; StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override; @@ -256,9 +235,7 @@ friend class GDBRemoteCommunicationClient; friend class GDBRemoteRegisterContext; - //------------------------------------------------------------------ /// Broadcaster event bits definitions. - //------------------------------------------------------------------ enum { eBroadcastBitAsyncContinue = (1 << 0), eBroadcastBitAsyncThreadShouldExit = (1 << 1), @@ -313,9 +290,7 @@ using FlashRange = FlashRangeVector::Entry; FlashRangeVector m_erased_flash_ranges; - //---------------------------------------------------------------------- // Accessors - //---------------------------------------------------------------------- bool IsRunning(lldb::StateType state) { return state == lldb::eStateRunning || IsStepping(state); } @@ -349,7 +324,7 @@ bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec); - const lldb::DataBufferSP GetAuxvData() override; + DataExtractor GetAuxvData() override; StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid); @@ -408,6 +383,11 @@ DynamicLoader *GetDynamicLoader() override; + bool GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use, + std::string xml_filename, + uint32_t &cur_reg_num, + uint32_t ®_offset); + // Query remote GDBServer for register information bool GetGDBServerRegisterInfo(ArchSpec &arch); @@ -428,9 +408,7 @@ bool HasErased(FlashRange range); private: - //------------------------------------------------------------------ // For ProcessGDBRemote only - //------------------------------------------------------------------ std::string m_partial_profile_data; std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map; uint64_t m_last_signals_version = 0; @@ -440,9 +418,7 @@ lldb::user_id_t break_id, lldb::user_id_t break_loc_id); - //------------------------------------------------------------------ // ContinueDelegate interface - //------------------------------------------------------------------ void HandleAsyncStdout(llvm::StringRef out) override; void HandleAsyncMisc(llvm::StringRef data) override; void HandleStopReply() override;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp index 8f16b83..8cadc45 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp
@@ -1,9 +1,8 @@ //===-- ProcessGDBRemoteLog.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h index d4981df..d9b8d45 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h
@@ -1,9 +1,8 @@ //===-- ProcessGDBRemoteLog.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp index db7dc3e..6607bce 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp
@@ -1,9 +1,8 @@ //===-- ThreadGDBRemote.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,18 +20,18 @@ #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/State.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/StringExtractorGDBRemote.h" #include "ProcessGDBRemote.h" #include "ProcessGDBRemoteLog.h" -#include "lldb/Utility/StringExtractorGDBRemote.h" + +#include <memory> using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_gdb_remote; -//---------------------------------------------------------------------- // Thread Registers -//---------------------------------------------------------------------- ThreadGDBRemote::ThreadGDBRemote(Process &process, lldb::tid_t tid) : Thread(process, tid), m_thread_name(), m_dispatch_queue_name(), @@ -308,9 +307,9 @@ // supported. bool read_all_registers_at_once = !gdb_process->GetGDBRemote().GetpPacketSupported(GetID()); - reg_ctx_sp.reset(new GDBRemoteRegisterContext( + reg_ctx_sp = std::make_shared<GDBRemoteRegisterContext>( *this, concrete_frame_idx, gdb_process->m_register_info, - read_all_registers_at_once)); + read_all_registers_at_once); } } else { Unwind *unwinder = GetUnwinder();
diff --git a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h index 4485a9c..c74be16 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h +++ b/src/llvm-project/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h
@@ -1,9 +1,8 @@ //===-- ThreadGDBRemote.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,13 +11,14 @@ #include <string> -#include "lldb/Target/Process.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/StructuredData.h" class StringExtractor; namespace lldb_private { +class Process; + namespace process_gdb_remote { class ProcessGDBRemote;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp index 08b9f08..11b9e45 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp
@@ -1,10 +1,9 @@ //===-- ProcessMachCore.cpp ------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,7 +12,6 @@ #include "llvm/Support/MathExtras.h" #include "llvm/Support/Threading.h" -#include <mutex> #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" @@ -21,6 +19,7 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Host/Host.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/Target.h" @@ -40,6 +39,9 @@ #include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h" #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h" +#include <memory> +#include <mutex> + using namespace lldb; using namespace lldb_private; @@ -71,8 +73,8 @@ llvm::MachO::mach_header mach_header; if (ObjectFileMachO::ParseHeader(data, &data_offset, mach_header)) { if (mach_header.filetype == llvm::MachO::MH_CORE) - process_sp.reset( - new ProcessMachCore(target_sp, listener_sp, *crash_file)); + process_sp = std::make_shared<ProcessMachCore>(target_sp, listener_sp, + *crash_file); } } } @@ -92,7 +94,7 @@ // ModuleSpecList::FindMatchingModuleSpec enforces a strict arch mach. ModuleSpec core_module_spec(m_core_file); Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp, - NULL, NULL, NULL)); + nullptr, nullptr, nullptr)); if (m_core_module_sp) { ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); @@ -103,9 +105,7 @@ return false; } -//---------------------------------------------------------------------- // ProcessMachCore constructor -//---------------------------------------------------------------------- ProcessMachCore::ProcessMachCore(lldb::TargetSP target_sp, ListenerSP listener_sp, const FileSpec &core_file) @@ -114,9 +114,7 @@ m_dyld_addr(LLDB_INVALID_ADDRESS), m_mach_kernel_addr(LLDB_INVALID_ADDRESS), m_dyld_plugin_name() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ProcessMachCore::~ProcessMachCore() { Clear(); // We need to call finalize on the process before destroying ourselves to @@ -126,9 +124,7 @@ Finalize(); } -//---------------------------------------------------------------------- // PluginInterface -//---------------------------------------------------------------------- ConstString ProcessMachCore::GetPluginName() { return GetPluginNameStatic(); } uint32_t ProcessMachCore::GetPluginVersion() { return 1; } @@ -190,9 +186,7 @@ return false; } -//---------------------------------------------------------------------- // Process Control -//---------------------------------------------------------------------- Status ProcessMachCore::DoLoadCore() { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER | LIBLLDB_LOG_PROCESS)); @@ -203,7 +197,7 @@ } ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); - if (core_objfile == NULL) { + if (core_objfile == nullptr) { error.SetErrorString("invalid core object file"); return error; } @@ -216,7 +210,7 @@ } SectionList *section_list = core_objfile->GetSectionList(); - if (section_list == NULL) { + if (section_list == nullptr) { error.SetErrorString("core file has no sections"); return error; } @@ -315,7 +309,7 @@ size_t p = corefile_identifier.find("stext=") + strlen("stext="); if (corefile_identifier[p] == '0' && corefile_identifier[p + 1] == 'x') { errno = 0; - addr = ::strtoul(corefile_identifier.c_str() + p, NULL, 16); + addr = ::strtoul(corefile_identifier.c_str() + p, nullptr, 16); if (errno != 0 || addr == 0) addr = LLDB_INVALID_ADDRESS; } @@ -330,6 +324,60 @@ addr, corefile_identifier.c_str()); } } + if (found_main_binary_definitively == false + && corefile_identifier.find("EFI ") != std::string::npos) { + UUID uuid; + if (corefile_identifier.find("UUID=") != std::string::npos) { + size_t p = corefile_identifier.find("UUID=") + strlen("UUID="); + std::string uuid_str = corefile_identifier.substr(p, 36); + uuid.SetFromStringRef(uuid_str); + } + if (uuid.IsValid()) { + if (log) + log->Printf("ProcessMachCore::DoLoadCore: Using the EFI " + "from LC_IDENT/LC_NOTE 'kern ver str' string: '%s'", + corefile_identifier.c_str()); + + // We're only given a UUID here, not a load address. + // But there are python scripts in the EFI binary's dSYM which + // know how to relocate the binary to the correct load address. + // lldb only needs to locate & load the binary + dSYM. + ModuleSpec module_spec; + module_spec.GetUUID() = uuid; + module_spec.GetArchitecture() = GetTarget().GetArchitecture(); + + // Lookup UUID locally, before attempting dsymForUUID like action + FileSpecList search_paths = + Target::GetDefaultDebugFileSearchPaths(); + module_spec.GetSymbolFileSpec() = + Symbols::LocateExecutableSymbolFile(module_spec, search_paths); + if (module_spec.GetSymbolFileSpec()) { + ModuleSpec executable_module_spec = + Symbols::LocateExecutableObjectFile(module_spec); + if (FileSystem::Instance().Exists(executable_module_spec.GetFileSpec())) { + module_spec.GetFileSpec() = + executable_module_spec.GetFileSpec(); + } + } + + // Force a a dsymForUUID lookup, if that tool is available. + if (!module_spec.GetSymbolFileSpec()) + Symbols::DownloadObjectAndSymbolFile(module_spec, true); + + if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) { + ModuleSP module_sp(new Module(module_spec)); + if (module_sp.get() && module_sp->GetObjectFile()) { + // Get the current target executable + ModuleSP exe_module_sp(GetTarget().GetExecutableModule()); + + // Make sure you don't already have the right module loaded + // and they will be uniqued + if (exe_module_sp.get() != module_sp.get()) + GetTarget().SetExecutableModule(module_sp, eLoadDependentsNo); + } + } + } + } if (!found_main_binary_definitively && (m_dyld_addr == LLDB_INVALID_ADDRESS || @@ -454,11 +502,11 @@ } lldb_private::DynamicLoader *ProcessMachCore::GetDynamicLoader() { - if (m_dyld_ap.get() == NULL) - m_dyld_ap.reset(DynamicLoader::FindPlugin( - this, - m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString())); - return m_dyld_ap.get(); + if (m_dyld_up.get() == nullptr) + m_dyld_up.reset(DynamicLoader::FindPlugin( + this, m_dyld_plugin_name.IsEmpty() ? nullptr + : m_dyld_plugin_name.GetCString())); + return m_dyld_up.get(); } bool ProcessMachCore::UpdateThreadList(ThreadList &old_thread_list, @@ -492,17 +540,13 @@ Status ProcessMachCore::DoDestroy() { return Status(); } -//------------------------------------------------------------------ // Process Queries -//------------------------------------------------------------------ bool ProcessMachCore::IsAlive() { return true; } bool ProcessMachCore::WarnBeforeDetach() const { return false; } -//------------------------------------------------------------------ // Process Memory -//------------------------------------------------------------------ size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) { // Don't allow the caching that lldb_private::Process::ReadMemory does since @@ -516,7 +560,6 @@ size_t bytes_read = 0; if (core_objfile) { - //---------------------------------------------------------------------- // Segments are not always contiguous in mach-o core files. We have core // files that have segments like: // Address Size File off File size @@ -533,7 +576,6 @@ // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16 // unless we loop through consecutive memory ranges that are contiguous in // the address space, but not in the file data. - //---------------------------------------------------------------------- while (bytes_read < size) { const addr_t curr_addr = addr + bytes_read; const VMRangeToFileOffset::Entry *core_memory_entry =
diff --git a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.h b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.h index 0c6fc69..e6b1256 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.h +++ b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ProcessMachCore.h
@@ -1,9 +1,8 @@ //===-- ProcessMachCore.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,9 +20,7 @@ class ProcessMachCore : public lldb_private::Process { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ ProcessMachCore(lldb::TargetSP target_sp, lldb::ListenerSP listener, const lldb_private::FileSpec &core_file); @@ -41,43 +38,31 @@ static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // Check if a given Process - //------------------------------------------------------------------ bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override; - //------------------------------------------------------------------ // Creating a new process, or attaching to an existing one - //------------------------------------------------------------------ lldb_private::Status DoLoadCore() override; lldb_private::DynamicLoader *GetDynamicLoader() override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - //------------------------------------------------------------------ // Process Control - //------------------------------------------------------------------ lldb_private::Status DoDestroy() override; void RefreshStateAfterStop() override; - //------------------------------------------------------------------ // Process Queries - //------------------------------------------------------------------ bool IsAlive() override; bool WarnBeforeDetach() const override; - //------------------------------------------------------------------ // Process Memory - //------------------------------------------------------------------ size_t ReadMemory(lldb::addr_t addr, void *buf, size_t size, lldb_private::Status &error) override; @@ -103,12 +88,8 @@ private: bool GetDynamicLoaderAddress(lldb::addr_t addr); - typedef enum CorefilePreference { - eUserProcessCorefile, - eKernelCorefile - } CorefilePreferences; + enum CorefilePreference { eUserProcessCorefile, eKernelCorefile }; - //------------------------------------------------------------------ /// If a core file can be interpreted multiple ways, this establishes /// which style wins. /// @@ -118,7 +99,6 @@ /// memory. Or it could be a user process coredump of lldb while doing /// kernel debugging - so a copy of the kernel is in its heap. This /// should become a setting so it can be over-ridden when necessary. - //------------------------------------------------------------------ CorefilePreference GetCorefilePreference() { // For now, if both user process and kernel binaries a present, // assume this is a kernel coredump which has a copy of a user @@ -126,9 +106,7 @@ return eKernelCorefile; } - //------------------------------------------------------------------ // For ProcessMachCore only - //------------------------------------------------------------------ typedef lldb_private::Range<lldb::addr_t, lldb::addr_t> FileRange; typedef lldb_private::RangeDataVector<lldb::addr_t, lldb::addr_t, FileRange> VMRangeToFileOffset;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.cpp b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.cpp index 16edd28..b71e484 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.cpp
@@ -1,9 +1,8 @@ //===-- ThreadMachCore.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,9 +28,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Thread Registers -//---------------------------------------------------------------------- ThreadMachCore::ThreadMachCore(Process &process, lldb::tid_t tid) : Thread(process, tid), m_thread_name(), m_dispatch_queue_name(),
diff --git a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.h b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.h index 696ba72..ac5957e 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.h +++ b/src/llvm-project/lldb/source/Plugins/Process/mach-core/ThreadMachCore.h
@@ -1,9 +1,8 @@ //===-- ThreadMachCore.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -53,17 +52,13 @@ protected: friend class ProcessMachCore; - //------------------------------------------------------------------ // Member variables. - //------------------------------------------------------------------ std::string m_thread_name; std::string m_dispatch_queue_name; lldb::addr_t m_thread_dispatch_qaddr; lldb::RegisterContextSP m_thread_reg_ctx_sp; - //------------------------------------------------------------------ // Protected member functions. - //------------------------------------------------------------------ bool CalculateStopInfo() override; };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/Process/minidump/CMakeLists.txt index 4126a7e..afa3550 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/CMakeLists.txt
@@ -15,5 +15,7 @@ lldbPluginProcessUtility lldbPluginProcessElfCore LINK_COMPONENTS + BinaryFormat + Object Support )
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp index d4053ca..ff015aa 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp
@@ -1,9 +1,8 @@ //===-- MinidumpParser.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,8 +10,9 @@ #include "NtStructures.h" #include "RegisterContextMinidump_x86_32.h" -#include "lldb/Utility/LLDBAssert.h" #include "Plugins/Process/Utility/LinuxProcMaps.h" +#include "lldb/Utility/LLDBAssert.h" +#include "lldb/Utility/Log.h" // C includes // C++ includes @@ -24,47 +24,33 @@ using namespace lldb_private; using namespace minidump; -llvm::Optional<MinidumpParser> -MinidumpParser::Create(const lldb::DataBufferSP &data_buf_sp) { - if (data_buf_sp->GetByteSize() < sizeof(MinidumpHeader)) { - return llvm::None; - } - return MinidumpParser(data_buf_sp); +llvm::Expected<MinidumpParser> +MinidumpParser::Create(const lldb::DataBufferSP &data_sp) { + auto ExpectedFile = llvm::object::MinidumpFile::create( + llvm::MemoryBufferRef(toStringRef(data_sp->GetData()), "minidump")); + if (!ExpectedFile) + return ExpectedFile.takeError(); + + return MinidumpParser(data_sp, std::move(*ExpectedFile)); } -MinidumpParser::MinidumpParser(const lldb::DataBufferSP &data_buf_sp) - : m_data_sp(data_buf_sp) {} +MinidumpParser::MinidumpParser(lldb::DataBufferSP data_sp, + std::unique_ptr<llvm::object::MinidumpFile> file) + : m_data_sp(std::move(data_sp)), m_file(std::move(file)) {} llvm::ArrayRef<uint8_t> MinidumpParser::GetData() { return llvm::ArrayRef<uint8_t>(m_data_sp->GetBytes(), m_data_sp->GetByteSize()); } -llvm::ArrayRef<uint8_t> -MinidumpParser::GetStream(MinidumpStreamType stream_type) { - auto iter = m_directory_map.find(static_cast<uint32_t>(stream_type)); - if (iter == m_directory_map.end()) - return {}; - - // check if there is enough data - if (iter->second.rva + iter->second.data_size > m_data_sp->GetByteSize()) - return {}; - - return llvm::ArrayRef<uint8_t>(m_data_sp->GetBytes() + iter->second.rva, - iter->second.data_size); +llvm::ArrayRef<uint8_t> MinidumpParser::GetStream(StreamType stream_type) { + return m_file->getRawStream(stream_type) + .getValueOr(llvm::ArrayRef<uint8_t>()); } -llvm::Optional<std::string> MinidumpParser::GetMinidumpString(uint32_t rva) { - auto arr_ref = m_data_sp->GetData(); - if (rva > arr_ref.size()) - return llvm::None; - arr_ref = arr_ref.drop_front(rva); - return parseMinidumpString(arr_ref); -} - -UUID MinidumpParser::GetModuleUUID(const MinidumpModule *module) { +UUID MinidumpParser::GetModuleUUID(const minidump::Module *module) { auto cv_record = - GetData().slice(module->CV_record.rva, module->CV_record.data_size); + GetData().slice(module->CvRecord.RVA, module->CvRecord.DataSize); // Read the CV record signature const llvm::support::ulittle32_t *signature = nullptr; @@ -73,60 +59,68 @@ return UUID(); const CvSignature cv_signature = - static_cast<CvSignature>(static_cast<const uint32_t>(*signature)); + static_cast<CvSignature>(static_cast<uint32_t>(*signature)); if (cv_signature == CvSignature::Pdb70) { - // PDB70 record const CvRecordPdb70 *pdb70_uuid = nullptr; Status error = consumeObject(cv_record, pdb70_uuid); - if (!error.Fail()) { - auto arch = GetArchitecture(); - // For Apple targets we only need a 16 byte UUID so that we can match - // the UUID in the Module to actual UUIDs from the built binaries. The - // "Age" field is zero in breakpad minidump files for Apple targets, so - // we restrict the UUID to the "Uuid" field so we have a UUID we can use - // to match. - if (arch.GetTriple().getVendor() == llvm::Triple::Apple) - return UUID::fromData(pdb70_uuid->Uuid, sizeof(pdb70_uuid->Uuid)); - else - return UUID::fromData(pdb70_uuid, sizeof(*pdb70_uuid)); + if (error.Fail()) + return UUID(); + + CvRecordPdb70 swapped; + if (!GetArchitecture().GetTriple().isOSBinFormatELF()) { + // LLDB's UUID class treats the data as a sequence of bytes, but breakpad + // interprets it as a sequence of little-endian fields, which it converts + // to big-endian when converting to text. Swap the bytes to big endian so + // that the string representation comes out right. + swapped = *pdb70_uuid; + llvm::sys::swapByteOrder(swapped.Uuid.Data1); + llvm::sys::swapByteOrder(swapped.Uuid.Data2); + llvm::sys::swapByteOrder(swapped.Uuid.Data3); + llvm::sys::swapByteOrder(swapped.Age); + pdb70_uuid = &swapped; } + if (pdb70_uuid->Age != 0) + return UUID::fromOptionalData(pdb70_uuid, sizeof(*pdb70_uuid)); + return UUID::fromOptionalData(&pdb70_uuid->Uuid, sizeof(pdb70_uuid->Uuid)); } else if (cv_signature == CvSignature::ElfBuildId) - return UUID::fromData(cv_record); + return UUID::fromOptionalData(cv_record); return UUID(); } -llvm::ArrayRef<MinidumpThread> MinidumpParser::GetThreads() { - llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::ThreadList); +llvm::ArrayRef<minidump::Thread> MinidumpParser::GetThreads() { + auto ExpectedThreads = GetMinidumpFile().getThreadList(); + if (ExpectedThreads) + return *ExpectedThreads; - if (data.size() == 0) - return llvm::None; - - return MinidumpThread::ParseThreadList(data); + LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD), + ExpectedThreads.takeError(), + "Failed to read thread list: {0}"); + return {}; } llvm::ArrayRef<uint8_t> -MinidumpParser::GetThreadContext(const MinidumpLocationDescriptor &location) { - if (location.rva + location.data_size > GetData().size()) +MinidumpParser::GetThreadContext(const LocationDescriptor &location) { + if (location.RVA + location.DataSize > GetData().size()) return {}; - return GetData().slice(location.rva, location.data_size); + return GetData().slice(location.RVA, location.DataSize); } llvm::ArrayRef<uint8_t> -MinidumpParser::GetThreadContext(const MinidumpThread &td) { - return GetThreadContext(td.thread_context); +MinidumpParser::GetThreadContext(const minidump::Thread &td) { + return GetThreadContext(td.Context); } llvm::ArrayRef<uint8_t> -MinidumpParser::GetThreadContextWow64(const MinidumpThread &td) { +MinidumpParser::GetThreadContextWow64(const minidump::Thread &td) { // On Windows, a 32-bit process can run on a 64-bit machine under WOW64. If // the minidump was captured with a 64-bit debugger, then the CONTEXT we just // grabbed from the mini_dump_thread is the one for the 64-bit "native" // process rather than the 32-bit "guest" process we care about. In this // case, we can get the 32-bit CONTEXT from the TEB (Thread Environment // Block) of the 64-bit process. - auto teb_mem = GetMemory(td.teb, sizeof(TEB64)); + auto teb_mem = GetMemory(td.EnvironmentBlock, sizeof(TEB64)); if (teb_mem.empty()) return {}; @@ -149,24 +143,19 @@ // stored in the first slot of the 64-bit TEB (wow64teb.Reserved1[0]). } -const MinidumpSystemInfo *MinidumpParser::GetSystemInfo() { - llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::SystemInfo); - - if (data.size() == 0) - return nullptr; - - return MinidumpSystemInfo::Parse(data); -} - ArchSpec MinidumpParser::GetArchitecture() { if (m_arch.IsValid()) return m_arch; // Set the architecture in m_arch - const MinidumpSystemInfo *system_info = GetSystemInfo(); + llvm::Expected<const SystemInfo &> system_info = m_file->getSystemInfo(); - if (!system_info) + if (!system_info) { + LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS), + system_info.takeError(), + "Failed to read SystemInfo stream: {0}"); return m_arch; + } // TODO what to do about big endiand flavors of arm ? // TODO set the arm subarch stuff if the minidump has info about it @@ -174,21 +163,17 @@ llvm::Triple triple; triple.setVendor(llvm::Triple::VendorType::UnknownVendor); - const MinidumpCPUArchitecture arch = - static_cast<const MinidumpCPUArchitecture>( - static_cast<const uint32_t>(system_info->processor_arch)); - - switch (arch) { - case MinidumpCPUArchitecture::X86: + switch (system_info->ProcessorArch) { + case ProcessorArchitecture::X86: triple.setArch(llvm::Triple::ArchType::x86); break; - case MinidumpCPUArchitecture::AMD64: + case ProcessorArchitecture::AMD64: triple.setArch(llvm::Triple::ArchType::x86_64); break; - case MinidumpCPUArchitecture::ARM: + case ProcessorArchitecture::ARM: triple.setArch(llvm::Triple::ArchType::arm); break; - case MinidumpCPUArchitecture::ARM64: + case ProcessorArchitecture::ARM64: triple.setArch(llvm::Triple::ArchType::aarch64); break; default: @@ -196,48 +181,49 @@ break; } - const MinidumpOSPlatform os = static_cast<const MinidumpOSPlatform>( - static_cast<const uint32_t>(system_info->platform_id)); - // TODO add all of the OSes that Minidump/breakpad distinguishes? - switch (os) { - case MinidumpOSPlatform::Win32S: - case MinidumpOSPlatform::Win32Windows: - case MinidumpOSPlatform::Win32NT: - case MinidumpOSPlatform::Win32CE: + switch (system_info->PlatformId) { + case OSPlatform::Win32S: + case OSPlatform::Win32Windows: + case OSPlatform::Win32NT: + case OSPlatform::Win32CE: triple.setOS(llvm::Triple::OSType::Win32); break; - case MinidumpOSPlatform::Linux: + case OSPlatform::Linux: triple.setOS(llvm::Triple::OSType::Linux); break; - case MinidumpOSPlatform::MacOSX: + case OSPlatform::MacOSX: triple.setOS(llvm::Triple::OSType::MacOSX); triple.setVendor(llvm::Triple::Apple); break; - case MinidumpOSPlatform::IOS: + case OSPlatform::IOS: triple.setOS(llvm::Triple::OSType::IOS); triple.setVendor(llvm::Triple::Apple); break; - case MinidumpOSPlatform::Android: + case OSPlatform::Android: triple.setOS(llvm::Triple::OSType::Linux); triple.setEnvironment(llvm::Triple::EnvironmentType::Android); break; default: { triple.setOS(llvm::Triple::OSType::UnknownOS); - std::string csd_version; - if (auto s = GetMinidumpString(system_info->csd_version_rva)) - csd_version = *s; - if (csd_version.find("Linux") != std::string::npos) - triple.setOS(llvm::Triple::OSType::Linux); - break; + auto ExpectedCSD = m_file->getString(system_info->CSDVersionRVA); + if (!ExpectedCSD) { + LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS), + ExpectedCSD.takeError(), + "Failed to CSD Version string: {0}"); + } else { + if (ExpectedCSD->find("Linux") != std::string::npos) + triple.setOS(llvm::Triple::OSType::Linux); } + break; + } } m_arch.SetTriple(triple); return m_arch; } const MinidumpMiscInfo *MinidumpParser::GetMiscInfo() { - llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::MiscInfo); + llvm::ArrayRef<uint8_t> data = GetStream(StreamType::MiscInfo); if (data.size() == 0) return nullptr; @@ -246,7 +232,7 @@ } llvm::Optional<LinuxProcStatus> MinidumpParser::GetLinuxProcStatus() { - llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::LinuxProcStatus); + llvm::ArrayRef<uint8_t> data = GetStream(StreamType::LinuxProcStatus); if (data.size() == 0) return llvm::None; @@ -268,41 +254,47 @@ return llvm::None; } -llvm::ArrayRef<MinidumpModule> MinidumpParser::GetModuleList() { - llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::ModuleList); +llvm::ArrayRef<minidump::Module> MinidumpParser::GetModuleList() { + auto ExpectedModules = GetMinidumpFile().getModuleList(); + if (ExpectedModules) + return *ExpectedModules; - if (data.size() == 0) - return {}; - - return MinidumpModule::ParseModuleList(data); + LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_MODULES), + ExpectedModules.takeError(), + "Failed to read module list: {0}"); + return {}; } -std::vector<const MinidumpModule *> MinidumpParser::GetFilteredModuleList() { - llvm::ArrayRef<MinidumpModule> modules = GetModuleList(); +std::vector<const minidump::Module *> MinidumpParser::GetFilteredModuleList() { + Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_MODULES); + auto ExpectedModules = GetMinidumpFile().getModuleList(); + if (!ExpectedModules) { + LLDB_LOG_ERROR(log, ExpectedModules.takeError(), + "Failed to read module list: {0}"); + return {}; + } + // map module_name -> filtered_modules index typedef llvm::StringMap<size_t> MapType; MapType module_name_to_filtered_index; - std::vector<const MinidumpModule *> filtered_modules; - - llvm::Optional<std::string> name; - std::string module_name; + std::vector<const minidump::Module *> filtered_modules; - for (const auto &module : modules) { - name = GetMinidumpString(module.module_name_rva); - - if (!name) + for (const auto &module : *ExpectedModules) { + auto ExpectedName = m_file->getString(module.ModuleNameRVA); + if (!ExpectedName) { + LLDB_LOG_ERROR(log, ExpectedName.takeError(), + "Failed to get module name: {0}"); continue; - - module_name = name.getValue(); - + } + MapType::iterator iter; bool inserted; // See if we have inserted this module aready into filtered_modules. If we // haven't insert an entry into module_name_to_filtered_index with the // index where we will insert it if it isn't in the vector already. std::tie(iter, inserted) = module_name_to_filtered_index.try_emplace( - module_name, filtered_modules.size()); + *ExpectedName, filtered_modules.size()); if (inserted) { // This module has not been seen yet, insert it into filtered_modules at @@ -314,7 +306,7 @@ // times when they are mapped discontiguously, so find the module with // the lowest "base_of_image" and use that as the filtered module. auto dup_module = filtered_modules[iter->second]; - if (module.base_of_image < dup_module->base_of_image) + if (module.BaseOfImage < dup_module->BaseOfImage) filtered_modules[iter->second] = &module; } } @@ -322,7 +314,7 @@ } const MinidumpExceptionStream *MinidumpParser::GetExceptionStream() { - llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::Exception); + llvm::ArrayRef<uint8_t> data = GetStream(StreamType::Exception); if (data.size() == 0) return nullptr; @@ -332,30 +324,30 @@ llvm::Optional<minidump::Range> MinidumpParser::FindMemoryRange(lldb::addr_t addr) { - llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::MemoryList); - llvm::ArrayRef<uint8_t> data64 = GetStream(MinidumpStreamType::Memory64List); + llvm::ArrayRef<uint8_t> data64 = GetStream(StreamType::Memory64List); + Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_MODULES); - if (data.empty() && data64.empty()) - return llvm::None; + auto ExpectedMemory = GetMinidumpFile().getMemoryList(); + if (!ExpectedMemory) { + LLDB_LOG_ERROR(log, ExpectedMemory.takeError(), + "Failed to read memory list: {0}"); + } else { + for (const auto &memory_desc : *ExpectedMemory) { + const LocationDescriptor &loc_desc = memory_desc.Memory; + const lldb::addr_t range_start = memory_desc.StartOfMemoryRange; + const size_t range_size = loc_desc.DataSize; - if (!data.empty()) { - llvm::ArrayRef<MinidumpMemoryDescriptor> memory_list = - MinidumpMemoryDescriptor::ParseMemoryList(data); - - if (memory_list.empty()) - return llvm::None; - - for (const auto &memory_desc : memory_list) { - const MinidumpLocationDescriptor &loc_desc = memory_desc.memory; - const lldb::addr_t range_start = memory_desc.start_of_memory_range; - const size_t range_size = loc_desc.data_size; - - if (loc_desc.rva + loc_desc.data_size > GetData().size()) + if (loc_desc.RVA + loc_desc.DataSize > GetData().size()) return llvm::None; if (range_start <= addr && addr < range_start + range_size) { - return minidump::Range(range_start, - GetData().slice(loc_desc.rva, range_size)); + auto ExpectedSlice = GetMinidumpFile().getRawData(loc_desc); + if (!ExpectedSlice) { + LLDB_LOG_ERROR(log, ExpectedSlice.takeError(), + "Failed to get memory slice: {0}"); + return llvm::None; + } + return minidump::Range(range_start, *ExpectedSlice); } } } @@ -418,7 +410,7 @@ static bool CreateRegionsCacheFromLinuxMaps(MinidumpParser &parser, std::vector<MemoryRegionInfo> ®ions) { - auto data = parser.GetStream(MinidumpStreamType::LinuxMaps); + auto data = parser.GetStream(StreamType::LinuxMaps); if (data.empty()) return false; ParseLinuxMapRegions(llvm::toStringRef(data), @@ -434,7 +426,7 @@ static bool CreateRegionsCacheFromMemoryInfoList(MinidumpParser &parser, std::vector<MemoryRegionInfo> ®ions) { - auto data = parser.GetStream(MinidumpStreamType::MemoryInfoList); + auto data = parser.GetStream(StreamType::MemoryInfoList); if (data.empty()) return false; auto mem_info_list = MinidumpMemoryInfo::ParseMemoryInfoList(data); @@ -459,19 +451,20 @@ static bool CreateRegionsCacheFromMemoryList(MinidumpParser &parser, std::vector<MemoryRegionInfo> ®ions) { - auto data = parser.GetStream(MinidumpStreamType::MemoryList); - if (data.empty()) + Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_MODULES); + auto ExpectedMemory = parser.GetMinidumpFile().getMemoryList(); + if (!ExpectedMemory) { + LLDB_LOG_ERROR(log, ExpectedMemory.takeError(), + "Failed to read memory list: {0}"); return false; - auto memory_list = MinidumpMemoryDescriptor::ParseMemoryList(data); - if (memory_list.empty()) - return false; - regions.reserve(memory_list.size()); - for (const auto &memory_desc : memory_list) { - if (memory_desc.memory.data_size == 0) + } + regions.reserve(ExpectedMemory->size()); + for (const MemoryDescriptor &memory_desc : *ExpectedMemory) { + if (memory_desc.Memory.DataSize == 0) continue; MemoryRegionInfo region; - region.GetRange().SetRangeBase(memory_desc.start_of_memory_range); - region.GetRange().SetByteSize(memory_desc.memory.data_size); + region.GetRange().SetRangeBase(memory_desc.StartOfMemoryRange); + region.GetRange().SetByteSize(memory_desc.Memory.DataSize); region.SetReadable(MemoryRegionInfo::eYes); region.SetMapped(MemoryRegionInfo::eYes); regions.push_back(region); @@ -484,7 +477,7 @@ CreateRegionsCacheFromMemory64List(MinidumpParser &parser, std::vector<MemoryRegionInfo> ®ions) { llvm::ArrayRef<uint8_t> data = - parser.GetStream(MinidumpStreamType::Memory64List); + parser.GetStream(StreamType::Memory64List); if (data.empty()) return false; llvm::ArrayRef<MinidumpMemoryDescriptor64> memory64_list; @@ -564,120 +557,14 @@ return m_regions; } -Status MinidumpParser::Initialize() { - Status error; - - lldbassert(m_directory_map.empty()); - - llvm::ArrayRef<uint8_t> header_data(m_data_sp->GetBytes(), - sizeof(MinidumpHeader)); - const MinidumpHeader *header = MinidumpHeader::Parse(header_data); - if (header == nullptr) { - error.SetErrorString("invalid minidump: can't parse the header"); - return error; - } - - // A minidump without at least one stream is clearly ill-formed - if (header->streams_count == 0) { - error.SetErrorString("invalid minidump: no streams present"); - return error; - } - - struct FileRange { - uint32_t offset = 0; - uint32_t size = 0; - - FileRange(uint32_t offset, uint32_t size) : offset(offset), size(size) {} - uint32_t end() const { return offset + size; } - }; - - const uint32_t file_size = m_data_sp->GetByteSize(); - - // Build a global minidump file map, checking for: - // - overlapping streams/data structures - // - truncation (streams pointing past the end of file) - std::vector<FileRange> minidump_map; - - // Add the minidump header to the file map - if (sizeof(MinidumpHeader) > file_size) { - error.SetErrorString("invalid minidump: truncated header"); - return error; - } - minidump_map.emplace_back( 0, sizeof(MinidumpHeader) ); - - // Add the directory entries to the file map - FileRange directory_range(header->stream_directory_rva, - header->streams_count * - sizeof(MinidumpDirectory)); - if (directory_range.end() > file_size) { - error.SetErrorString("invalid minidump: truncated streams directory"); - return error; - } - minidump_map.push_back(directory_range); - - // Parse stream directory entries - llvm::ArrayRef<uint8_t> directory_data( - m_data_sp->GetBytes() + directory_range.offset, directory_range.size); - for (uint32_t i = 0; i < header->streams_count; ++i) { - const MinidumpDirectory *directory_entry = nullptr; - error = consumeObject(directory_data, directory_entry); - if (error.Fail()) - return error; - if (directory_entry->stream_type == 0) { - // Ignore dummy streams (technically ill-formed, but a number of - // existing minidumps seem to contain such streams) - if (directory_entry->location.data_size == 0) - continue; - error.SetErrorString("invalid minidump: bad stream type"); - return error; - } - // Update the streams map, checking for duplicate stream types - if (!m_directory_map - .insert({directory_entry->stream_type, directory_entry->location}) - .second) { - error.SetErrorString("invalid minidump: duplicate stream type"); - return error; - } - // Ignore the zero-length streams for layout checks - if (directory_entry->location.data_size != 0) { - minidump_map.emplace_back(directory_entry->location.rva, - directory_entry->location.data_size); - } - } - - // Sort the file map ranges by start offset - llvm::sort(minidump_map.begin(), minidump_map.end(), - [](const FileRange &a, const FileRange &b) { - return a.offset < b.offset; - }); - - // Check for overlapping streams/data structures - for (size_t i = 1; i < minidump_map.size(); ++i) { - const auto &prev_range = minidump_map[i - 1]; - if (prev_range.end() > minidump_map[i].offset) { - error.SetErrorString("invalid minidump: overlapping streams"); - return error; - } - } - - // Check for streams past the end of file - const auto &last_range = minidump_map.back(); - if (last_range.end() > file_size) { - error.SetErrorString("invalid minidump: truncated stream"); - return error; - } - - return error; -} - -#define ENUM_TO_CSTR(ST) case (uint32_t)MinidumpStreamType::ST: return #ST +#define ENUM_TO_CSTR(ST) \ + case StreamType::ST: \ + return #ST llvm::StringRef -MinidumpParser::GetStreamTypeAsString(uint32_t stream_type) { +MinidumpParser::GetStreamTypeAsString(StreamType stream_type) { switch (stream_type) { ENUM_TO_CSTR(Unused); - ENUM_TO_CSTR(Reserved0); - ENUM_TO_CSTR(Reserved1); ENUM_TO_CSTR(ThreadList); ENUM_TO_CSTR(ModuleList); ENUM_TO_CSTR(MemoryList); @@ -698,6 +585,7 @@ ENUM_TO_CSTR(JavascriptData); ENUM_TO_CSTR(SystemMemoryInfo); ENUM_TO_CSTR(ProcessVMCounters); + ENUM_TO_CSTR(LastReserved); ENUM_TO_CSTR(BreakpadInfo); ENUM_TO_CSTR(AssertionInfo); ENUM_TO_CSTR(LinuxCPUInfo); @@ -711,6 +599,17 @@ ENUM_TO_CSTR(LinuxProcStat); ENUM_TO_CSTR(LinuxProcUptime); ENUM_TO_CSTR(LinuxProcFD); + ENUM_TO_CSTR(FacebookAppCustomData); + ENUM_TO_CSTR(FacebookBuildID); + ENUM_TO_CSTR(FacebookAppVersionName); + ENUM_TO_CSTR(FacebookJavaStack); + ENUM_TO_CSTR(FacebookDalvikInfo); + ENUM_TO_CSTR(FacebookUnwindSymbols); + ENUM_TO_CSTR(FacebookDumpErrorLog); + ENUM_TO_CSTR(FacebookAppStateLog); + ENUM_TO_CSTR(FacebookAbortReason); + ENUM_TO_CSTR(FacebookThreadName); + ENUM_TO_CSTR(FacebookLogcat); } return "unknown stream type"; }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.h index 07ea6aa..fce64f0 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpParser.h
@@ -1,9 +1,8 @@ //===-- MinidumpParser.h -----------------------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,6 +21,7 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Object/Minidump.h" // C includes @@ -41,31 +41,30 @@ Range(lldb::addr_t start, llvm::ArrayRef<uint8_t> range_ref) : start(start), range_ref(range_ref) {} + + friend bool operator==(const Range &lhs, const Range &rhs) { + return lhs.start == rhs.start && lhs.range_ref == rhs.range_ref; + } }; class MinidumpParser { public: - static llvm::Optional<MinidumpParser> + static llvm::Expected<MinidumpParser> Create(const lldb::DataBufferSP &data_buf_sp); llvm::ArrayRef<uint8_t> GetData(); - llvm::ArrayRef<uint8_t> GetStream(MinidumpStreamType stream_type); + llvm::ArrayRef<uint8_t> GetStream(StreamType stream_type); - llvm::Optional<std::string> GetMinidumpString(uint32_t rva); + UUID GetModuleUUID(const minidump::Module *module); - UUID GetModuleUUID(const MinidumpModule* module); + llvm::ArrayRef<minidump::Thread> GetThreads(); - llvm::ArrayRef<MinidumpThread> GetThreads(); + llvm::ArrayRef<uint8_t> GetThreadContext(const LocationDescriptor &location); - llvm::ArrayRef<uint8_t> - GetThreadContext(const MinidumpLocationDescriptor &location); + llvm::ArrayRef<uint8_t> GetThreadContext(const minidump::Thread &td); - llvm::ArrayRef<uint8_t> GetThreadContext(const MinidumpThread &td); - - llvm::ArrayRef<uint8_t> GetThreadContextWow64(const MinidumpThread &td); - - const MinidumpSystemInfo *GetSystemInfo(); + llvm::ArrayRef<uint8_t> GetThreadContextWow64(const minidump::Thread &td); ArchSpec GetArchitecture(); @@ -75,13 +74,13 @@ llvm::Optional<lldb::pid_t> GetPid(); - llvm::ArrayRef<MinidumpModule> GetModuleList(); + llvm::ArrayRef<minidump::Module> GetModuleList(); // There are cases in which there is more than one record in the ModuleList // for the same module name.(e.g. when the binary has non contiguous segments) // So this function returns a filtered module list - if it finds records that // have the same name, it keeps the copy with the lowest load address. - std::vector<const MinidumpModule *> GetFilteredModuleList(); + std::vector<const minidump::Module *> GetFilteredModuleList(); const MinidumpExceptionStream *GetExceptionStream(); @@ -93,24 +92,19 @@ const MemoryRegionInfos &GetMemoryRegions(); - // Perform consistency checks and initialize internal data structures - Status Initialize(); + static llvm::StringRef GetStreamTypeAsString(StreamType stream_type); - static llvm::StringRef GetStreamTypeAsString(uint32_t stream_type); - - const llvm::DenseMap<uint32_t, MinidumpLocationDescriptor> & - GetDirectoryMap() const { - return m_directory_map; - } + llvm::object::MinidumpFile &GetMinidumpFile() { return *m_file; } private: - MinidumpParser(const lldb::DataBufferSP &data_buf_sp); + MinidumpParser(lldb::DataBufferSP data_sp, + std::unique_ptr<llvm::object::MinidumpFile> file); MemoryRegionInfo FindMemoryRegion(lldb::addr_t load_addr) const; private: lldb::DataBufferSP m_data_sp; - llvm::DenseMap<uint32_t, MinidumpLocationDescriptor> m_directory_map; + std::unique_ptr<llvm::object::MinidumpFile> m_file; ArchSpec m_arch; MemoryRegionInfos m_regions; bool m_parsed_regions = false;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp index 7b1900e..d7fc6e4 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp
@@ -1,9 +1,8 @@ //===-- MinidumpTypes.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,96 +14,6 @@ using namespace lldb_private; using namespace minidump; -const MinidumpHeader *MinidumpHeader::Parse(llvm::ArrayRef<uint8_t> &data) { - const MinidumpHeader *header = nullptr; - Status error = consumeObject(data, header); - - const MinidumpHeaderConstants signature = - static_cast<const MinidumpHeaderConstants>( - static_cast<const uint32_t>(header->signature)); - const MinidumpHeaderConstants version = - static_cast<const MinidumpHeaderConstants>( - static_cast<const uint32_t>(header->version) & 0x0000ffff); - // the high 16 bits of the version field are implementation specific - - if (error.Fail() || signature != MinidumpHeaderConstants::Signature || - version != MinidumpHeaderConstants::Version) - return nullptr; - - return header; -} - -// Minidump string -llvm::Optional<std::string> -lldb_private::minidump::parseMinidumpString(llvm::ArrayRef<uint8_t> &data) { - std::string result; - - const uint32_t *source_length_ptr; - Status error = consumeObject(data, source_length_ptr); - - // Copy non-aligned source_length data into aligned memory. - uint32_t source_length; - std::memcpy(&source_length, source_length_ptr, sizeof(source_length)); - - if (error.Fail() || source_length > data.size() || source_length % 2 != 0) - return llvm::None; - - auto source_start = reinterpret_cast<const llvm::UTF16 *>(data.data()); - // source_length is the length of the string in bytes we need the length of - // the string in UTF-16 characters/code points (16 bits per char) that's why - // it's divided by 2 - const auto source_end = source_start + source_length / 2; - // resize to worst case length - result.resize(UNI_MAX_UTF8_BYTES_PER_CODE_POINT * source_length / 2); - auto result_start = reinterpret_cast<llvm::UTF8 *>(&result[0]); - const auto result_end = result_start + result.size(); - llvm::ConvertUTF16toUTF8(&source_start, source_end, &result_start, result_end, - llvm::strictConversion); - const auto result_size = - std::distance(reinterpret_cast<llvm::UTF8 *>(&result[0]), result_start); - result.resize(result_size); // shrink to actual length - - return result; -} - -// MinidumpThread -const MinidumpThread *MinidumpThread::Parse(llvm::ArrayRef<uint8_t> &data) { - const MinidumpThread *thread = nullptr; - Status error = consumeObject(data, thread); - if (error.Fail()) - return nullptr; - - return thread; -} - -llvm::ArrayRef<MinidumpThread> -MinidumpThread::ParseThreadList(llvm::ArrayRef<uint8_t> &data) { - const auto orig_size = data.size(); - const llvm::support::ulittle32_t *thread_count; - Status error = consumeObject(data, thread_count); - if (error.Fail() || *thread_count * sizeof(MinidumpThread) > data.size()) - return {}; - - // Compilers might end up padding an extra 4 bytes depending on how the - // structure is padded by the compiler and the #pragma pack settings. - if (4 + *thread_count * sizeof(MinidumpThread) < orig_size) - data = data.drop_front(4); - - return llvm::ArrayRef<MinidumpThread>( - reinterpret_cast<const MinidumpThread *>(data.data()), *thread_count); -} - -// MinidumpSystemInfo -const MinidumpSystemInfo * -MinidumpSystemInfo::Parse(llvm::ArrayRef<uint8_t> &data) { - const MinidumpSystemInfo *system_info; - Status error = consumeObject(data, system_info); - if (error.Fail()) - return nullptr; - - return system_info; -} - // MinidumpMiscInfo const MinidumpMiscInfo *MinidumpMiscInfo::Parse(llvm::ArrayRef<uint8_t> &data) { const MinidumpMiscInfo *misc_info; @@ -116,8 +25,7 @@ } llvm::Optional<lldb::pid_t> MinidumpMiscInfo::GetPid() const { - uint32_t pid_flag = - static_cast<const uint32_t>(MinidumpMiscInfoFlags::ProcessID); + uint32_t pid_flag = static_cast<uint32_t>(MinidumpMiscInfoFlags::ProcessID); if (flags1 & pid_flag) return llvm::Optional<lldb::pid_t>(process_id); @@ -149,33 +57,6 @@ lldb::pid_t LinuxProcStatus::GetPid() const { return pid; } -// Module stuff -const MinidumpModule *MinidumpModule::Parse(llvm::ArrayRef<uint8_t> &data) { - const MinidumpModule *module = nullptr; - Status error = consumeObject(data, module); - if (error.Fail()) - return nullptr; - - return module; -} - -llvm::ArrayRef<MinidumpModule> -MinidumpModule::ParseModuleList(llvm::ArrayRef<uint8_t> &data) { - const auto orig_size = data.size(); - const llvm::support::ulittle32_t *modules_count; - Status error = consumeObject(data, modules_count); - if (error.Fail() || *modules_count * sizeof(MinidumpModule) > data.size()) - return {}; - - // Compilers might end up padding an extra 4 bytes depending on how the - // structure is padded by the compiler and the #pragma pack settings. - if (4 + *modules_count * sizeof(MinidumpModule) < orig_size) - data = data.drop_front(4); - - return llvm::ArrayRef<MinidumpModule>( - reinterpret_cast<const MinidumpModule *>(data.data()), *modules_count); -} - // Exception stuff const MinidumpExceptionStream * MinidumpExceptionStream::Parse(llvm::ArrayRef<uint8_t> &data) { @@ -187,25 +68,6 @@ return exception_stream; } -llvm::ArrayRef<MinidumpMemoryDescriptor> -MinidumpMemoryDescriptor::ParseMemoryList(llvm::ArrayRef<uint8_t> &data) { - const auto orig_size = data.size(); - const llvm::support::ulittle32_t *mem_ranges_count; - Status error = consumeObject(data, mem_ranges_count); - if (error.Fail() || - *mem_ranges_count * sizeof(MinidumpMemoryDescriptor) > data.size()) - return {}; - - // Compilers might end up padding an extra 4 bytes depending on how the - // structure is padded by the compiler and the #pragma pack settings. - if (4 + *mem_ranges_count * sizeof(MinidumpMemoryDescriptor) < orig_size) - data = data.drop_front(4); - - return llvm::makeArrayRef( - reinterpret_cast<const MinidumpMemoryDescriptor *>(data.data()), - *mem_ranges_count); -} - std::pair<llvm::ArrayRef<MinidumpMemoryDescriptor64>, uint64_t> MinidumpMemoryDescriptor64::ParseMemory64List(llvm::ArrayRef<uint8_t> &data) { const llvm::support::ulittle64_t *mem_ranges_count;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.h index a5ea215..b4878e8 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/MinidumpTypes.h
@@ -1,9 +1,8 @@ //===-- MinidumpTypes.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,6 +17,7 @@ #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" +#include "llvm/BinaryFormat/Minidump.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Endian.h" @@ -32,15 +32,10 @@ namespace minidump { +using namespace llvm::minidump; + LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE(); -enum class MinidumpHeaderConstants : uint32_t { - Signature = 0x504d444d, // 'PMDM' - Version = 0x0000a793, // 42899 - LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ Signature) - -}; - enum class CvSignature : uint32_t { Pdb70 = 0x53445352, // RSDS ElfBuildId = 0x4270454c, // BpEL (Breakpad/Crashpad minidumps) @@ -49,124 +44,18 @@ // Reference: // https://crashpad.chromium.org/doxygen/structcrashpad_1_1CodeViewRecordPDB70.html struct CvRecordPdb70 { - uint8_t Uuid[16]; + struct { + llvm::support::ulittle32_t Data1; + llvm::support::ulittle16_t Data2; + llvm::support::ulittle16_t Data3; + uint8_t Data4[8]; + } Uuid; llvm::support::ulittle32_t Age; // char PDBFileName[]; }; static_assert(sizeof(CvRecordPdb70) == 20, "sizeof CvRecordPdb70 is not correct!"); -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680394.aspx -enum class MinidumpStreamType : uint32_t { - Unused = 0, - Reserved0 = 1, - Reserved1 = 2, - ThreadList = 3, - ModuleList = 4, - MemoryList = 5, - Exception = 6, - SystemInfo = 7, - ThreadExList = 8, - Memory64List = 9, - CommentA = 10, - CommentW = 11, - HandleData = 12, - FunctionTable = 13, - UnloadedModuleList = 14, - MiscInfo = 15, - MemoryInfoList = 16, - ThreadInfoList = 17, - HandleOperationList = 18, - Token = 19, - JavascriptData = 20, - SystemMemoryInfo = 21, - ProcessVMCounters = 22, - LastReserved = 0x0000ffff, - - /* Breakpad extension types. 0x4767 = "Gg" */ - BreakpadInfo = 0x47670001, - AssertionInfo = 0x47670002, - /* These are additional minidump stream values which are specific to - * the linux breakpad implementation. */ - LinuxCPUInfo = 0x47670003, /* /proc/cpuinfo */ - LinuxProcStatus = 0x47670004, /* /proc/$x/status */ - LinuxLSBRelease = 0x47670005, /* /etc/lsb-release */ - LinuxCMDLine = 0x47670006, /* /proc/$x/cmdline */ - LinuxEnviron = 0x47670007, /* /proc/$x/environ */ - LinuxAuxv = 0x47670008, /* /proc/$x/auxv */ - LinuxMaps = 0x47670009, /* /proc/$x/maps */ - LinuxDSODebug = 0x4767000A, - LinuxProcStat = 0x4767000B, /* /proc/$x/stat */ - LinuxProcUptime = 0x4767000C, /* uptime */ - LinuxProcFD = 0x4767000D, /* /proc/$x/fb */ -}; - -// for MinidumpSystemInfo.processor_arch -enum class MinidumpCPUArchitecture : uint16_t { - X86 = 0, /* PROCESSOR_ARCHITECTURE_INTEL */ - MIPS = 1, /* PROCESSOR_ARCHITECTURE_MIPS */ - Alpha = 2, /* PROCESSOR_ARCHITECTURE_ALPHA */ - PPC = 3, /* PROCESSOR_ARCHITECTURE_PPC */ - SHX = 4, /* PROCESSOR_ARCHITECTURE_SHX (Super-H) */ - ARM = 5, /* PROCESSOR_ARCHITECTURE_ARM */ - IA64 = 6, /* PROCESSOR_ARCHITECTURE_IA64 */ - Alpha64 = 7, /* PROCESSOR_ARCHITECTURE_ALPHA64 */ - MSIL = 8, /* PROCESSOR_ARCHITECTURE_MSIL - * (Microsoft Intermediate Language) */ - AMD64 = 9, /* PROCESSOR_ARCHITECTURE_AMD64 */ - X86Win64 = 10, /* PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 (WoW64) */ - SPARC = 0x8001, /* Breakpad-defined value for SPARC */ - PPC64 = 0x8002, /* Breakpad-defined value for PPC64 */ - ARM64 = 0x8003, /* Breakpad-defined value for ARM64 */ - MIPS64 = 0x8004, /* Breakpad-defined value for MIPS64 */ - Unknown = 0xffff /* PROCESSOR_ARCHITECTURE_UNKNOWN */ -}; - -// for MinidumpSystemInfo.platform_id -enum class MinidumpOSPlatform : uint32_t { - Win32S = 0, /* VER_PLATFORM_WIN32s (Windows 3.1) */ - Win32Windows = 1, /* VER_PLATFORM_WIN32_WINDOWS (Windows 95-98-Me) */ - Win32NT = 2, /* VER_PLATFORM_WIN32_NT (Windows NT, 2000+) */ - Win32CE = 3, /* VER_PLATFORM_WIN32_CE, VER_PLATFORM_WIN32_HH - * (Windows CE, Windows Mobile, "Handheld") */ - - /* The following values are Breakpad-defined. */ - Unix = 0x8000, /* Generic Unix-ish */ - MacOSX = 0x8101, /* Mac OS X/Darwin */ - IOS = 0x8102, /* iOS */ - Linux = 0x8201, /* Linux */ - Solaris = 0x8202, /* Solaris */ - Android = 0x8203, /* Android */ - PS3 = 0x8204, /* PS3 */ - NaCl = 0x8205 /* Native Client (NaCl) */ -}; - -// For MinidumpCPUInfo.arm_cpu_info.elf_hwcaps. -// This matches the Linux kernel definitions from <asm/hwcaps.h> -enum class MinidumpPCPUInformationARMElfHwCaps : uint32_t { - SWP = (1 << 0), - Half = (1 << 1), - Thumb = (1 << 2), - _26BIT = (1 << 3), - FastMult = (1 << 4), - FPA = (1 << 5), - VFP = (1 << 6), - EDSP = (1 << 7), - Java = (1 << 8), - IWMMXT = (1 << 9), - Crunch = (1 << 10), - ThumbEE = (1 << 11), - Neon = (1 << 12), - VFPv3 = (1 << 13), - VFPv3D16 = (1 << 14), - TLS = (1 << 15), - VFPv4 = (1 << 16), - IDIVA = (1 << 17), - IDIVT = (1 << 18), - LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ IDIVT) -}; - enum class MinidumpMiscInfoFlags : uint32_t { ProcessID = (1 << 0), ProcessTimes = (1 << 1), @@ -186,50 +75,6 @@ return error; } -// parse a MinidumpString which is with UTF-16 -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680395(v=vs.85).aspx -llvm::Optional<std::string> parseMinidumpString(llvm::ArrayRef<uint8_t> &data); - -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680378(v=vs.85).aspx -struct MinidumpHeader { - llvm::support::ulittle32_t signature; - llvm::support::ulittle32_t - version; // The high 16 bits of version field are implementation specific - llvm::support::ulittle32_t streams_count; - llvm::support::ulittle32_t - stream_directory_rva; // offset of the stream directory - llvm::support::ulittle32_t checksum; - llvm::support::ulittle32_t time_date_stamp; // time_t format - llvm::support::ulittle64_t flags; - - static const MinidumpHeader *Parse(llvm::ArrayRef<uint8_t> &data); -}; -static_assert(sizeof(MinidumpHeader) == 32, - "sizeof MinidumpHeader is not correct!"); - -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680383.aspx -struct MinidumpLocationDescriptor { - llvm::support::ulittle32_t data_size; - llvm::support::ulittle32_t rva; -}; -static_assert(sizeof(MinidumpLocationDescriptor) == 8, - "sizeof MinidumpLocationDescriptor is not correct!"); - -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680384(v=vs.85).aspx -struct MinidumpMemoryDescriptor { - llvm::support::ulittle64_t start_of_memory_range; - MinidumpLocationDescriptor memory; - - static llvm::ArrayRef<MinidumpMemoryDescriptor> - ParseMemoryList(llvm::ArrayRef<uint8_t> &data); -}; -static_assert(sizeof(MinidumpMemoryDescriptor) == 16, - "sizeof MinidumpMemoryDescriptor is not correct!"); - struct MinidumpMemoryDescriptor64 { llvm::support::ulittle64_t start_of_memory_range; llvm::support::ulittle64_t data_size; @@ -241,15 +86,6 @@ "sizeof MinidumpMemoryDescriptor64 is not correct!"); // Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680365.aspx -struct MinidumpDirectory { - llvm::support::ulittle32_t stream_type; - MinidumpLocationDescriptor location; -}; -static_assert(sizeof(MinidumpDirectory) == 12, - "sizeof MinidumpDirectory is not correct!"); - -// Reference: // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680385(v=vs.85).aspx struct MinidumpMemoryInfoListHeader { llvm::support::ulittle32_t size_of_header; @@ -333,72 +169,6 @@ static_assert(sizeof(MinidumpMemoryInfo) == 48, "sizeof MinidumpMemoryInfo is not correct!"); -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680517(v=vs.85).aspx -struct MinidumpThread { - llvm::support::ulittle32_t thread_id; - llvm::support::ulittle32_t suspend_count; - llvm::support::ulittle32_t priority_class; - llvm::support::ulittle32_t priority; - llvm::support::ulittle64_t teb; - MinidumpMemoryDescriptor stack; - MinidumpLocationDescriptor thread_context; - - static const MinidumpThread *Parse(llvm::ArrayRef<uint8_t> &data); - - static llvm::ArrayRef<MinidumpThread> - ParseThreadList(llvm::ArrayRef<uint8_t> &data); -}; -static_assert(sizeof(MinidumpThread) == 48, - "sizeof MinidumpThread is not correct!"); - -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680396(v=vs.85).aspx -union MinidumpCPUInfo { - struct { - llvm::support::ulittle32_t vendor_id[3]; /* cpuid 0: ebx, edx, ecx */ - llvm::support::ulittle32_t version_information; /* cpuid 1: eax */ - llvm::support::ulittle32_t feature_information; /* cpuid 1: edx */ - llvm::support::ulittle32_t - amd_extended_cpu_features; /* cpuid 0x80000001, ebx */ - } x86_cpu_info; - struct { - llvm::support::ulittle32_t cpuid; - llvm::support::ulittle32_t elf_hwcaps; /* linux specific, 0 otherwise */ - } arm_cpu_info; - struct { - llvm::support::ulittle64_t processor_features[2]; - } other_cpu_info; -}; -static_assert(sizeof(MinidumpCPUInfo) == 24, - "sizeof MinidumpCPUInfo is not correct!"); - -// Reference: -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680396(v=vs.85).aspx -struct MinidumpSystemInfo { - llvm::support::ulittle16_t processor_arch; - llvm::support::ulittle16_t processor_level; - llvm::support::ulittle16_t processor_revision; - - uint8_t number_of_processors; - uint8_t product_type; - - llvm::support::ulittle32_t major_version; - llvm::support::ulittle32_t minor_version; - llvm::support::ulittle32_t build_number; - llvm::support::ulittle32_t platform_id; - llvm::support::ulittle32_t csd_version_rva; - - llvm::support::ulittle16_t suit_mask; - llvm::support::ulittle16_t reserved2; - - MinidumpCPUInfo cpu; - - static const MinidumpSystemInfo *Parse(llvm::ArrayRef<uint8_t> &data); -}; -static_assert(sizeof(MinidumpSystemInfo) == 56, - "sizeof MinidumpSystemInfo is not correct!"); - // TODO misc2, misc3 ? // Reference: // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680389(v=vs.85).aspx @@ -432,46 +202,6 @@ LinuxProcStatus() = default; }; -// MinidumpModule stuff -struct MinidumpVSFixedFileInfo { - llvm::support::ulittle32_t signature; - llvm::support::ulittle32_t struct_version; - llvm::support::ulittle32_t file_version_hi; - llvm::support::ulittle32_t file_version_lo; - llvm::support::ulittle32_t product_version_hi; - llvm::support::ulittle32_t product_version_lo; - // file_flags_mask - identifies valid bits in fileFlags - llvm::support::ulittle32_t file_flags_mask; - llvm::support::ulittle32_t file_flags; - llvm::support::ulittle32_t file_os; - llvm::support::ulittle32_t file_type; - llvm::support::ulittle32_t file_subtype; - llvm::support::ulittle32_t file_date_hi; - llvm::support::ulittle32_t file_date_lo; -}; -static_assert(sizeof(MinidumpVSFixedFileInfo) == 52, - "sizeof MinidumpVSFixedFileInfo is not correct!"); - -struct MinidumpModule { - llvm::support::ulittle64_t base_of_image; - llvm::support::ulittle32_t size_of_image; - llvm::support::ulittle32_t checksum; - llvm::support::ulittle32_t time_date_stamp; - llvm::support::ulittle32_t module_name_rva; - MinidumpVSFixedFileInfo version_info; - MinidumpLocationDescriptor CV_record; - MinidumpLocationDescriptor misc_record; - llvm::support::ulittle32_t reserved0[2]; - llvm::support::ulittle32_t reserved1[2]; - - static const MinidumpModule *Parse(llvm::ArrayRef<uint8_t> &data); - - static llvm::ArrayRef<MinidumpModule> - ParseModuleList(llvm::ArrayRef<uint8_t> &data); -}; -static_assert(sizeof(MinidumpModule) == 108, - "sizeof MinidumpVSFixedFileInfo is not correct!"); - // Exception stuff struct MinidumpException { enum : unsigned { @@ -494,7 +224,7 @@ llvm::support::ulittle32_t thread_id; llvm::support::ulittle32_t alignment; MinidumpException exception_record; - MinidumpLocationDescriptor thread_context; + LocationDescriptor thread_context; static const MinidumpExceptionStream *Parse(llvm::ArrayRef<uint8_t> &data); };
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/NtStructures.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/NtStructures.h index c0afd77..fdb0cfb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/NtStructures.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/NtStructures.h
@@ -1,9 +1,8 @@ //===-- NtStructures.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp index c5cca7e..a7fc42c 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
@@ -1,13 +1,13 @@ //===-- ProcessMinidump.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "ProcessMinidump.h" + #include "ThreadMinidump.h" #include "lldb/Core/DumpDataExtractor.h" @@ -29,64 +29,93 @@ #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/State.h" - +#include "llvm/BinaryFormat/Magic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Threading.h" #include "Plugins/Process/Utility/StopInfoMachException.h" -// C includes -// C++ includes +#include <memory> using namespace lldb; using namespace lldb_private; using namespace minidump; -//------------------------------------------------------------------ -/// A placeholder module used for minidumps, where the original -/// object files may not be available (so we can't parse the object -/// files to extract the set of sections/segments) -/// -/// This placeholder module has a single synthetic section (.module_image) -/// which represents the module memory range covering the whole module. -//------------------------------------------------------------------ -class PlaceholderModule : public Module { +namespace { + +/// A minimal ObjectFile implementation providing a dummy object file for the +/// cases when the real module binary is not available. This allows the module +/// to show up in "image list" and symbols to be added to it. +class PlaceholderObjectFile : public ObjectFile { public: - PlaceholderModule(const ModuleSpec &module_spec) : - Module(module_spec.GetFileSpec(), module_spec.GetArchitecture()) { - if (module_spec.GetUUID().IsValid()) - SetUUID(module_spec.GetUUID()); + PlaceholderObjectFile(const lldb::ModuleSP &module_sp, + const ModuleSpec &module_spec, lldb::offset_t base, + lldb::offset_t size) + : ObjectFile(module_sp, &module_spec.GetFileSpec(), /*file_offset*/ 0, + /*length*/ 0, /*data_sp*/ nullptr, /*data_offset*/ 0), + m_arch(module_spec.GetArchitecture()), m_uuid(module_spec.GetUUID()), + m_base(base), m_size(size) { + m_symtab_up = llvm::make_unique<Symtab>(this); } - // Creates a synthetic module section covering the whole module image (and - // sets the section load address as well) - void CreateImageSection(const MinidumpModule *module, Target& target) { - const ConstString section_name(".module_image"); - lldb::SectionSP section_sp(new Section( - shared_from_this(), // Module to which this section belongs. - nullptr, // ObjectFile - 0, // Section ID. - section_name, // Section name. - eSectionTypeContainer, // Section type. - module->base_of_image, // VM address. - module->size_of_image, // VM size in bytes of this section. - 0, // Offset of this section in the file. - module->size_of_image, // Size of the section as found in the file. - 12, // Alignment of the section (log2) - 0, // Flags for this section. - 1)); // Number of host bytes per target byte - section_sp->SetPermissions(ePermissionsExecutable | ePermissionsReadable); - GetSectionList()->AddSection(section_sp); + ConstString GetPluginName() override { return ConstString("placeholder"); } + uint32_t GetPluginVersion() override { return 1; } + bool ParseHeader() override { return true; } + Type CalculateType() override { return eTypeUnknown; } + Strata CalculateStrata() override { return eStrataUnknown; } + uint32_t GetDependentModules(FileSpecList &file_list) override { return 0; } + bool IsExecutable() const override { return false; } + ArchSpec GetArchitecture() override { return m_arch; } + UUID GetUUID() override { return m_uuid; } + Symtab *GetSymtab() override { return m_symtab_up.get(); } + bool IsStripped() override { return true; } + ByteOrder GetByteOrder() const override { return m_arch.GetByteOrder(); } + + uint32_t GetAddressByteSize() const override { + return m_arch.GetAddressByteSize(); + } + + Address GetBaseAddress() override { + return Address(m_sections_up->GetSectionAtIndex(0), 0); + } + + void CreateSections(SectionList &unified_section_list) override { + m_sections_up = llvm::make_unique<SectionList>(); + auto section_sp = std::make_shared<Section>( + GetModule(), this, /*sect_id*/ 0, ConstString(".module_image"), + eSectionTypeOther, m_base, m_size, /*file_offset*/ 0, /*file_size*/ 0, + /*log2align*/ 0, /*flags*/ 0); + section_sp->SetPermissions(ePermissionsReadable | ePermissionsExecutable); + m_sections_up->AddSection(section_sp); + unified_section_list.AddSection(std::move(section_sp)); + } + + bool SetLoadAddress(Target &target, addr_t value, + bool value_is_offset) override { + assert(!value_is_offset); + assert(value == m_base); + + // Create sections if they haven't been created already. + GetModule()->GetSectionList(); + assert(m_sections_up->GetNumSections(0) == 1); + target.GetSectionLoadList().SetSectionLoadAddress( - section_sp, module->base_of_image); + m_sections_up->GetSectionAtIndex(0), m_base); + return true; } -ObjectFile *GetObjectFile() override { return nullptr; } - - SectionList *GetSectionList() override { - return Module::GetUnifiedSectionList(); + void Dump(Stream *s) override { + s->Format("Placeholder object file for {0} loaded at [{1:x}-{2:x})\n", + GetFileSpec(), m_base, m_base + m_size); } + +private: + ArchSpec m_arch; + UUID m_uuid; + lldb::offset_t m_base; + lldb::offset_t m_size; }; +} // namespace ConstString ProcessMinidump::GetPluginNameStatic() { static ConstString g_name("minidump"); @@ -105,18 +134,14 @@ lldb::ProcessSP process_sp; // Read enough data for the Minidump header - constexpr size_t header_size = sizeof(MinidumpHeader); + constexpr size_t header_size = sizeof(Header); auto DataPtr = FileSystem::Instance().CreateDataBuffer(crash_file->GetPath(), header_size, 0); if (!DataPtr) return nullptr; lldbassert(DataPtr->GetByteSize() == header_size); - - // first, only try to parse the header, beacuse we need to be fast - llvm::ArrayRef<uint8_t> HeaderBytes = DataPtr->GetData(); - const MinidumpHeader *header = MinidumpHeader::Parse(HeaderBytes); - if (header == nullptr) + if (identify_magic(toStringRef(DataPtr->GetData())) != llvm::file_magic::minidump) return nullptr; auto AllData = @@ -124,13 +149,8 @@ if (!AllData) return nullptr; - auto minidump_parser = MinidumpParser::Create(AllData); - // check if the parser object is valid - if (!minidump_parser) - return nullptr; - return std::make_shared<ProcessMinidump>(target_sp, listener_sp, *crash_file, - minidump_parser.getValue()); + std::move(AllData)); } bool ProcessMinidump::CanDebug(lldb::TargetSP target_sp, @@ -141,9 +161,9 @@ ProcessMinidump::ProcessMinidump(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec &core_file, - MinidumpParser minidump_parser) - : Process(target_sp, listener_sp), m_minidump_parser(minidump_parser), - m_core_file(core_file), m_is_wow64(false) {} + DataBufferSP core_data) + : Process(target_sp, listener_sp), m_core_file(core_file), + m_core_data(std::move(core_data)), m_is_wow64(false) {} ProcessMinidump::~ProcessMinidump() { Clear(); @@ -169,12 +189,12 @@ } Status ProcessMinidump::DoLoadCore() { - Status error; + auto expected_parser = MinidumpParser::Create(m_core_data); + if (!expected_parser) + return Status(expected_parser.takeError()); + m_minidump_parser = std::move(*expected_parser); - // Minidump parser initialization & consistency checks - error = m_minidump_parser.Initialize(); - if (error.Fail()) - return error; + Status error; // Do we support the minidump's architecture? ArchSpec arch = GetArchitecture(); @@ -193,11 +213,11 @@ } GetTarget().SetArchitecture(arch, true /*set_platform*/); - m_thread_list = m_minidump_parser.GetThreads(); - m_active_exception = m_minidump_parser.GetExceptionStream(); + m_thread_list = m_minidump_parser->GetThreads(); + m_active_exception = m_minidump_parser->GetExceptionStream(); ReadModuleList(); - llvm::Optional<lldb::pid_t> pid = m_minidump_parser.GetPid(); + llvm::Optional<lldb::pid_t> pid = m_minidump_parser->GetPid(); if (!pid) { error.SetErrorString("failed to parse PID"); return error; @@ -268,7 +288,7 @@ size_t ProcessMinidump::DoReadMemory(lldb::addr_t addr, void *buf, size_t size, Status &error) { - llvm::ArrayRef<uint8_t> mem = m_minidump_parser.GetMemory(addr, size); + llvm::ArrayRef<uint8_t> mem = m_minidump_parser->GetMemory(addr, size); if (mem.empty()) { error.SetErrorString("could not parse memory info"); return 0; @@ -280,7 +300,7 @@ ArchSpec ProcessMinidump::GetArchitecture() { if (!m_is_wow64) { - return m_minidump_parser.GetArchitecture(); + return m_minidump_parser->GetArchitecture(); } llvm::Triple triple; @@ -292,13 +312,13 @@ Status ProcessMinidump::GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info) { - range_info = m_minidump_parser.GetMemoryRegionInfo(load_addr); + range_info = m_minidump_parser->GetMemoryRegionInfo(load_addr); return Status(); } Status ProcessMinidump::GetMemoryRegions( lldb_private::MemoryRegionInfos ®ion_list) { - region_list = m_minidump_parser.GetMemoryRegions(); + region_list = m_minidump_parser->GetMemoryRegions(); return Status(); } @@ -306,20 +326,20 @@ bool ProcessMinidump::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) { - for (const MinidumpThread& thread : m_thread_list) { - MinidumpLocationDescriptor context_location = thread.thread_context; + for (const minidump::Thread &thread : m_thread_list) { + LocationDescriptor context_location = thread.Context; // If the minidump contains an exception context, use it if (m_active_exception != nullptr && - m_active_exception->thread_id == thread.thread_id) { + m_active_exception->thread_id == thread.ThreadId) { context_location = m_active_exception->thread_context; } llvm::ArrayRef<uint8_t> context; if (!m_is_wow64) - context = m_minidump_parser.GetThreadContext(context_location); + context = m_minidump_parser->GetThreadContext(context_location); else - context = m_minidump_parser.GetThreadContextWow64(thread); + context = m_minidump_parser->GetThreadContextWow64(thread); lldb::ThreadSP thread_sp(new ThreadMinidump(*this, thread, context)); new_thread_list.AddThread(thread_sp); @@ -328,39 +348,60 @@ } void ProcessMinidump::ReadModuleList() { - std::vector<const MinidumpModule *> filtered_modules = - m_minidump_parser.GetFilteredModuleList(); + std::vector<const minidump::Module *> filtered_modules = + m_minidump_parser->GetFilteredModuleList(); + + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES)); for (auto module : filtered_modules) { - llvm::Optional<std::string> name = - m_minidump_parser.GetMinidumpString(module->module_name_rva); - - if (!name) - continue; - - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES)); - if (log) { - log->Printf("ProcessMinidump::%s found module: name: %s %#010" PRIx64 - "-%#010" PRIx64 " size: %" PRIu32, - __FUNCTION__, name.getValue().c_str(), - uint64_t(module->base_of_image), - module->base_of_image + module->size_of_image, - uint32_t(module->size_of_image)); - } + std::string name = cantFail(m_minidump_parser->GetMinidumpFile().getString( + module->ModuleNameRVA)); + LLDB_LOG(log, "found module: name: {0} {1:x10}-{2:x10} size: {3}", name, + module->BaseOfImage, module->BaseOfImage + module->SizeOfImage, + module->SizeOfImage); // check if the process is wow64 - a 32 bit windows process running on a // 64 bit windows - if (llvm::StringRef(name.getValue()).endswith_lower("wow64.dll")) { + if (llvm::StringRef(name).endswith_lower("wow64.dll")) { m_is_wow64 = true; } - const auto uuid = m_minidump_parser.GetModuleUUID(module); - auto file_spec = FileSpec(name.getValue(), GetArchitecture().GetTriple()); - FileSystem::Instance().Resolve(file_spec); + const auto uuid = m_minidump_parser->GetModuleUUID(module); + auto file_spec = FileSpec(name, GetArchitecture().GetTriple()); ModuleSpec module_spec(file_spec, uuid); + module_spec.GetArchitecture() = GetArchitecture(); Status error; - lldb::ModuleSP module_sp = GetTarget().GetSharedModule(module_spec, &error); - if (!module_sp || error.Fail()) { + // Try and find a module with a full UUID that matches. This function will + // add the module to the target if it finds one. + lldb::ModuleSP module_sp = GetTarget().GetOrCreateModule(module_spec, + true /* notify */, &error); + if (!module_sp) { + // Try and find a module without specifying the UUID and only looking for + // the file given a basename. We then will look for a partial UUID match + // if we find any matches. This function will add the module to the + // target if it finds one, so we need to remove the module from the target + // if the UUID doesn't match during our manual UUID verification. This + // allows the "target.exec-search-paths" setting to specify one or more + // directories that contain executables that can be searched for matches. + ModuleSpec basename_module_spec(module_spec); + basename_module_spec.GetUUID().Clear(); + basename_module_spec.GetFileSpec().GetDirectory().Clear(); + module_sp = GetTarget().GetOrCreateModule(basename_module_spec, + true /* notify */, &error); + if (module_sp) { + // We consider the module to be a match if the minidump UUID is a + // prefix of the actual UUID, or if either of the UUIDs are empty. + const auto dmp_bytes = uuid.GetBytes(); + const auto mod_bytes = module_sp->GetUUID().GetBytes(); + const bool match = dmp_bytes.empty() || mod_bytes.empty() || + mod_bytes.take_front(dmp_bytes.size()) == dmp_bytes; + if (!match) { + GetTarget().GetImages().Remove(module_sp); + module_sp.reset(); + } + } + } + if (!module_sp) { // We failed to locate a matching local object file. Fortunately, the // minidump format encodes enough information about each module's memory // range to allow us to create placeholder modules. @@ -368,26 +409,18 @@ // This enables most LLDB functionality involving address-to-module // translations (ex. identifing the module for a stack frame PC) and // modules/sections commands (ex. target modules list, ...) - if (log) { - log->Printf("Unable to locate the matching object file, creating a " - "placeholder module for: %s", - name.getValue().c_str()); - } + LLDB_LOG(log, + "Unable to locate the matching object file, creating a " + "placeholder module for: {0}", + name); - auto placeholder_module = - std::make_shared<PlaceholderModule>(module_spec); - placeholder_module->CreateImageSection(module, GetTarget()); - module_sp = placeholder_module; - GetTarget().GetImages().Append(module_sp); - } - - if (log) { - log->Printf("ProcessMinidump::%s load module: name: %s", __FUNCTION__, - name.getValue().c_str()); + module_sp = Module::CreateModuleFromObjectFile<PlaceholderObjectFile>( + module_spec, module->BaseOfImage, module->SizeOfImage); + GetTarget().GetImages().Append(module_sp, true /* notify */); } bool load_addr_changed = false; - module_sp->SetLoadAddress(GetTarget(), module->base_of_image, false, + module_sp->SetLoadAddress(GetTarget(), module->BaseOfImage, false, load_addr_changed); } } @@ -410,10 +443,10 @@ // try to set up symbolic breakpoints, which in turn may force loading more // debug information than needed. JITLoaderList &ProcessMinidump::GetJITLoaders() { - if (!m_jit_loaders_ap) { - m_jit_loaders_ap = llvm::make_unique<JITLoaderList>(); + if (!m_jit_loaders_up) { + m_jit_loaders_up = llvm::make_unique<JITLoaderList>(); } - return *m_jit_loaders_ap; + return *m_jit_loaders_up; } #define INIT_BOOL(VAR, LONG, SHORT, DESC) \ @@ -437,10 +470,23 @@ OptionGroupBoolean m_dump_linux_proc_uptime; OptionGroupBoolean m_dump_linux_proc_fd; OptionGroupBoolean m_dump_linux_all; + OptionGroupBoolean m_fb_app_data; + OptionGroupBoolean m_fb_build_id; + OptionGroupBoolean m_fb_version; + OptionGroupBoolean m_fb_java_stack; + OptionGroupBoolean m_fb_dalvik; + OptionGroupBoolean m_fb_unwind; + OptionGroupBoolean m_fb_error_log; + OptionGroupBoolean m_fb_app_state; + OptionGroupBoolean m_fb_abort; + OptionGroupBoolean m_fb_thread; + OptionGroupBoolean m_fb_logcat; + OptionGroupBoolean m_fb_all; void SetDefaultOptionsIfNoneAreSet() { if (m_dump_all.GetOptionValue().GetCurrentValue() || m_dump_linux_all.GetOptionValue().GetCurrentValue() || + m_fb_all.GetOptionValue().GetCurrentValue() || m_dump_directory.GetOptionValue().GetCurrentValue() || m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue() || m_dump_linux_proc_status.GetOptionValue().GetCurrentValue() || @@ -451,7 +497,18 @@ m_dump_linux_maps.GetOptionValue().GetCurrentValue() || m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue() || m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue() || - m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue()) + m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue() || + m_fb_app_data.GetOptionValue().GetCurrentValue() || + m_fb_build_id.GetOptionValue().GetCurrentValue() || + m_fb_version.GetOptionValue().GetCurrentValue() || + m_fb_java_stack.GetOptionValue().GetCurrentValue() || + m_fb_dalvik.GetOptionValue().GetCurrentValue() || + m_fb_unwind.GetOptionValue().GetCurrentValue() || + m_fb_error_log.GetOptionValue().GetCurrentValue() || + m_fb_app_state.GetOptionValue().GetCurrentValue() || + m_fb_abort.GetOptionValue().GetCurrentValue() || + m_fb_thread.GetOptionValue().GetCurrentValue() || + m_fb_logcat.GetOptionValue().GetCurrentValue()) return; // If no options were set, then dump everything m_dump_all.GetOptionValue().SetCurrentValue(true); @@ -506,11 +563,46 @@ return DumpLinux() || m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue(); } + bool DumpFacebook() const { + return DumpAll() || m_fb_all.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookAppData() const { + return DumpFacebook() || m_fb_app_data.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookBuildID() const { + return DumpFacebook() || m_fb_build_id.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookVersionName() const { + return DumpFacebook() || m_fb_version.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookJavaStack() const { + return DumpFacebook() || m_fb_java_stack.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookDalvikInfo() const { + return DumpFacebook() || m_fb_dalvik.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookUnwindSymbols() const { + return DumpFacebook() || m_fb_unwind.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookErrorLog() const { + return DumpFacebook() || m_fb_error_log.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookAppStateLog() const { + return DumpFacebook() || m_fb_app_state.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookAbortReason() const { + return DumpFacebook() || m_fb_abort.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookThreadName() const { + return DumpFacebook() || m_fb_thread.GetOptionValue().GetCurrentValue(); + } + bool DumpFacebookLogcat() const { + return DumpFacebook() || m_fb_logcat.GetOptionValue().GetCurrentValue(); + } public: - CommandObjectProcessMinidumpDump(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process plugin dump", - "Dump information from the minidump file.", NULL), + "Dump information from the minidump file.", nullptr), m_option_group(), INIT_BOOL(m_dump_all, "all", 'a', "Dump the everything in the minidump."), @@ -537,7 +629,30 @@ INIT_BOOL(m_dump_linux_proc_fd, "fd", 'f', "Dump linux /proc/<pid>/fd."), INIT_BOOL(m_dump_linux_all, "linux", 'l', - "Dump all linux streams.") { + "Dump all linux streams."), + INIT_BOOL(m_fb_app_data, "fb-app-data", 1, + "Dump Facebook application custom data."), + INIT_BOOL(m_fb_build_id, "fb-build-id", 2, + "Dump the Facebook build ID."), + INIT_BOOL(m_fb_version, "fb-version", 3, + "Dump Facebook application version string."), + INIT_BOOL(m_fb_java_stack, "fb-java-stack", 4, + "Dump Facebook java stack."), + INIT_BOOL(m_fb_dalvik, "fb-dalvik-info", 5, + "Dump Facebook Dalvik info."), + INIT_BOOL(m_fb_unwind, "fb-unwind-symbols", 6, + "Dump Facebook unwind symbols."), + INIT_BOOL(m_fb_error_log, "fb-error-log", 7, + "Dump Facebook error log."), + INIT_BOOL(m_fb_app_state, "fb-app-state-log", 8, + "Dump Facebook java stack."), + INIT_BOOL(m_fb_abort, "fb-abort-reason", 9, + "Dump Facebook abort reason."), + INIT_BOOL(m_fb_thread, "fb-thread-name", 10, + "Dump Facebook thread name."), + INIT_BOOL(m_fb_logcat, "fb-logcat", 11, + "Dump Facebook logcat."), + INIT_BOOL(m_fb_all, "facebook", 12, "Dump all Facebook streams.") { APPEND_OPT(m_dump_all); APPEND_OPT(m_dump_directory); APPEND_OPT(m_dump_linux_cpuinfo); @@ -551,10 +666,22 @@ APPEND_OPT(m_dump_linux_proc_uptime); APPEND_OPT(m_dump_linux_proc_fd); APPEND_OPT(m_dump_linux_all); + APPEND_OPT(m_fb_app_data); + APPEND_OPT(m_fb_build_id); + APPEND_OPT(m_fb_version); + APPEND_OPT(m_fb_java_stack); + APPEND_OPT(m_fb_dalvik); + APPEND_OPT(m_fb_unwind); + APPEND_OPT(m_fb_error_log); + APPEND_OPT(m_fb_app_state); + APPEND_OPT(m_fb_abort); + APPEND_OPT(m_fb_thread); + APPEND_OPT(m_fb_logcat); + APPEND_OPT(m_fb_all); m_option_group.Finalize(); } - ~CommandObjectProcessMinidumpDump() {} + ~CommandObjectProcessMinidumpDump() override {} Options *GetOptions() override { return &m_option_group; } @@ -572,31 +699,33 @@ m_interpreter.GetExecutionContext().GetProcessPtr()); result.SetStatus(eReturnStatusSuccessFinishResult); Stream &s = result.GetOutputStream(); - MinidumpParser &minidump = process->m_minidump_parser; + MinidumpParser &minidump = *process->m_minidump_parser; if (DumpDirectory()) { - s.Printf("RVA SIZE TYPE MinidumpStreamType\n"); + s.Printf("RVA SIZE TYPE StreamType\n"); s.Printf("---------- ---------- ---------- --------------------------\n"); - for (const auto &pair: minidump.GetDirectoryMap()) - s.Printf("0x%8.8x 0x%8.8x 0x%8.8x %s\n", (uint32_t)pair.second.rva, - (uint32_t)pair.second.data_size, pair.first, - MinidumpParser::GetStreamTypeAsString(pair.first).data()); + for (const auto &stream_desc : minidump.GetMinidumpFile().streams()) + s.Printf( + "0x%8.8x 0x%8.8x 0x%8.8x %s\n", (uint32_t)stream_desc.Location.RVA, + (uint32_t)stream_desc.Location.DataSize, + (unsigned)(StreamType)stream_desc.Type, + MinidumpParser::GetStreamTypeAsString(stream_desc.Type).data()); s.Printf("\n"); } - auto DumpTextStream = [&](MinidumpStreamType stream_type, + auto DumpTextStream = [&](StreamType stream_type, llvm::StringRef label) -> void { auto bytes = minidump.GetStream(stream_type); if (!bytes.empty()) { if (label.empty()) - label = MinidumpParser::GetStreamTypeAsString((uint32_t)stream_type); + label = MinidumpParser::GetStreamTypeAsString(stream_type); s.Printf("%s:\n%s\n\n", label.data(), bytes.data()); } }; - auto DumpBinaryStream = [&](MinidumpStreamType stream_type, + auto DumpBinaryStream = [&](StreamType stream_type, llvm::StringRef label) -> void { auto bytes = minidump.GetStream(stream_type); if (!bytes.empty()) { if (label.empty()) - label = MinidumpParser::GetStreamTypeAsString((uint32_t)stream_type); + label = MinidumpParser::GetStreamTypeAsString(stream_type); s.Printf("%s:\n", label.data()); DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle, process->GetAddressByteSize()); @@ -607,25 +736,67 @@ }; if (DumpLinuxCPUInfo()) - DumpTextStream(MinidumpStreamType::LinuxCPUInfo, "/proc/cpuinfo"); + DumpTextStream(StreamType::LinuxCPUInfo, "/proc/cpuinfo"); if (DumpLinuxProcStatus()) - DumpTextStream(MinidumpStreamType::LinuxProcStatus, "/proc/PID/status"); + DumpTextStream(StreamType::LinuxProcStatus, "/proc/PID/status"); if (DumpLinuxLSBRelease()) - DumpTextStream(MinidumpStreamType::LinuxLSBRelease, "/etc/lsb-release"); + DumpTextStream(StreamType::LinuxLSBRelease, "/etc/lsb-release"); if (DumpLinuxCMDLine()) - DumpTextStream(MinidumpStreamType::LinuxCMDLine, "/proc/PID/cmdline"); + DumpTextStream(StreamType::LinuxCMDLine, "/proc/PID/cmdline"); if (DumpLinuxEnviron()) - DumpTextStream(MinidumpStreamType::LinuxEnviron, "/proc/PID/environ"); + DumpTextStream(StreamType::LinuxEnviron, "/proc/PID/environ"); if (DumpLinuxAuxv()) - DumpBinaryStream(MinidumpStreamType::LinuxAuxv, "/proc/PID/auxv"); + DumpBinaryStream(StreamType::LinuxAuxv, "/proc/PID/auxv"); if (DumpLinuxMaps()) - DumpTextStream(MinidumpStreamType::LinuxMaps, "/proc/PID/maps"); + DumpTextStream(StreamType::LinuxMaps, "/proc/PID/maps"); if (DumpLinuxProcStat()) - DumpTextStream(MinidumpStreamType::LinuxProcStat, "/proc/PID/stat"); + DumpTextStream(StreamType::LinuxProcStat, "/proc/PID/stat"); if (DumpLinuxProcUptime()) - DumpTextStream(MinidumpStreamType::LinuxProcUptime, "uptime"); + DumpTextStream(StreamType::LinuxProcUptime, "uptime"); if (DumpLinuxProcFD()) - DumpTextStream(MinidumpStreamType::LinuxProcFD, "/proc/PID/fd"); + DumpTextStream(StreamType::LinuxProcFD, "/proc/PID/fd"); + if (DumpFacebookAppData()) + DumpTextStream(StreamType::FacebookAppCustomData, + "Facebook App Data"); + if (DumpFacebookBuildID()) { + auto bytes = minidump.GetStream(StreamType::FacebookBuildID); + if (bytes.size() >= 4) { + DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle, + process->GetAddressByteSize()); + lldb::offset_t offset = 0; + uint32_t build_id = data.GetU32(&offset); + s.Printf("Facebook Build ID:\n"); + s.Printf("%u\n", build_id); + s.Printf("\n"); + } + } + if (DumpFacebookVersionName()) + DumpTextStream(StreamType::FacebookAppVersionName, + "Facebook Version String"); + if (DumpFacebookJavaStack()) + DumpTextStream(StreamType::FacebookJavaStack, + "Facebook Java Stack"); + if (DumpFacebookDalvikInfo()) + DumpTextStream(StreamType::FacebookDalvikInfo, + "Facebook Dalvik Info"); + if (DumpFacebookUnwindSymbols()) + DumpBinaryStream(StreamType::FacebookUnwindSymbols, + "Facebook Unwind Symbols Bytes"); + if (DumpFacebookErrorLog()) + DumpTextStream(StreamType::FacebookDumpErrorLog, + "Facebook Error Log"); + if (DumpFacebookAppStateLog()) + DumpTextStream(StreamType::FacebookAppStateLog, + "Faceook Application State Log"); + if (DumpFacebookAbortReason()) + DumpTextStream(StreamType::FacebookAbortReason, + "Facebook Abort Reason"); + if (DumpFacebookThreadName()) + DumpTextStream(StreamType::FacebookThreadName, + "Facebook Thread Name"); + if (DumpFacebookLogcat()) + DumpTextStream(StreamType::FacebookLogcat, + "Facebook Logcat"); return true; } }; @@ -640,12 +811,12 @@ CommandObjectSP(new CommandObjectProcessMinidumpDump(interpreter))); } - ~CommandObjectMultiwordProcessMinidump() {} + ~CommandObjectMultiwordProcessMinidump() override {} }; CommandObject *ProcessMinidump::GetPluginCommandObject() { if (!m_command_sp) - m_command_sp.reset(new CommandObjectMultiwordProcessMinidump( - GetTarget().GetDebugger().GetCommandInterpreter())); + m_command_sp = std::make_shared<CommandObjectMultiwordProcessMinidump>( + GetTarget().GetDebugger().GetCommandInterpreter()); return m_command_sp.get(); }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.h index 30347b7..c39040f 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/ProcessMinidump.h
@@ -1,9 +1,8 @@ //===-- ProcessMinidump.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -42,7 +41,7 @@ static const char *GetPluginDescriptionStatic(); ProcessMinidump(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, - const FileSpec &core_file, MinidumpParser minidump_parser); + const FileSpec &core_file, lldb::DataBufferSP code_data); ~ProcessMinidump() override; @@ -93,7 +92,7 @@ return error; } - MinidumpParser m_minidump_parser; + llvm::Optional<MinidumpParser> m_minidump_parser; protected: void Clear(); @@ -107,7 +106,8 @@ private: FileSpec m_core_file; - llvm::ArrayRef<MinidumpThread> m_thread_list; + lldb::DataBufferSP m_core_data; + llvm::ArrayRef<minidump::Thread> m_thread_list; const MinidumpExceptionStream *m_active_exception; lldb::CommandObjectSP m_command_sp; bool m_is_wow64;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.cpp index 93c3ba7..f2e4560 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_ARM.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,33 +29,35 @@ #define DEF_R(i) \ { \ "r" #i, nullptr, 4, OFFSET(r) + i * 4, eEncodingUint, eFormatHex, \ - {INV, dwarf_r##i, INV, INV, reg_r##i}, nullptr, nullptr, nullptr, 0 \ + {dwarf_r##i, dwarf_r##i, INV, INV, reg_r##i}, \ + nullptr, nullptr, nullptr, 0 \ } #define DEF_R_ARG(i, n) \ { \ "r" #i, "arg" #n, 4, OFFSET(r) + i * 4, eEncodingUint, eFormatHex, \ - {INV, dwarf_r##i, LLDB_REGNUM_GENERIC_ARG1 + i, INV, reg_r##i}, \ + {dwarf_r##i, dwarf_r##i, LLDB_REGNUM_GENERIC_ARG1 + i, INV, reg_r##i}, \ nullptr, nullptr, nullptr, 0 \ } #define DEF_D(i) \ { \ "d" #i, nullptr, 8, OFFSET(d) + i * 8, eEncodingVector, \ - eFormatVectorOfUInt8, {INV, dwarf_d##i, INV, INV, reg_d##i}, \ + eFormatVectorOfUInt8, {dwarf_d##i, dwarf_d##i, INV, INV, reg_d##i}, \ nullptr, nullptr, nullptr, 0 \ } #define DEF_S(i) \ { \ "s" #i, nullptr, 4, OFFSET(s) + i * 4, eEncodingIEEE754, eFormatFloat, \ - {INV, dwarf_s##i, INV, INV, reg_s##i}, nullptr, nullptr, nullptr, 0 \ + {dwarf_s##i, dwarf_s##i, INV, INV, reg_s##i}, \ + nullptr, nullptr, nullptr, 0 \ } #define DEF_Q(i) \ { \ "q" #i, nullptr, 16, OFFSET(q) + i * 16, eEncodingVector, \ - eFormatVectorOfUInt8, {INV, dwarf_q##i, INV, INV, reg_q##i}, \ + eFormatVectorOfUInt8, {dwarf_q##i, dwarf_q##i, INV, INV, reg_q##i}, \ nullptr, nullptr, nullptr, 0 \ } @@ -462,7 +463,7 @@ constexpr size_t k_num_reg_sets = llvm::array_lengthof(g_reg_sets); RegisterContextMinidump_ARM::RegisterContextMinidump_ARM( - Thread &thread, const DataExtractor &data, bool apple) + lldb_private::Thread &thread, const DataExtractor &data, bool apple) : RegisterContext(thread, 0), m_apple(apple) { lldb::offset_t offset = 0; m_regs.context_flags = data.GetU32(&offset);
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.h index 959611a..eff8cdf 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_ARM.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.cpp index 3582e7d..bbd0e14 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_ARM64.cpp -----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,8 +28,8 @@ #define DEF_X(i) \ { \ "x" #i, nullptr, 8, OFFSET(x) + i * 8, eEncodingUint, eFormatHex, \ - {INV, arm64_dwarf::x##i, INV, INV, reg_x##i}, nullptr, nullptr, \ - nullptr, 0 \ + {arm64_dwarf::x##i, arm64_dwarf::x##i, INV, INV, reg_x##i}, \ + nullptr, nullptr, nullptr, 0 \ } #define DEF_W(i) \ @@ -42,15 +41,15 @@ #define DEF_X_ARG(i, n) \ { \ "x" #i, "arg" #n, 8, OFFSET(x) + i * 8, eEncodingUint, eFormatHex, \ - {INV, arm64_dwarf::x##i, LLDB_REGNUM_GENERIC_ARG1 + i, INV, reg_x##i}, \ - nullptr, nullptr, nullptr, 0 \ + {arm64_dwarf::x##i, arm64_dwarf::x##i, LLDB_REGNUM_GENERIC_ARG1 + i, \ + INV, reg_x##i}, nullptr, nullptr, nullptr, 0 \ } #define DEF_V(i) \ { \ "v" #i, nullptr, 16, OFFSET(v) + i * 16, eEncodingVector, \ - eFormatVectorOfUInt8, {INV, arm64_dwarf::v##i, INV, INV, reg_v##i}, \ - nullptr, nullptr, nullptr, 0 \ + eFormatVectorOfUInt8, {arm64_dwarf::v##i, arm64_dwarf::v##i, INV, INV, \ + reg_v##i}, nullptr, nullptr, nullptr, 0 \ } #define DEF_D(i) \ @@ -314,7 +313,7 @@ OFFSET(x) + 29 * 8, eEncodingUint, eFormatHex, - {INV, arm64_dwarf::x29, LLDB_REGNUM_GENERIC_FP, INV, reg_fp}, + {arm64_dwarf::x29, arm64_dwarf::x29, LLDB_REGNUM_GENERIC_FP, INV, reg_fp}, nullptr, nullptr, nullptr, @@ -325,7 +324,7 @@ OFFSET(x) + 30 * 8, eEncodingUint, eFormatHex, - {INV, arm64_dwarf::x30, LLDB_REGNUM_GENERIC_RA, INV, reg_lr}, + {arm64_dwarf::x30, arm64_dwarf::x30, LLDB_REGNUM_GENERIC_RA, INV, reg_lr}, nullptr, nullptr, nullptr, @@ -336,7 +335,7 @@ OFFSET(x) + 31 * 8, eEncodingUint, eFormatHex, - {INV, arm64_dwarf::x31, LLDB_REGNUM_GENERIC_SP, INV, reg_sp}, + {arm64_dwarf::x31, arm64_dwarf::x31, LLDB_REGNUM_GENERIC_SP, INV, reg_sp}, nullptr, nullptr, nullptr, @@ -347,7 +346,7 @@ OFFSET(pc), eEncodingUint, eFormatHex, - {INV, arm64_dwarf::pc, LLDB_REGNUM_GENERIC_PC, INV, reg_pc}, + {arm64_dwarf::pc, arm64_dwarf::pc, LLDB_REGNUM_GENERIC_PC, INV, reg_pc}, nullptr, nullptr, nullptr, @@ -770,7 +769,7 @@ constexpr size_t k_num_reg_sets = llvm::array_lengthof(g_reg_sets); RegisterContextMinidump_ARM64::RegisterContextMinidump_ARM64( - Thread &thread, const DataExtractor &data) + lldb_private::Thread &thread, const DataExtractor &data) : RegisterContext(thread, 0) { lldb::offset_t offset = 0; m_regs.context_flags = data.GetU64(&offset); @@ -783,7 +782,7 @@ auto regs_data = data.GetData(&offset, sizeof(m_regs.v)); if (regs_data) memcpy(m_regs.v, regs_data, sizeof(m_regs.v)); - assert(k_num_regs == k_num_reg_infos); + static_assert(k_num_regs == k_num_reg_infos, ""); } size_t RegisterContextMinidump_ARM64::GetRegisterCount() { return k_num_regs; }
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.h index ee47b15..f9e7f39 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_ARM64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_ARM64.h -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.cpp index 1fdbb5e..8ac2abb 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_x86_32.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.h index 38c2ffc..d787f78 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_32.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_x86_32.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.cpp index eaa155d..515ccf6 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_x86_64.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.h index 30ce906..34ddd47 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/RegisterContextMinidump_x86_64.h
@@ -1,9 +1,8 @@ //===-- RegisterContextMinidump_x86_64.h ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.cpp b/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.cpp index f4c1365..5262de5 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.cpp +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.cpp
@@ -1,13 +1,13 @@ //===-- ThreadMinidump.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "ThreadMinidump.h" + #include "ProcessMinidump.h" #include "RegisterContextMinidump_ARM.h" @@ -27,14 +27,15 @@ #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Log.h" +#include <memory> using namespace lldb; using namespace lldb_private; using namespace minidump; -ThreadMinidump::ThreadMinidump(Process &process, const MinidumpThread &td, +ThreadMinidump::ThreadMinidump(Process &process, const minidump::Thread &td, llvm::ArrayRef<uint8_t> gpregset_data) - : Thread(process, td.thread_id), m_thread_reg_ctx_sp(), + : Thread(process, td.ThreadId), m_thread_reg_ctx_sp(), m_gpregset_data(gpregset_data) {} ThreadMinidump::~ThreadMinidump() {} @@ -72,8 +73,9 @@ lldb::DataBufferSP buf = ConvertMinidumpContext_x86_32(m_gpregset_data, reg_interface); DataExtractor gpregset(buf, lldb::eByteOrderLittle, 4); - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_x86_64( - *this, reg_interface, gpregset, {})); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_x86_64>( + *this, reg_interface, gpregset, + llvm::ArrayRef<lldb_private::CoreNote>()); break; } case llvm::Triple::x86_64: { @@ -81,22 +83,24 @@ lldb::DataBufferSP buf = ConvertMinidumpContext_x86_64(m_gpregset_data, reg_interface); DataExtractor gpregset(buf, lldb::eByteOrderLittle, 8); - m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_x86_64( - *this, reg_interface, gpregset, {})); + m_thread_reg_ctx_sp = std::make_shared<RegisterContextCorePOSIX_x86_64>( + *this, reg_interface, gpregset, + llvm::ArrayRef<lldb_private::CoreNote>()); break; } case llvm::Triple::aarch64: { DataExtractor data(m_gpregset_data.data(), m_gpregset_data.size(), lldb::eByteOrderLittle, 8); - m_thread_reg_ctx_sp.reset(new RegisterContextMinidump_ARM64(*this, data)); + m_thread_reg_ctx_sp = + std::make_shared<RegisterContextMinidump_ARM64>(*this, data); break; } case llvm::Triple::arm: { DataExtractor data(m_gpregset_data.data(), m_gpregset_data.size(), lldb::eByteOrderLittle, 8); const bool apple = arch.GetTriple().getVendor() == llvm::Triple::Apple; - m_thread_reg_ctx_sp.reset( - new RegisterContextMinidump_ARM(*this, data, apple)); + m_thread_reg_ctx_sp = + std::make_shared<RegisterContextMinidump_ARM>(*this, data, apple); break; } default: @@ -104,8 +108,8 @@ } reg_ctx_sp = m_thread_reg_ctx_sp; - } else if (m_unwinder_ap) { - reg_ctx_sp = m_unwinder_ap->CreateRegisterContextForFrame(frame); + } else if (m_unwinder_up) { + reg_ctx_sp = m_unwinder_up->CreateRegisterContextForFrame(frame); } return reg_ctx_sp;
diff --git a/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.h b/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.h index 45364fa..44c41bc 100644 --- a/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.h +++ b/src/llvm-project/lldb/source/Plugins/Process/minidump/ThreadMinidump.h
@@ -1,9 +1,8 @@ //===-- ThreadMinidump.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,7 +20,7 @@ class ThreadMinidump : public Thread { public: - ThreadMinidump(Process &process, const MinidumpThread &td, + ThreadMinidump(Process &process, const minidump::Thread &td, llvm::ArrayRef<uint8_t> gpregset_data); ~ThreadMinidump() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.cpp b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.cpp index 4bd4c6a..7b95983 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.cpp +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.cpp
@@ -1,9 +1,8 @@ //===-- ScriptInterpreterNone.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,7 +10,6 @@ #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StringList.h" @@ -22,21 +20,21 @@ using namespace lldb; using namespace lldb_private; -ScriptInterpreterNone::ScriptInterpreterNone(CommandInterpreter &interpreter) - : ScriptInterpreter(interpreter, eScriptLanguageNone) {} +ScriptInterpreterNone::ScriptInterpreterNone(Debugger &debugger) + : ScriptInterpreter(debugger, eScriptLanguageNone) {} ScriptInterpreterNone::~ScriptInterpreterNone() {} bool ScriptInterpreterNone::ExecuteOneLine(llvm::StringRef command, CommandReturnObject *, const ExecuteScriptOptions &) { - m_interpreter.GetDebugger().GetErrorFile()->PutCString( + m_debugger.GetErrorFile()->PutCString( "error: there is no embedded script interpreter in this mode.\n"); return false; } void ScriptInterpreterNone::ExecuteInterpreterLoop() { - m_interpreter.GetDebugger().GetErrorFile()->PutCString( + m_debugger.GetErrorFile()->PutCString( "error: there is no embedded script interpreter in this mode.\n"); } @@ -53,8 +51,8 @@ void ScriptInterpreterNone::Terminate() {} lldb::ScriptInterpreterSP -ScriptInterpreterNone::CreateInstance(CommandInterpreter &interpreter) { - return std::make_shared<ScriptInterpreterNone>(interpreter); +ScriptInterpreterNone::CreateInstance(Debugger &debugger) { + return std::make_shared<ScriptInterpreterNone>(debugger); } lldb_private::ConstString ScriptInterpreterNone::GetPluginNameStatic() {
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.h b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.h index 8937d98..242065c 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.h +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/None/ScriptInterpreterNone.h
@@ -1,9 +1,8 @@ //===-- ScriptInterpreterNone.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,7 +15,7 @@ class ScriptInterpreterNone : public ScriptInterpreter { public: - ScriptInterpreterNone(CommandInterpreter &interpreter); + ScriptInterpreterNone(Debugger &debugger); ~ScriptInterpreterNone() override; @@ -26,23 +25,18 @@ void ExecuteInterpreterLoop() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); - static lldb::ScriptInterpreterSP - CreateInstance(CommandInterpreter &interpreter); + static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger); static lldb_private::ConstString GetPluginNameStatic(); static const char *GetPluginDescriptionStatic(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt index 56eacc9..f7360d7 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt
@@ -23,6 +23,8 @@ lldbHost lldbInterpreter lldbTarget + ${PYTHON_LIBRARY} + LINK_COMPONENTS Support )
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp index 7e96dd9..29dd037 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp
@@ -1,9 +1,8 @@ //===-- PythonDataObjects.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,12 +20,12 @@ #include "lldb/Interpreter/ScriptInterpreter.h" #include "lldb/Utility/Stream.h" +#include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ConvertUTF.h" +#include "llvm/Support/Errno.h" #include <stdio.h> -#include "llvm/ADT/StringSwitch.h" - using namespace lldb_private; using namespace lldb; @@ -34,13 +33,11 @@ s << "Python Obj: 0x" << GetValue(); } -//---------------------------------------------------------------------- // PythonObject -//---------------------------------------------------------------------- void PythonObject::Dump(Stream &strm) const { if (m_py_obj) { - FILE *file = ::tmpfile(); + FILE *file = llvm::sys::RetryAfterSignal(nullptr, ::tmpfile); if (file) { ::PyObject_Print(m_py_obj, file, 0); const long length = ftell(file); @@ -78,6 +75,8 @@ #endif if (PythonByteArray::Check(m_py_obj)) return PyObjectType::ByteArray; + if (PythonBoolean::Check(m_py_obj)) + return PyObjectType::Boolean; if (PythonInteger::Check(m_py_obj)) return PyObjectType::Integer; if (PythonFile::Check(m_py_obj)) @@ -108,7 +107,7 @@ PythonObject PythonObject::ResolveNameWithDictionary(llvm::StringRef name, const PythonDictionary &dict) { - size_t dot_pos = name.find_first_of('.'); + size_t dot_pos = name.find('.'); llvm::StringRef piece = name.substr(0, dot_pos); PythonObject result = dict.GetItemForKey(PythonString(piece)); if (dot_pos == llvm::StringRef::npos) { @@ -132,7 +131,7 @@ // refers to the `sys` module, and `name` == "path.append", then it will find // the function `sys.path.append`. - size_t dot_pos = name.find_first_of('.'); + size_t dot_pos = name.find('.'); if (dot_pos == llvm::StringRef::npos) { // No dots in the name, we should be able to find the value immediately as // an attribute of `m_py_obj`. @@ -179,6 +178,9 @@ case PyObjectType::Dictionary: return PythonDictionary(PyRefType::Borrowed, m_py_obj) .CreateStructuredDictionary(); + case PyObjectType::Boolean: + return PythonBoolean(PyRefType::Borrowed, m_py_obj) + .CreateStructuredBoolean(); case PyObjectType::Integer: return PythonInteger(PyRefType::Borrowed, m_py_obj) .CreateStructuredInteger(); @@ -198,9 +200,7 @@ } } -//---------------------------------------------------------------------- // PythonString -//---------------------------------------------------------------------- PythonBytes::PythonBytes() : PythonObject() {} PythonBytes::PythonBytes(llvm::ArrayRef<uint8_t> bytes) : PythonObject() { @@ -215,8 +215,6 @@ Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a string } -PythonBytes::PythonBytes(const PythonBytes &object) : PythonObject(object) {} - PythonBytes::~PythonBytes() {} bool PythonBytes::Check(PyObject *py_obj) { @@ -334,16 +332,12 @@ return result; } -//---------------------------------------------------------------------- // PythonString -//---------------------------------------------------------------------- PythonString::PythonString(PyRefType type, PyObject *py_obj) : PythonObject() { Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a string } -PythonString::PythonString(const PythonString &object) : PythonObject(object) {} - PythonString::PythonString(llvm::StringRef string) : PythonObject() { SetString(string); } @@ -434,9 +428,7 @@ return result; } -//---------------------------------------------------------------------- // PythonInteger -//---------------------------------------------------------------------- PythonInteger::PythonInteger() : PythonObject() {} @@ -445,9 +437,6 @@ Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a integer type } -PythonInteger::PythonInteger(const PythonInteger &object) - : PythonObject(object) {} - PythonInteger::PythonInteger(int64_t value) : PythonObject() { SetInteger(value); } @@ -526,9 +515,51 @@ return result; } -//---------------------------------------------------------------------- +// PythonBoolean + +PythonBoolean::PythonBoolean(PyRefType type, PyObject *py_obj) + : PythonObject() { + Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a boolean type +} + +PythonBoolean::PythonBoolean(bool value) { + SetValue(value); +} + +bool PythonBoolean::Check(PyObject *py_obj) { + return py_obj ? PyBool_Check(py_obj) : false; +} + +void PythonBoolean::Reset(PyRefType type, PyObject *py_obj) { + // Grab the desired reference type so that if we end up rejecting `py_obj` it + // still gets decremented if necessary. + PythonObject result(type, py_obj); + + if (!PythonBoolean::Check(py_obj)) { + PythonObject::Reset(); + return; + } + + // Calling PythonObject::Reset(const PythonObject&) will lead to stack + // overflow since it calls back into the virtual implementation. + PythonObject::Reset(PyRefType::Borrowed, result.get()); +} + +bool PythonBoolean::GetValue() const { + return m_py_obj ? PyObject_IsTrue(m_py_obj) : false; +} + +void PythonBoolean::SetValue(bool value) { + PythonObject::Reset(PyRefType::Owned, PyBool_FromLong(value)); +} + +StructuredData::BooleanSP PythonBoolean::CreateStructuredBoolean() const { + StructuredData::BooleanSP result(new StructuredData::Boolean); + result->SetValue(GetValue()); + return result; +} + // PythonList -//---------------------------------------------------------------------- PythonList::PythonList(PyInitialValue value) : PythonObject() { if (value == PyInitialValue::Empty) @@ -543,8 +574,6 @@ Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a list } -PythonList::PythonList(const PythonList &list) : PythonObject(list) {} - PythonList::~PythonList() {} bool PythonList::Check(PyObject *py_obj) { @@ -607,9 +636,7 @@ return result; } -//---------------------------------------------------------------------- // PythonTuple -//---------------------------------------------------------------------- PythonTuple::PythonTuple(PyInitialValue value) : PythonObject() { if (value == PyInitialValue::Empty) @@ -624,8 +651,6 @@ Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a tuple } -PythonTuple::PythonTuple(const PythonTuple &tuple) : PythonObject(tuple) {} - PythonTuple::PythonTuple(std::initializer_list<PythonObject> objects) { m_py_obj = PyTuple_New(objects.size()); @@ -703,9 +728,7 @@ return result; } -//---------------------------------------------------------------------- // PythonDictionary -//---------------------------------------------------------------------- PythonDictionary::PythonDictionary(PyInitialValue value) : PythonObject() { if (value == PyInitialValue::Empty) @@ -717,9 +740,6 @@ Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a dictionary } -PythonDictionary::PythonDictionary(const PythonDictionary &object) - : PythonObject(object) {} - PythonDictionary::~PythonDictionary() {} bool PythonDictionary::Check(PyObject *py_obj) { @@ -789,8 +809,6 @@ Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a module } -PythonModule::PythonModule(const PythonModule &dict) : PythonObject(dict) {} - PythonModule::~PythonModule() {} PythonModule PythonModule::BuiltinsModule() { @@ -845,9 +863,6 @@ Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a callable } -PythonCallable::PythonCallable(const PythonCallable &callable) - : PythonObject(callable) {} - PythonCallable::~PythonCallable() {} bool PythonCallable::Check(PyObject *py_obj) {
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h index 7cd98df..049ce90 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h
@@ -1,9 +1,8 @@ //===-- PythonDataObjects.h--------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,13 +14,8 @@ // LLDB Python header must be included first #include "lldb-python.h" -#include "lldb/Utility/Flags.h" - #include "lldb/Host/File.h" -#include "lldb/Interpreter/OptionValue.h" -#include "lldb/Utility/ConstString.h" #include "lldb/Utility/StructuredData.h" -#include "lldb/lldb-defines.h" #include "llvm/ADT/ArrayRef.h" @@ -58,6 +52,7 @@ enum class PyObjectType { Unknown, None, + Boolean, Integer, Dictionary, List, @@ -203,7 +198,6 @@ explicit PythonBytes(llvm::ArrayRef<uint8_t> bytes); PythonBytes(const uint8_t *bytes, size_t length); PythonBytes(PyRefType type, PyObject *o); - PythonBytes(const PythonBytes &object); ~PythonBytes() override; @@ -255,7 +249,6 @@ explicit PythonString(llvm::StringRef string); explicit PythonString(const char *string); PythonString(PyRefType type, PyObject *o); - PythonString(const PythonString &object); ~PythonString() override; @@ -280,7 +273,6 @@ PythonInteger(); explicit PythonInteger(int64_t value); PythonInteger(PyRefType type, PyObject *o); - PythonInteger(const PythonInteger &object); ~PythonInteger() override; @@ -298,13 +290,34 @@ StructuredData::IntegerSP CreateStructuredInteger() const; }; +class PythonBoolean : public PythonObject { +public: + PythonBoolean() = default; + explicit PythonBoolean(bool value); + PythonBoolean(PyRefType type, PyObject *o); + + ~PythonBoolean() override = default; + + static bool Check(PyObject *py_obj); + + // Bring in the no-argument base class version + using PythonObject::Reset; + + void Reset(PyRefType type, PyObject *py_obj) override; + + bool GetValue() const; + + void SetValue(bool value); + + StructuredData::BooleanSP CreateStructuredBoolean() const; +}; + class PythonList : public PythonObject { public: PythonList() {} explicit PythonList(PyInitialValue value); explicit PythonList(int list_size); PythonList(PyRefType type, PyObject *o); - PythonList(const PythonList &list); ~PythonList() override; @@ -332,7 +345,6 @@ explicit PythonTuple(PyInitialValue value); explicit PythonTuple(int tuple_size); PythonTuple(PyRefType type, PyObject *o); - PythonTuple(const PythonTuple &tuple); PythonTuple(std::initializer_list<PythonObject> objects); PythonTuple(std::initializer_list<PyObject *> objects); @@ -359,7 +371,6 @@ PythonDictionary() {} explicit PythonDictionary(PyInitialValue value); PythonDictionary(PyRefType type, PyObject *o); - PythonDictionary(const PythonDictionary &dict); ~PythonDictionary() override; @@ -384,7 +395,6 @@ public: PythonModule(); PythonModule(PyRefType type, PyObject *o); - PythonModule(const PythonModule &dict); ~PythonModule() override; @@ -417,7 +427,6 @@ PythonCallable(); PythonCallable(PyRefType type, PyObject *o); - PythonCallable(const PythonCallable &dict); ~PythonCallable() override;
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.cpp b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.cpp index d28a803..c9d834c 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.cpp +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.cpp
@@ -1,9 +1,8 @@ //===-- PythonExceptionState.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.h b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.h index 20f4b4c..3a88aa0 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.h +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonExceptionState.h
@@ -1,9 +1,8 @@ //===-- PythonExceptionState.h ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp index 41cb443..2d2b68c 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp
@@ -1,9 +1,8 @@ //===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,17 +17,10 @@ #include "PythonDataObjects.h" #include "PythonExceptionState.h" -#include "ScriptInterpreterPython.h" +#include "ScriptInterpreterPythonImpl.h" -#include <stdio.h> -#include <stdlib.h> - -#include <mutex> -#include <string> - -#include "lldb/API/SBValue.h" #include "lldb/API/SBFrame.h" -#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/API/SBValue.h" #include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Breakpoint/WatchpointOptions.h" #include "lldb/Core/Communication.h" @@ -54,68 +46,146 @@ #include "llvm/ADT/StringRef.h" #include "llvm/Support/FileSystem.h" +#include <memory> +#include <mutex> +#include <stdio.h> +#include <stdlib.h> +#include <string> + using namespace lldb; using namespace lldb_private; -static ScriptInterpreterPython::SWIGInitCallback g_swig_init_callback = nullptr; -static ScriptInterpreterPython::SWIGBreakpointCallbackFunction - g_swig_breakpoint_callback = nullptr; -static ScriptInterpreterPython::SWIGWatchpointCallbackFunction - g_swig_watchpoint_callback = nullptr; -static ScriptInterpreterPython::SWIGPythonTypeScriptCallbackFunction - g_swig_typescript_callback = nullptr; -static ScriptInterpreterPython::SWIGPythonCreateSyntheticProvider - g_swig_synthetic_script = nullptr; -static ScriptInterpreterPython::SWIGPythonCreateCommandObject - g_swig_create_cmd = nullptr; -static ScriptInterpreterPython::SWIGPythonCalculateNumChildren - g_swig_calc_children = nullptr; -static ScriptInterpreterPython::SWIGPythonGetChildAtIndex - g_swig_get_child_index = nullptr; -static ScriptInterpreterPython::SWIGPythonGetIndexOfChildWithName - g_swig_get_index_child = nullptr; -static ScriptInterpreterPython::SWIGPythonCastPyObjectToSBValue - g_swig_cast_to_sbvalue = nullptr; -static ScriptInterpreterPython::SWIGPythonGetValueObjectSPFromSBValue - g_swig_get_valobj_sp_from_sbvalue = nullptr; -static ScriptInterpreterPython::SWIGPythonUpdateSynthProviderInstance - g_swig_update_provider = nullptr; -static ScriptInterpreterPython::SWIGPythonMightHaveChildrenSynthProviderInstance - g_swig_mighthavechildren_provider = nullptr; -static ScriptInterpreterPython::SWIGPythonGetValueSynthProviderInstance - g_swig_getvalue_provider = nullptr; -static ScriptInterpreterPython::SWIGPythonCallCommand g_swig_call_command = - nullptr; -static ScriptInterpreterPython::SWIGPythonCallCommandObject - g_swig_call_command_object = nullptr; -static ScriptInterpreterPython::SWIGPythonCallModuleInit - g_swig_call_module_init = nullptr; -static ScriptInterpreterPython::SWIGPythonCreateOSPlugin - g_swig_create_os_plugin = nullptr; -static ScriptInterpreterPython::SWIGPythonCreateFrameRecognizer - g_swig_create_frame_recognizer = nullptr; -static ScriptInterpreterPython::SWIGPythonGetRecognizedArguments - g_swig_get_recognized_arguments = nullptr; -static ScriptInterpreterPython::SWIGPythonScriptKeyword_Process - g_swig_run_script_keyword_process = nullptr; -static ScriptInterpreterPython::SWIGPythonScriptKeyword_Thread - g_swig_run_script_keyword_thread = nullptr; -static ScriptInterpreterPython::SWIGPythonScriptKeyword_Target - g_swig_run_script_keyword_target = nullptr; -static ScriptInterpreterPython::SWIGPythonScriptKeyword_Frame - g_swig_run_script_keyword_frame = nullptr; -static ScriptInterpreterPython::SWIGPythonScriptKeyword_Value - g_swig_run_script_keyword_value = nullptr; -static ScriptInterpreterPython::SWIGPython_GetDynamicSetting g_swig_plugin_get = - nullptr; -static ScriptInterpreterPython::SWIGPythonCreateScriptedThreadPlan - g_swig_thread_plan_script = nullptr; -static ScriptInterpreterPython::SWIGPythonCallThreadPlan - g_swig_call_thread_plan = nullptr; -static ScriptInterpreterPython::SWIGPythonCreateScriptedBreakpointResolver - g_swig_bkpt_resolver_script = nullptr; -static ScriptInterpreterPython::SWIGPythonCallBreakpointResolver - g_swig_call_bkpt_resolver = nullptr; +// Defined in the SWIG source file +#if PY_MAJOR_VERSION >= 3 +extern "C" PyObject *PyInit__lldb(void); + +#define LLDBSwigPyInit PyInit__lldb + +#else +extern "C" void init_lldb(void); + +#define LLDBSwigPyInit init_lldb +#endif + +// These prototypes are the Pythonic implementations of the required callbacks. +// Although these are scripting-language specific, their definition depends on +// the public API. +extern "C" bool LLDBSwigPythonBreakpointCallbackFunction( + const char *python_function_name, const char *session_dictionary_name, + const lldb::StackFrameSP &sb_frame, + const lldb::BreakpointLocationSP &sb_bp_loc); + +extern "C" bool LLDBSwigPythonWatchpointCallbackFunction( + const char *python_function_name, const char *session_dictionary_name, + const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp); + +extern "C" bool LLDBSwigPythonCallTypeScript( + const char *python_function_name, void *session_dictionary, + const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, + const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval); + +extern "C" void * +LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, + const char *session_dictionary_name, + const lldb::ValueObjectSP &valobj_sp); + +extern "C" void * +LLDBSwigPythonCreateCommandObject(const char *python_class_name, + const char *session_dictionary_name, + const lldb::DebuggerSP debugger_sp); + +extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan( + const char *python_class_name, const char *session_dictionary_name, + const lldb::ThreadPlanSP &thread_plan_sp); + +extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor, + const char *method_name, + Event *event_sp, bool &got_error); + +extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver( + const char *python_class_name, const char *session_dictionary_name, + lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp); + +extern "C" unsigned int +LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name, + lldb_private::SymbolContext *sym_ctx); + +extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor, + uint32_t max); + +extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor, + uint32_t idx); + +extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor, + const char *child_name); + +extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data); + +extern lldb::ValueObjectSP +LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data); + +extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor); + +extern "C" bool +LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor); + +extern "C" void * +LLDBSwigPython_GetValueSynthProviderInstance(void *implementor); + +extern "C" bool +LLDBSwigPythonCallCommand(const char *python_function_name, + const char *session_dictionary_name, + lldb::DebuggerSP &debugger, const char *args, + lldb_private::CommandReturnObject &cmd_retobj, + lldb::ExecutionContextRefSP exe_ctx_ref_sp); + +extern "C" bool +LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger, + const char *args, + lldb_private::CommandReturnObject &cmd_retobj, + lldb::ExecutionContextRefSP exe_ctx_ref_sp); + +extern "C" bool +LLDBSwigPythonCallModuleInit(const char *python_module_name, + const char *session_dictionary_name, + lldb::DebuggerSP &debugger); + +extern "C" void * +LLDBSWIGPythonCreateOSPlugin(const char *python_class_name, + const char *session_dictionary_name, + const lldb::ProcessSP &process_sp); + +extern "C" void * +LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name, + const char *session_dictionary_name); + +extern "C" void * +LLDBSwigPython_GetRecognizedArguments(void *implementor, + const lldb::StackFrameSP &frame_sp); + +extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess( + const char *python_function_name, const char *session_dictionary_name, + lldb::ProcessSP &process, std::string &output); + +extern "C" bool LLDBSWIGPythonRunScriptKeywordThread( + const char *python_function_name, const char *session_dictionary_name, + lldb::ThreadSP &thread, std::string &output); + +extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget( + const char *python_function_name, const char *session_dictionary_name, + lldb::TargetSP &target, std::string &output); + +extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame( + const char *python_function_name, const char *session_dictionary_name, + lldb::StackFrameSP &frame, std::string &output); + +extern "C" bool LLDBSWIGPythonRunScriptKeywordValue( + const char *python_function_name, const char *session_dictionary_name, + lldb::ValueObjectSP &value, std::string &output); + +extern "C" void * +LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, + const lldb::TargetSP &target_sp); static bool g_initialized = false; @@ -138,7 +208,7 @@ InitializePythonHome(); // Register _lldb as a built-in module. - PyImport_AppendInittab("_lldb", g_swig_init_callback); + PyImport_AppendInittab("_lldb", LLDBSwigPyInit); // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you @@ -156,7 +226,7 @@ if (m_was_already_initialized) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", - m_was_already_initialized == PyGILState_UNLOCKED ? "un" : ""); + m_gil_state == PyGILState_UNLOCKED ? "un" : ""); PyGILState_Release(m_gil_state); } else { // We initialized the threads in this function, just unlock the GIL. @@ -176,10 +246,33 @@ static char g_python_home[] = LLDB_PYTHON_HOME; #endif Py_SetPythonHome(g_python_home); +#else +#if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7 + // For Darwin, the only Python version supported is the one shipped in the + // OS OS and linked with lldb. Other installation of Python may have higher + // priorities in the path, overriding PYTHONHOME and causing + // problems/incompatibilities. In order to avoid confusion, always hardcode + // the PythonHome to be right, as it's not going to change. + static char path[] = + "/System/Library/Frameworks/Python.framework/Versions/2.7"; + Py_SetPythonHome(path); +#endif #endif } void InitializeThreadsPrivate() { +// Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself, +// so there is no way to determine whether the embedded interpreter +// was already initialized by some external code. `PyEval_ThreadsInitialized` +// would always return `true` and `PyGILState_Ensure/Release` flow would be +// executed instead of unlocking GIL with `PyEval_SaveThread`. When +// an another thread calls `PyGILState_Ensure` it would get stuck in deadlock. +#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3) + // The only case we should go further and acquire the GIL: it is unlocked. + if (PyGILState_Check()) + return; +#endif + if (PyEval_ThreadsInitialized()) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); @@ -198,166 +291,7 @@ PyGILState_STATE m_gil_state; bool m_was_already_initialized; }; -} - -ScriptInterpreterPython::Locker::Locker(ScriptInterpreterPython *py_interpreter, - uint16_t on_entry, uint16_t on_leave, - FILE *in, FILE *out, FILE *err) - : ScriptInterpreterLocker(), - m_teardown_session((on_leave & TearDownSession) == TearDownSession), - m_python_interpreter(py_interpreter) { - DoAcquireLock(); - if ((on_entry & InitSession) == InitSession) { - if (!DoInitSession(on_entry, in, out, err)) { - // Don't teardown the session if we didn't init it. - m_teardown_session = false; - } - } -} - -bool ScriptInterpreterPython::Locker::DoAcquireLock() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); - m_GILState = PyGILState_Ensure(); - LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked", - m_GILState == PyGILState_UNLOCKED ? "un" : ""); - - // we need to save the thread state when we first start the command because - // we might decide to interrupt it while some action is taking place outside - // of Python (e.g. printing to screen, waiting for the network, ...) in that - // case, _PyThreadState_Current will be NULL - and we would be unable to set - // the asynchronous exception - not a desirable situation - m_python_interpreter->SetThreadState(PyThreadState_Get()); - m_python_interpreter->IncrementLockCount(); - return true; -} - -bool ScriptInterpreterPython::Locker::DoInitSession(uint16_t on_entry_flags, - FILE *in, FILE *out, - FILE *err) { - if (!m_python_interpreter) - return false; - return m_python_interpreter->EnterSession(on_entry_flags, in, out, err); -} - -bool ScriptInterpreterPython::Locker::DoFreeLock() { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); - LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", - m_GILState == PyGILState_UNLOCKED ? "un" : ""); - PyGILState_Release(m_GILState); - m_python_interpreter->DecrementLockCount(); - return true; -} - -bool ScriptInterpreterPython::Locker::DoTearDownSession() { - if (!m_python_interpreter) - return false; - m_python_interpreter->LeaveSession(); - return true; -} - -ScriptInterpreterPython::Locker::~Locker() { - if (m_teardown_session) - DoTearDownSession(); - DoFreeLock(); -} - -ScriptInterpreterPython::ScriptInterpreterPython( - CommandInterpreter &interpreter) - : ScriptInterpreter(interpreter, eScriptLanguagePython), - IOHandlerDelegateMultiline("DONE"), m_saved_stdin(), m_saved_stdout(), - m_saved_stderr(), m_main_module(), m_lldb_module(), - m_session_dict(PyInitialValue::Invalid), - m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(), - m_run_one_line_str_global(), - m_dictionary_name( - interpreter.GetDebugger().GetInstanceName().AsCString()), - m_terminal_state(), m_active_io_handler(eIOHandlerNone), - m_session_is_active(false), m_pty_slave_is_open(false), - m_valid_session(true), m_lock_count(0), m_command_thread_state(nullptr) { - InitializePrivate(); - - m_dictionary_name.append("_dict"); - StreamString run_string; - run_string.Printf("%s = dict()", m_dictionary_name.c_str()); - - Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock, - ScriptInterpreterPython::Locker::FreeAcquiredLock); - PyRun_SimpleString(run_string.GetData()); - - run_string.Clear(); - run_string.Printf( - "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", - m_dictionary_name.c_str()); - PyRun_SimpleString(run_string.GetData()); - - // Reloading modules requires a different syntax in Python 2 and Python 3. - // This provides a consistent syntax no matter what version of Python. - run_string.Clear(); - run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", - m_dictionary_name.c_str()); - PyRun_SimpleString(run_string.GetData()); - - // WARNING: temporary code that loads Cocoa formatters - this should be done - // on a per-platform basis rather than loading the whole set and letting the - // individual formatter classes exploit APIs to check whether they can/cannot - // do their task - run_string.Clear(); - run_string.Printf( - "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", - m_dictionary_name.c_str()); - PyRun_SimpleString(run_string.GetData()); - run_string.Clear(); - - run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from " - "lldb.embedded_interpreter import run_python_interpreter; " - "from lldb.embedded_interpreter import run_one_line')", - m_dictionary_name.c_str()); - PyRun_SimpleString(run_string.GetData()); - run_string.Clear(); - - run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 - "; pydoc.pager = pydoc.plainpager')", - m_dictionary_name.c_str(), - interpreter.GetDebugger().GetID()); - PyRun_SimpleString(run_string.GetData()); -} - -ScriptInterpreterPython::~ScriptInterpreterPython() { - // the session dictionary may hold objects with complex state which means - // that they may need to be torn down with some level of smarts and that, in - // turn, requires a valid thread state force Python to procure itself such a - // thread state, nuke the session dictionary and then release it for others - // to use and proceed with the rest of the shutdown - auto gil_state = PyGILState_Ensure(); - m_session_dict.Reset(); - PyGILState_Release(gil_state); -} - -void ScriptInterpreterPython::Initialize() { - static llvm::once_flag g_once_flag; - - llvm::call_once(g_once_flag, []() { - PluginManager::RegisterPlugin(GetPluginNameStatic(), - GetPluginDescriptionStatic(), - lldb::eScriptLanguagePython, CreateInstance); - }); -} - -void ScriptInterpreterPython::Terminate() {} - -lldb::ScriptInterpreterSP -ScriptInterpreterPython::CreateInstance(CommandInterpreter &interpreter) { - return std::make_shared<ScriptInterpreterPython>(interpreter); -} - -lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() { - static ConstString g_name("script-python"); - return g_name; -} - -const char *ScriptInterpreterPython::GetPluginDescriptionStatic() { - return "Embedded Python interpreter"; -} +} // namespace void ScriptInterpreterPython::ComputePythonDirForApple( llvm::SmallVectorImpl<char> &path) { @@ -424,13 +358,164 @@ return g_spec; } -lldb_private::ConstString ScriptInterpreterPython::GetPluginName() { +lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() { + static ConstString g_name("script-python"); + return g_name; +} + +const char *ScriptInterpreterPython::GetPluginDescriptionStatic() { + return "Embedded Python interpreter"; +} + +void ScriptInterpreterPython::Initialize() { + static llvm::once_flag g_once_flag; + + llvm::call_once(g_once_flag, []() { + PluginManager::RegisterPlugin(GetPluginNameStatic(), + GetPluginDescriptionStatic(), + lldb::eScriptLanguagePython, + ScriptInterpreterPythonImpl::CreateInstance); + }); +} + +void ScriptInterpreterPython::Terminate() {} + +ScriptInterpreterPythonImpl::Locker::Locker( + ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry, + uint16_t on_leave, FILE *in, FILE *out, FILE *err) + : ScriptInterpreterLocker(), + m_teardown_session((on_leave & TearDownSession) == TearDownSession), + m_python_interpreter(py_interpreter) { + DoAcquireLock(); + if ((on_entry & InitSession) == InitSession) { + if (!DoInitSession(on_entry, in, out, err)) { + // Don't teardown the session if we didn't init it. + m_teardown_session = false; + } + } +} + +bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); + m_GILState = PyGILState_Ensure(); + LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked", + m_GILState == PyGILState_UNLOCKED ? "un" : ""); + + // we need to save the thread state when we first start the command because + // we might decide to interrupt it while some action is taking place outside + // of Python (e.g. printing to screen, waiting for the network, ...) in that + // case, _PyThreadState_Current will be NULL - and we would be unable to set + // the asynchronous exception - not a desirable situation + m_python_interpreter->SetThreadState(PyThreadState_Get()); + m_python_interpreter->IncrementLockCount(); + return true; +} + +bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags, + FILE *in, FILE *out, + FILE *err) { + if (!m_python_interpreter) + return false; + return m_python_interpreter->EnterSession(on_entry_flags, in, out, err); +} + +bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); + LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", + m_GILState == PyGILState_UNLOCKED ? "un" : ""); + PyGILState_Release(m_GILState); + m_python_interpreter->DecrementLockCount(); + return true; +} + +bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() { + if (!m_python_interpreter) + return false; + m_python_interpreter->LeaveSession(); + return true; +} + +ScriptInterpreterPythonImpl::Locker::~Locker() { + if (m_teardown_session) + DoTearDownSession(); + DoFreeLock(); +} + +ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger) + : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(), + m_saved_stderr(), m_main_module(), + m_session_dict(PyInitialValue::Invalid), + m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(), + m_run_one_line_str_global(), + m_dictionary_name(m_debugger.GetInstanceName().AsCString()), + m_terminal_state(), m_active_io_handler(eIOHandlerNone), + m_session_is_active(false), m_pty_slave_is_open(false), + m_valid_session(true), m_lock_count(0), m_command_thread_state(nullptr) { + InitializePrivate(); + + m_dictionary_name.append("_dict"); + StreamString run_string; + run_string.Printf("%s = dict()", m_dictionary_name.c_str()); + + Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); + PyRun_SimpleString(run_string.GetData()); + + run_string.Clear(); + run_string.Printf( + "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", + m_dictionary_name.c_str()); + PyRun_SimpleString(run_string.GetData()); + + // Reloading modules requires a different syntax in Python 2 and Python 3. + // This provides a consistent syntax no matter what version of Python. + run_string.Clear(); + run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", + m_dictionary_name.c_str()); + PyRun_SimpleString(run_string.GetData()); + + // WARNING: temporary code that loads Cocoa formatters - this should be done + // on a per-platform basis rather than loading the whole set and letting the + // individual formatter classes exploit APIs to check whether they can/cannot + // do their task + run_string.Clear(); + run_string.Printf( + "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", + m_dictionary_name.c_str()); + PyRun_SimpleString(run_string.GetData()); + run_string.Clear(); + + run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from " + "lldb.embedded_interpreter import run_python_interpreter; " + "from lldb.embedded_interpreter import run_one_line')", + m_dictionary_name.c_str()); + PyRun_SimpleString(run_string.GetData()); + run_string.Clear(); + + run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 + "; pydoc.pager = pydoc.plainpager')", + m_dictionary_name.c_str(), m_debugger.GetID()); + PyRun_SimpleString(run_string.GetData()); +} + +ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() { + // the session dictionary may hold objects with complex state which means + // that they may need to be torn down with some level of smarts and that, in + // turn, requires a valid thread state force Python to procure itself such a + // thread state, nuke the session dictionary and then release it for others + // to use and proceed with the rest of the shutdown + auto gil_state = PyGILState_Ensure(); + m_session_dict.Reset(); + PyGILState_Release(gil_state); +} + +lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() { return GetPluginNameStatic(); } -uint32_t ScriptInterpreterPython::GetPluginVersion() { return 1; } +uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; } -void ScriptInterpreterPython::IOHandlerActivated(IOHandler &io_handler) { +void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler, + bool interactive) { const char *instructions = nullptr; switch (m_active_io_handler) { @@ -451,17 +536,17 @@ if (instructions) { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) { + if (output_sp && interactive) { output_sp->PutCString(instructions); output_sp->Flush(); } } } -void ScriptInterpreterPython::IOHandlerInputComplete(IOHandler &io_handler, - std::string &data) { +void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler, + std::string &data) { io_handler.SetIsDone(true); - bool batch_mode = m_interpreter.GetBatchCommandMode(); + bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode(); switch (m_active_io_handler) { case eIOHandlerNone: @@ -473,18 +558,18 @@ if (!bp_options) continue; - auto data_ap = llvm::make_unique<CommandDataPython>(); - if (!data_ap) + auto data_up = llvm::make_unique<CommandDataPython>(); + if (!data_up) break; - data_ap->user_source.SplitIntoLines(data); + data_up->user_source.SplitIntoLines(data); - if (GenerateBreakpointCommandCallbackData(data_ap->user_source, - data_ap->script_source) + if (GenerateBreakpointCommandCallbackData(data_up->user_source, + data_up->script_source) .Success()) { auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>( - std::move(data_ap)); + std::move(data_up)); bp_options->SetCallback( - ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); + ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); } else if (!batch_mode) { StreamFileSP error_sp = io_handler.GetErrorStreamFile(); if (error_sp) { @@ -498,15 +583,15 @@ case eIOHandlerWatchpoint: { WatchpointOptions *wp_options = (WatchpointOptions *)io_handler.GetUserData(); - auto data_ap = llvm::make_unique<WatchpointOptions::CommandData>(); - data_ap->user_source.SplitIntoLines(data); + auto data_up = llvm::make_unique<WatchpointOptions::CommandData>(); + data_up->user_source.SplitIntoLines(data); - if (GenerateWatchpointCommandCallbackData(data_ap->user_source, - data_ap->script_source)) { + if (GenerateWatchpointCommandCallbackData(data_up->user_source, + data_up->script_source)) { auto baton_sp = - std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap)); + std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); wp_options->SetCallback( - ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp); + ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); } else if (!batch_mode) { StreamFileSP error_sp = io_handler.GetErrorStreamFile(); if (error_sp) { @@ -519,9 +604,14 @@ } } -void ScriptInterpreterPython::ResetOutputFileHandle(FILE *fh) {} +lldb::ScriptInterpreterSP +ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) { + return std::make_shared<ScriptInterpreterPythonImpl>(debugger); +} -void ScriptInterpreterPython::SaveTerminalState(int fd) { +void ScriptInterpreterPythonImpl::ResetOutputFileHandle(FILE *fh) {} + +void ScriptInterpreterPythonImpl::SaveTerminalState(int fd) { // Python mucks with the terminal state of STDIN. If we can possibly avoid // this by setting the file handles up correctly prior to entering the // interpreter we should. For now we save and restore the terminal state on @@ -529,7 +619,7 @@ m_terminal_state.Save(fd, false); } -void ScriptInterpreterPython::RestoreTerminalState() { +void ScriptInterpreterPythonImpl::RestoreTerminalState() { // Python mucks with the terminal state of STDIN. If we can possibly avoid // this by setting the file handles up correctly prior to entering the // interpreter we should. For now we save and restore the terminal state on @@ -537,10 +627,10 @@ m_terminal_state.Restore(); } -void ScriptInterpreterPython::LeaveSession() { +void ScriptInterpreterPythonImpl::LeaveSession() { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); if (log) - log->PutCString("ScriptInterpreterPython::LeaveSession()"); + log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()"); // checking that we have a valid thread state - since we use our own // threading and locking in some (rare) cases during cleanup Python may end @@ -572,9 +662,9 @@ m_session_is_active = false; } -bool ScriptInterpreterPython::SetStdHandle(File &file, const char *py_name, - PythonFile &save_file, - const char *mode) { +bool ScriptInterpreterPythonImpl::SetStdHandle(File &file, const char *py_name, + PythonFile &save_file, + const char *mode) { if (file.IsValid()) { // Flush the file before giving it to python to avoid interleaved output. file.Flush(); @@ -592,15 +682,15 @@ return false; } -bool ScriptInterpreterPython::EnterSession(uint16_t on_entry_flags, FILE *in, - FILE *out, FILE *err) { +bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags, + FILE *in, FILE *out, FILE *err) { // If we have already entered the session, without having officially 'left' // it, then there is no need to 'enter' it again. Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); if (m_session_is_active) { if (log) log->Printf( - "ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 + "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ") session is already active, returning without doing anything", on_entry_flags); return false; @@ -608,7 +698,8 @@ if (log) log->Printf( - "ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ")", + "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 + ")", on_entry_flags); m_session_is_active = true; @@ -617,11 +708,10 @@ if (on_entry_flags & Locker::InitGlobals) { run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, - m_dictionary_name.c_str(), - GetCommandInterpreter().GetDebugger().GetID()); + m_dictionary_name.c_str(), m_debugger.GetID()); run_string.Printf( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", - GetCommandInterpreter().GetDebugger().GetID()); + m_debugger.GetID()); run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()"); run_string.PutCString("; lldb.process = lldb.target.GetProcess()"); run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()"); @@ -631,11 +721,10 @@ // If we aren't initing the globals, we should still always set the // debugger (since that is always unique.) run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, - m_dictionary_name.c_str(), - GetCommandInterpreter().GetDebugger().GetID()); + m_dictionary_name.c_str(), m_debugger.GetID()); run_string.Printf( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", - GetCommandInterpreter().GetDebugger().GetID()); + m_debugger.GetID()); run_string.PutCString("')"); } @@ -652,8 +741,7 @@ lldb::StreamFileSP out_sp; lldb::StreamFileSP err_sp; if (!in_file.IsValid() || !out_file.IsValid() || !err_file.IsValid()) - m_interpreter.GetDebugger().AdoptTopIOHandlerFilesIfInvalid(in_sp, out_sp, - err_sp); + m_debugger.AdoptTopIOHandlerFilesIfInvalid(in_sp, out_sp, err_sp); if (on_entry_flags & Locker::NoSTDIN) { m_saved_stdin.Reset(); @@ -681,13 +769,13 @@ return true; } -PythonObject &ScriptInterpreterPython::GetMainModule() { +PythonObject &ScriptInterpreterPythonImpl::GetMainModule() { if (!m_main_module.IsValid()) m_main_module.Reset(PyRefType::Borrowed, PyImport_AddModule("__main__")); return m_main_module; } -PythonDictionary &ScriptInterpreterPython::GetSessionDictionary() { +PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() { if (m_session_dict.IsValid()) return m_session_dict; @@ -705,7 +793,7 @@ return m_session_dict; } -PythonDictionary &ScriptInterpreterPython::GetSysModuleDictionary() { +PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() { if (m_sys_module_dict.IsValid()) return m_sys_module_dict; @@ -732,7 +820,7 @@ return sstr.GetString(); } -bool ScriptInterpreterPython::GetEmbeddedInterpreterModuleObjects() { +bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() { if (m_run_one_line_function.IsValid()) return true; @@ -762,7 +850,7 @@ } } -bool ScriptInterpreterPython::ExecuteOneLine( +bool ScriptInterpreterPythonImpl::ExecuteOneLine( llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options) { std::string command_str = command.str(); @@ -777,13 +865,13 @@ // another string to pass to PyRun_SimpleString messes up the escaping. So // we use the following more complicated method to pass the command string // directly down to Python. - Debugger &debugger = m_interpreter.GetDebugger(); + Debugger &debugger = m_debugger; StreamFileSP input_file_sp; StreamFileSP output_file_sp; StreamFileSP error_file_sp; Communication output_comm( - "lldb.ScriptInterpreterPython.ExecuteOneLine.comm"); + "lldb.ScriptInterpreterPythonImpl.ExecuteOneLine.comm"); bool join_read_thread = false; if (options.GetEnableIO()) { if (result) { @@ -797,22 +885,22 @@ #if defined(_WIN32) lldb::file_t read_file = pipe.GetReadNativeHandle(); pipe.ReleaseReadFileDescriptor(); - std::unique_ptr<ConnectionGenericFile> conn_ap( + std::unique_ptr<ConnectionGenericFile> conn_up( new ConnectionGenericFile(read_file, true)); #else - std::unique_ptr<ConnectionFileDescriptor> conn_ap( + std::unique_ptr<ConnectionFileDescriptor> conn_up( new ConnectionFileDescriptor(pipe.ReleaseReadFileDescriptor(), true)); #endif - if (conn_ap->IsConnected()) { - output_comm.SetConnection(conn_ap.release()); + if (conn_up->IsConnected()) { + output_comm.SetConnection(conn_up.release()); output_comm.SetReadThreadBytesReceivedCallback( ReadThreadBytesReceived, &result->GetOutputStream()); output_comm.StartReadThread(); join_read_thread = true; FILE *outfile_handle = fdopen(pipe.ReleaseWriteFileDescriptor(), "w"); - output_file_sp.reset(new StreamFile(outfile_handle, true)); + output_file_sp = std::make_shared<StreamFile>(outfile_handle, true); error_file_sp = output_file_sp; if (outfile_handle) ::setbuf(outfile_handle, nullptr); @@ -828,12 +916,12 @@ debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp, error_file_sp); } else { - input_file_sp.reset(new StreamFile()); + input_file_sp = std::make_shared<StreamFile>(); FileSystem::Instance().Open(input_file_sp->GetFile(), FileSpec(FileSystem::DEV_NULL), File::eOpenOptionRead); - output_file_sp.reset(new StreamFile()); + output_file_sp = std::make_shared<StreamFile>(); FileSystem::Instance().Open(output_file_sp->GetFile(), FileSpec(FileSystem::DEV_NULL), File::eOpenOptionWrite); @@ -856,15 +944,11 @@ // happen. Locker locker( this, - ScriptInterpreterPython::Locker::AcquireLock | - ScriptInterpreterPython::Locker::InitSession | - (options.GetSetLLDBGlobals() - ? ScriptInterpreterPython::Locker::InitGlobals - : 0) | + Locker::AcquireLock | Locker::InitSession | + (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN), - ScriptInterpreterPython::Locker::FreeAcquiredLock | - ScriptInterpreterPython::Locker::TearDownSession, - in_file, out_file, err_file); + Locker::FreeAcquiredLock | Locker::TearDownSession, in_file, out_file, + err_file); // Find the correct script interpreter dictionary in the main module. PythonDictionary &session_dict = GetSessionDictionary(); @@ -924,82 +1008,11 @@ return false; } -class IOHandlerPythonInterpreter : public IOHandler { -public: - IOHandlerPythonInterpreter(Debugger &debugger, - ScriptInterpreterPython *python) - : IOHandler(debugger, IOHandler::Type::PythonInterpreter), - m_python(python) {} - - ~IOHandlerPythonInterpreter() override {} - - ConstString GetControlSequence(char ch) override { - if (ch == 'd') - return ConstString("quit()\n"); - return ConstString(); - } - - void Run() override { - if (m_python) { - int stdin_fd = GetInputFD(); - if (stdin_fd >= 0) { - Terminal terminal(stdin_fd); - TerminalState terminal_state; - const bool is_a_tty = terminal.IsATerminal(); - - if (is_a_tty) { - terminal_state.Save(stdin_fd, false); - terminal.SetCanonical(false); - terminal.SetEcho(true); - } - - ScriptInterpreterPython::Locker locker( - m_python, ScriptInterpreterPython::Locker::AcquireLock | - ScriptInterpreterPython::Locker::InitSession | - ScriptInterpreterPython::Locker::InitGlobals, - ScriptInterpreterPython::Locker::FreeAcquiredLock | - ScriptInterpreterPython::Locker::TearDownSession); - - // The following call drops into the embedded interpreter loop and - // stays there until the user chooses to exit from the Python - // interpreter. This embedded interpreter will, as any Python code that - // performs I/O, unlock the GIL before a system call that can hang, and - // lock it when the syscall has returned. - - // We need to surround the call to the embedded interpreter with calls - // to PyGILState_Ensure and PyGILState_Release (using the Locker - // above). This is because Python has a global lock which must be held - // whenever we want to touch any Python objects. Otherwise, if the user - // calls Python code, the interpreter state will be off, and things - // could hang (it's happened before). - - StreamString run_string; - run_string.Printf("run_python_interpreter (%s)", - m_python->GetDictionaryName()); - PyRun_SimpleString(run_string.GetData()); - - if (is_a_tty) - terminal_state.Restore(); - } - } - SetIsDone(true); - } - - void Cancel() override {} - - bool Interrupt() override { return m_python->Interrupt(); } - - void GotEOF() override {} - -protected: - ScriptInterpreterPython *m_python; -}; - -void ScriptInterpreterPython::ExecuteInterpreterLoop() { +void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); - Debugger &debugger = GetCommandInterpreter().GetDebugger(); + Debugger &debugger = m_debugger; // At the moment, the only time the debugger does not have an input file // handle is when this is called directly from Python, in which case it is @@ -1016,7 +1029,7 @@ } } -bool ScriptInterpreterPython::Interrupt() { +bool ScriptInterpreterPythonImpl::Interrupt() { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); if (IsExecutingPython()) { @@ -1028,29 +1041,27 @@ PyThreadState_Swap(state); int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt); if (log) - log->Printf("ScriptInterpreterPython::Interrupt() sending " + log->Printf("ScriptInterpreterPythonImpl::Interrupt() sending " "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", tid, num_threads); return true; } } if (log) - log->Printf("ScriptInterpreterPython::Interrupt() python code not running, " - "can't interrupt"); + log->Printf( + "ScriptInterpreterPythonImpl::Interrupt() python code not running, " + "can't interrupt"); return false; } -bool ScriptInterpreterPython::ExecuteOneLineWithReturn( +bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn( llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, void *ret_value, const ExecuteScriptOptions &options) { - Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock | - ScriptInterpreterPython::Locker::InitSession | - (options.GetSetLLDBGlobals() - ? ScriptInterpreterPython::Locker::InitGlobals - : 0) | - Locker::NoSTDIN, - ScriptInterpreterPython::Locker::FreeAcquiredLock | - ScriptInterpreterPython::Locker::TearDownSession); + Locker locker(this, + Locker::AcquireLock | Locker::InitSession | + (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | + Locker::NoSTDIN, + Locker::FreeAcquiredLock | Locker::TearDownSession); PythonObject py_return; PythonObject &main_module = GetMainModule(); @@ -1195,18 +1206,15 @@ return ret_success; } -Status ScriptInterpreterPython::ExecuteMultipleLines( +Status ScriptInterpreterPythonImpl::ExecuteMultipleLines( const char *in_string, const ExecuteScriptOptions &options) { Status error; - Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock | - ScriptInterpreterPython::Locker::InitSession | - (options.GetSetLLDBGlobals() - ? ScriptInterpreterPython::Locker::InitGlobals - : 0) | - Locker::NoSTDIN, - ScriptInterpreterPython::Locker::FreeAcquiredLock | - ScriptInterpreterPython::Locker::TearDownSession); + Locker locker(this, + Locker::AcquireLock | Locker::InitSession | + (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | + Locker::NoSTDIN, + Locker::FreeAcquiredLock | Locker::TearDownSession); PythonObject return_value; PythonObject &main_module = GetMainModule(); @@ -1256,31 +1264,32 @@ return error; } -void ScriptInterpreterPython::CollectDataForBreakpointCommandCallback( +void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback( std::vector<BreakpointOptions *> &bp_options_vec, CommandReturnObject &result) { m_active_io_handler = eIOHandlerBreakpoint; - m_interpreter.GetPythonCommandsFromIOHandler(" ", *this, true, - &bp_options_vec); + m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( + " ", *this, true, &bp_options_vec); } -void ScriptInterpreterPython::CollectDataForWatchpointCommandCallback( +void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback( WatchpointOptions *wp_options, CommandReturnObject &result) { m_active_io_handler = eIOHandlerWatchpoint; - m_interpreter.GetPythonCommandsFromIOHandler(" ", *this, true, wp_options); + m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( + " ", *this, true, wp_options); } -void ScriptInterpreterPython::SetBreakpointCommandCallbackFunction( +void ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction( BreakpointOptions *bp_options, const char *function_name) { // For now just cons up a oneliner that calls the provided function. std::string oneliner("return "); oneliner += function_name; oneliner += "(frame, bp_loc, internal_dict)"; - m_interpreter.GetScriptInterpreter()->SetBreakpointCommandCallback( + m_debugger.GetScriptInterpreter()->SetBreakpointCommandCallback( bp_options, oneliner.c_str()); } -Status ScriptInterpreterPython::SetBreakpointCommandCallback( +Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( BreakpointOptions *bp_options, std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { Status error; @@ -1291,59 +1300,59 @@ } auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up)); - bp_options->SetCallback(ScriptInterpreterPython::BreakpointCallbackFunction, - baton_sp); + bp_options->SetCallback( + ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); return error; } // Set a Python one-liner as the callback for the breakpoint. -Status ScriptInterpreterPython::SetBreakpointCommandCallback( +Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( BreakpointOptions *bp_options, const char *command_body_text) { - auto data_ap = llvm::make_unique<CommandDataPython>(); + auto data_up = llvm::make_unique<CommandDataPython>(); // Split the command_body_text into lines, and pass that to // GenerateBreakpointCommandCallbackData. That will wrap the body in an // auto-generated function, and return the function name in script_source. // That is what the callback will actually invoke. - data_ap->user_source.SplitIntoLines(command_body_text); - Status error = GenerateBreakpointCommandCallbackData(data_ap->user_source, - data_ap->script_source); + data_up->user_source.SplitIntoLines(command_body_text); + Status error = GenerateBreakpointCommandCallbackData(data_up->user_source, + data_up->script_source); if (error.Success()) { auto baton_sp = - std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_ap)); - bp_options->SetCallback(ScriptInterpreterPython::BreakpointCallbackFunction, - baton_sp); + std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); + bp_options->SetCallback( + ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); return error; } else return error; } // Set a Python one-liner as the callback for the watchpoint. -void ScriptInterpreterPython::SetWatchpointCommandCallback( +void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback( WatchpointOptions *wp_options, const char *oneliner) { - auto data_ap = llvm::make_unique<WatchpointOptions::CommandData>(); + auto data_up = llvm::make_unique<WatchpointOptions::CommandData>(); // It's necessary to set both user_source and script_source to the oneliner. // The former is used to generate callback description (as in watchpoint // command list) while the latter is used for Python to interpret during the // actual callback. - data_ap->user_source.AppendString(oneliner); - data_ap->script_source.assign(oneliner); + data_up->user_source.AppendString(oneliner); + data_up->script_source.assign(oneliner); - if (GenerateWatchpointCommandCallbackData(data_ap->user_source, - data_ap->script_source)) { + if (GenerateWatchpointCommandCallbackData(data_up->user_source, + data_up->script_source)) { auto baton_sp = - std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap)); - wp_options->SetCallback(ScriptInterpreterPython::WatchpointCallbackFunction, - baton_sp); + std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); + wp_options->SetCallback( + ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); } return; } -Status ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter( +Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter( StringList &function_def) { // Convert StringList to one long, newline delimited, const char *. std::string function_def_string(function_def.CopyList()); @@ -1354,8 +1363,8 @@ return error; } -Status ScriptInterpreterPython::GenerateFunction(const char *signature, - const StringList &input) { +Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature, + const StringList &input) { Status error; int num_lines = input.GetSize(); if (num_lines == 0) { @@ -1411,7 +1420,7 @@ return error; } -bool ScriptInterpreterPython::GenerateTypeScriptFunction( +bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( StringList &user_input, std::string &output, const void *name_token) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); @@ -1438,7 +1447,7 @@ return true; } -bool ScriptInterpreterPython::GenerateScriptAliasFunction( +bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction( StringList &user_input, std::string &output) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); @@ -1462,9 +1471,8 @@ return true; } -bool ScriptInterpreterPython::GenerateTypeSynthClass(StringList &user_input, - std::string &output, - const void *name_token) { +bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( + StringList &user_input, std::string &output, const void *name_token) { static uint32_t num_created_classes = 0; user_input.RemoveBlankLines(); int num_lines = user_input.GetSize(); @@ -1507,8 +1515,8 @@ return true; } -StructuredData::GenericSP ScriptInterpreterPython::CreateFrameRecognizer( - const char *class_name) { +StructuredData::GenericSP +ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) { if (class_name == nullptr || class_name[0] == '\0') return StructuredData::GenericSP(); @@ -1517,31 +1525,34 @@ { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); - ret_val = - g_swig_create_frame_recognizer(class_name, m_dictionary_name.c_str()); + ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name, + m_dictionary_name.c_str()); } return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); } -lldb::ValueObjectListSP ScriptInterpreterPython::GetRecognizedArguments( +lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( const StructuredData::ObjectSP &os_plugin_object_sp, lldb::StackFrameSP frame_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); - if (!os_plugin_object_sp) return ValueObjectListSP(); + if (!os_plugin_object_sp) + return ValueObjectListSP(); StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); - if (!generic) return nullptr; + if (!generic) + return nullptr; PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); - if (!implementor.IsAllocated()) return ValueObjectListSP(); + if (!implementor.IsAllocated()) + return ValueObjectListSP(); - PythonObject py_return( - PyRefType::Owned, - (PyObject *)g_swig_get_recognized_arguments(implementor.get(), frame_sp)); + PythonObject py_return(PyRefType::Owned, + (PyObject *)LLDBSwigPython_GetRecognizedArguments( + implementor.get(), frame_sp)); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { @@ -1554,16 +1565,18 @@ for (size_t i = 0; i < result_list.GetSize(); i++) { PyObject *item = result_list.GetItemAtIndex(i).get(); lldb::SBValue *sb_value_ptr = - (lldb::SBValue *)g_swig_cast_to_sbvalue(item); - auto valobj_sp = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr); - if (valobj_sp) result->Append(valobj_sp); + (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); + auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); + if (valobj_sp) + result->Append(valobj_sp); } return result; } return ValueObjectListSP(); } -StructuredData::GenericSP ScriptInterpreterPython::OSPlugin_CreatePluginObject( +StructuredData::GenericSP +ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject( const char *class_name, lldb::ProcessSP process_sp) { if (class_name == nullptr || class_name[0] == '\0') return StructuredData::GenericSP(); @@ -1576,14 +1589,14 @@ { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); - ret_val = g_swig_create_os_plugin(class_name, m_dictionary_name.c_str(), - process_sp); + ret_val = LLDBSWIGPythonCreateOSPlugin( + class_name, m_dictionary_name.c_str(), process_sp); } return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); } -StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_RegisterInfo( +StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo( StructuredData::ObjectSP os_plugin_object_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); @@ -1638,7 +1651,7 @@ return StructuredData::DictionarySP(); } -StructuredData::ArraySP ScriptInterpreterPython::OSPlugin_ThreadsInfo( +StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo( StructuredData::ObjectSP os_plugin_object_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); @@ -1723,7 +1736,8 @@ template <> const char *GetPythonValueFormatString(float t) { return "f"; } template <> const char *GetPythonValueFormatString(double t) { return "d"; } -StructuredData::StringSP ScriptInterpreterPython::OSPlugin_RegisterContextData( +StructuredData::StringSP +ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData( StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); @@ -1779,7 +1793,7 @@ return StructuredData::StringSP(); } -StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_CreateThread( +StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread( StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, lldb::addr_t context) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); @@ -1838,7 +1852,7 @@ return StructuredData::DictionarySP(); } -StructuredData::ObjectSP ScriptInterpreterPython::CreateScriptedThreadPlan( +StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan( const char *class_name, lldb::ThreadPlanSP thread_plan_sp) { if (class_name == nullptr || class_name[0] == '\0') return StructuredData::ObjectSP(); @@ -1847,10 +1861,9 @@ return StructuredData::ObjectSP(); Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); - ScriptInterpreter *script_interpreter = - debugger.GetCommandInterpreter().GetScriptInterpreter(); - ScriptInterpreterPython *python_interpreter = - static_cast<ScriptInterpreterPython *>(script_interpreter); + ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); + ScriptInterpreterPythonImpl *python_interpreter = + static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); if (!script_interpreter) return StructuredData::ObjectSP(); @@ -1861,7 +1874,7 @@ Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_thread_plan_script( + ret_val = LLDBSwigPythonCreateScriptedThreadPlan( class_name, python_interpreter->m_dictionary_name.c_str(), thread_plan_sp); } @@ -1869,7 +1882,7 @@ return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); } -bool ScriptInterpreterPython::ScriptedThreadPlanExplainsStop( +bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop( StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { bool explains_stop = true; StructuredData::Generic *generic = nullptr; @@ -1878,7 +1891,7 @@ if (generic) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - explains_stop = g_swig_call_thread_plan( + explains_stop = LLDBSWIGPythonCallThreadPlan( generic->GetValue(), "explains_stop", event, script_error); if (script_error) return true; @@ -1886,7 +1899,7 @@ return explains_stop; } -bool ScriptInterpreterPython::ScriptedThreadPlanShouldStop( +bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop( StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { bool should_stop = true; StructuredData::Generic *generic = nullptr; @@ -1895,15 +1908,15 @@ if (generic) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - should_stop = g_swig_call_thread_plan(generic->GetValue(), "should_stop", - event, script_error); + should_stop = LLDBSWIGPythonCallThreadPlan( + generic->GetValue(), "should_stop", event, script_error); if (script_error) return true; } return should_stop; } -bool ScriptInterpreterPython::ScriptedThreadPlanIsStale( +bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale( StructuredData::ObjectSP implementor_sp, bool &script_error) { bool is_stale = true; StructuredData::Generic *generic = nullptr; @@ -1912,15 +1925,15 @@ if (generic) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - is_stale = g_swig_call_thread_plan(generic->GetValue(), "is_stale", nullptr, - script_error); + is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale", + nullptr, script_error); if (script_error) return true; } return is_stale; } -lldb::StateType ScriptInterpreterPython::ScriptedThreadPlanGetRunState( +lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState( StructuredData::ObjectSP implementor_sp, bool &script_error) { bool should_step = false; StructuredData::Generic *generic = nullptr; @@ -1929,8 +1942,8 @@ if (generic) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - should_step = g_swig_call_thread_plan(generic->GetValue(), "should_step", - NULL, script_error); + should_step = LLDBSWIGPythonCallThreadPlan( + generic->GetValue(), "should_step", nullptr, script_error); if (script_error) should_step = true; } @@ -1941,11 +1954,10 @@ } StructuredData::GenericSP -ScriptInterpreterPython::CreateScriptedBreakpointResolver( - const char *class_name, - StructuredDataImpl *args_data, +ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver( + const char *class_name, StructuredDataImpl *args_data, lldb::BreakpointSP &bkpt_sp) { - + if (class_name == nullptr || class_name[0] == '\0') return StructuredData::GenericSP(); @@ -1953,10 +1965,9 @@ return StructuredData::GenericSP(); Debugger &debugger = bkpt_sp->GetTarget().GetDebugger(); - ScriptInterpreter *script_interpreter = - debugger.GetCommandInterpreter().GetScriptInterpreter(); - ScriptInterpreterPython *python_interpreter = - static_cast<ScriptInterpreterPython *>(script_interpreter); + ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); + ScriptInterpreterPythonImpl *python_interpreter = + static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); if (!script_interpreter) return StructuredData::GenericSP(); @@ -1967,26 +1978,23 @@ Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_bkpt_resolver_script( - class_name, python_interpreter->m_dictionary_name.c_str(), - args_data, bkpt_sp); + ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver( + class_name, python_interpreter->m_dictionary_name.c_str(), args_data, + bkpt_sp); } return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); } -bool -ScriptInterpreterPython::ScriptedBreakpointResolverSearchCallback( - StructuredData::GenericSP implementor_sp, - SymbolContext *sym_ctx) { +bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback( + StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) { bool should_continue = false; - + if (implementor_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - should_continue - = g_swig_call_bkpt_resolver(implementor_sp->GetValue(), "__callback__", - sym_ctx); + should_continue = LLDBSwigPythonCallBreakpointResolver( + implementor_sp->GetValue(), "__callback__", sym_ctx); if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); @@ -1996,14 +2004,14 @@ } lldb::SearchDepth -ScriptInterpreterPython::ScriptedBreakpointResolverSearchDepth( +ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth( StructuredData::GenericSP implementor_sp) { int depth_as_int = lldb::eSearchDepthModule; if (implementor_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - depth_as_int - = g_swig_call_bkpt_resolver(implementor_sp->GetValue(), "__get_depth__", nullptr); + depth_as_int = LLDBSwigPythonCallBreakpointResolver( + implementor_sp->GetValue(), "__get_depth__", nullptr); if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); @@ -2013,14 +2021,14 @@ return lldb::eSearchDepthModule; if (depth_as_int <= lldb::kLastSearchDepthKind) - return (lldb::SearchDepth) depth_as_int; + return (lldb::SearchDepth)depth_as_int; else return lldb::eSearchDepthModule; } StructuredData::ObjectSP -ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec, - lldb_private::Status &error) { +ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, + lldb_private::Status &error) { if (!FileSystem::Instance().Exists(file_spec)) { error.SetErrorString("no such file"); return StructuredData::ObjectSP(); @@ -2035,11 +2043,10 @@ return StructuredData::ObjectSP(); } -StructuredData::DictionarySP ScriptInterpreterPython::GetDynamicSettings( +StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, lldb_private::Status &error) { - if (!plugin_module_sp || !target || !setting_name || !setting_name[0] || - !g_swig_plugin_get) + if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) return StructuredData::DictionarySP(); StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); if (!generic) @@ -2050,15 +2057,15 @@ Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); TargetSP target_sp(target->shared_from_this()); reply_pyobj.Reset(PyRefType::Owned, - (PyObject *)g_swig_plugin_get(generic->GetValue(), - setting_name, target_sp)); + (PyObject *)LLDBSWIGPython_GetDynamicSetting( + generic->GetValue(), setting_name, target_sp)); PythonDictionary py_dict(PyRefType::Borrowed, reply_pyobj.get()); return py_dict.CreateStructuredDictionary(); } StructuredData::ObjectSP -ScriptInterpreterPython::CreateSyntheticScriptedProvider( +ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( const char *class_name, lldb::ValueObjectSP valobj) { if (class_name == nullptr || class_name[0] == '\0') return StructuredData::ObjectSP(); @@ -2073,10 +2080,9 @@ return StructuredData::ObjectSP(); Debugger &debugger = target->GetDebugger(); - ScriptInterpreter *script_interpreter = - debugger.GetCommandInterpreter().GetScriptInterpreter(); - ScriptInterpreterPython *python_interpreter = - (ScriptInterpreterPython *)script_interpreter; + ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); + ScriptInterpreterPythonImpl *python_interpreter = + (ScriptInterpreterPythonImpl *)script_interpreter; if (!script_interpreter) return StructuredData::ObjectSP(); @@ -2086,7 +2092,7 @@ { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_synthetic_script( + ret_val = LLDBSwigPythonCreateSyntheticProvider( class_name, python_interpreter->m_dictionary_name.c_str(), valobj); } @@ -2094,9 +2100,8 @@ } StructuredData::GenericSP -ScriptInterpreterPython::CreateScriptCommandObject(const char *class_name) { - DebuggerSP debugger_sp( - GetCommandInterpreter().GetDebugger().shared_from_this()); +ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { + DebuggerSP debugger_sp(m_debugger.shared_from_this()); if (class_name == nullptr || class_name[0] == '\0') return StructuredData::GenericSP(); @@ -2109,29 +2114,28 @@ { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = - g_swig_create_cmd(class_name, m_dictionary_name.c_str(), debugger_sp); + ret_val = LLDBSwigPythonCreateCommandObject( + class_name, m_dictionary_name.c_str(), debugger_sp); } return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); } -bool ScriptInterpreterPython::GenerateTypeScriptFunction( +bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( const char *oneliner, std::string &output, const void *name_token) { StringList input; input.SplitIntoLines(oneliner, strlen(oneliner)); return GenerateTypeScriptFunction(input, output, name_token); } -bool ScriptInterpreterPython::GenerateTypeSynthClass(const char *oneliner, - std::string &output, - const void *name_token) { +bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( + const char *oneliner, std::string &output, const void *name_token) { StringList input; input.SplitIntoLines(oneliner, strlen(oneliner)); return GenerateTypeSynthClass(input, output, name_token); } -Status ScriptInterpreterPython::GenerateBreakpointCommandCallbackData( +Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( StringList &user_input, std::string &output) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); @@ -2156,7 +2160,7 @@ return error; } -bool ScriptInterpreterPython::GenerateWatchpointCommandCallbackData( +bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( StringList &user_input, std::string &output) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); @@ -2178,7 +2182,7 @@ return true; } -bool ScriptInterpreterPython::GetScriptedSummary( +bool ScriptInterpreterPythonImpl::GetScriptedSummary( const char *python_function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, std::string &retval) { @@ -2208,9 +2212,9 @@ { TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); - static Timer::Category func_cat("g_swig_typescript_callback"); - Timer scoped_timer(func_cat, "g_swig_typescript_callback"); - ret_val = g_swig_typescript_callback( + static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); + Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); + ret_val = LLDBSwigPythonCallTypeScript( python_function_name, GetSessionDictionary().get(), valobj, &new_callee, options_sp, retval); } @@ -2221,16 +2225,15 @@ } if (new_callee && old_callee != new_callee) - callee_wrapper_sp.reset(new StructuredPythonObject(new_callee)); + callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee); return ret_val; } -void ScriptInterpreterPython::Clear() { +void ScriptInterpreterPythonImpl::Clear() { // Release any global variables that might have strong references to // LLDB objects when clearing the python script interpreter. - Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock, - ScriptInterpreterPython::Locker::FreeAcquiredLock); + Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); // This may be called as part of Py_Finalize. In that case the modules are // destroyed in random order and we can't guarantee that we can access these. @@ -2239,7 +2242,7 @@ "= None; lldb.thread = None; lldb.frame = None"); } -bool ScriptInterpreterPython::BreakpointCallbackFunction( +bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { CommandDataPython *bp_option_data = (CommandDataPython *)baton; @@ -2255,10 +2258,9 @@ return true; Debugger &debugger = target->GetDebugger(); - ScriptInterpreter *script_interpreter = - debugger.GetCommandInterpreter().GetScriptInterpreter(); - ScriptInterpreterPython *python_interpreter = - (ScriptInterpreterPython *)script_interpreter; + ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); + ScriptInterpreterPythonImpl *python_interpreter = + (ScriptInterpreterPythonImpl *)script_interpreter; if (!script_interpreter) return true; @@ -2276,7 +2278,7 @@ Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_breakpoint_callback( + ret_val = LLDBSwigPythonBreakpointCallbackFunction( python_function_name, python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, bp_loc_sp); @@ -2290,7 +2292,7 @@ return true; } -bool ScriptInterpreterPython::WatchpointCallbackFunction( +bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( void *baton, StoppointCallbackContext *context, user_id_t watch_id) { WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *)baton; @@ -2306,10 +2308,9 @@ return true; Debugger &debugger = target->GetDebugger(); - ScriptInterpreter *script_interpreter = - debugger.GetCommandInterpreter().GetScriptInterpreter(); - ScriptInterpreterPython *python_interpreter = - (ScriptInterpreterPython *)script_interpreter; + ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); + ScriptInterpreterPythonImpl *python_interpreter = + (ScriptInterpreterPythonImpl *)script_interpreter; if (!script_interpreter) return true; @@ -2324,7 +2325,7 @@ Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_watchpoint_callback( + ret_val = LLDBSwigPythonWatchpointCallbackFunction( python_function_name, python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, wp_sp); @@ -2338,7 +2339,7 @@ return true; } -size_t ScriptInterpreterPython::CalculateNumChildren( +size_t ScriptInterpreterPythonImpl::CalculateNumChildren( const StructuredData::ObjectSP &implementor_sp, uint32_t max) { if (!implementor_sp) return 0; @@ -2349,21 +2350,18 @@ if (!implementor) return 0; - if (!g_swig_calc_children) - return 0; - size_t ret_val = 0; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_calc_children(implementor, max); + ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max); } return ret_val; } -lldb::ValueObjectSP ScriptInterpreterPython::GetChildAtIndex( +lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { if (!implementor_sp) return lldb::ValueObjectSP(); @@ -2375,22 +2373,18 @@ if (!implementor) return lldb::ValueObjectSP(); - if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue) - return lldb::ValueObjectSP(); - lldb::ValueObjectSP ret_val; - { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - void *child_ptr = g_swig_get_child_index(implementor, idx); + void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx); if (child_ptr != nullptr && child_ptr != Py_None) { lldb::SBValue *sb_value_ptr = - (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr); + (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); if (sb_value_ptr == nullptr) Py_XDECREF(child_ptr); else - ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr); + ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); } else { Py_XDECREF(child_ptr); } @@ -2399,7 +2393,7 @@ return ret_val; } -int ScriptInterpreterPython::GetIndexOfChildWithName( +int ScriptInterpreterPythonImpl::GetIndexOfChildWithName( const StructuredData::ObjectSP &implementor_sp, const char *child_name) { if (!implementor_sp) return UINT32_MAX; @@ -2411,21 +2405,18 @@ if (!implementor) return UINT32_MAX; - if (!g_swig_get_index_child) - return UINT32_MAX; - int ret_val = UINT32_MAX; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_get_index_child(implementor, child_name); + ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); } return ret_val; } -bool ScriptInterpreterPython::UpdateSynthProviderInstance( +bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( const StructuredData::ObjectSP &implementor_sp) { bool ret_val = false; @@ -2439,19 +2430,16 @@ if (!implementor) return ret_val; - if (!g_swig_update_provider) - return ret_val; - { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_update_provider(implementor); + ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor); } return ret_val; } -bool ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance( +bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( const StructuredData::ObjectSP &implementor_sp) { bool ret_val = false; @@ -2465,19 +2453,17 @@ if (!implementor) return ret_val; - if (!g_swig_mighthavechildren_provider) - return ret_val; - { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_mighthavechildren_provider(implementor); + ret_val = + LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor); } return ret_val; } -lldb::ValueObjectSP ScriptInterpreterPython::GetSyntheticValue( +lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( const StructuredData::ObjectSP &implementor_sp) { lldb::ValueObjectSP ret_val(nullptr); @@ -2491,21 +2477,17 @@ if (!implementor) return ret_val; - if (!g_swig_getvalue_provider || !g_swig_cast_to_sbvalue || - !g_swig_get_valobj_sp_from_sbvalue) - return ret_val; - { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - void *child_ptr = g_swig_getvalue_provider(implementor); + void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor); if (child_ptr != nullptr && child_ptr != Py_None) { lldb::SBValue *sb_value_ptr = - (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr); + (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); if (sb_value_ptr == nullptr) Py_XDECREF(child_ptr); else - ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr); + ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); } else { Py_XDECREF(child_ptr); } @@ -2514,7 +2496,7 @@ return ret_val; } -ConstString ScriptInterpreterPython::GetSyntheticTypeName( +ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( const StructuredData::ObjectSP &implementor_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); @@ -2580,10 +2562,9 @@ return ret_val; } -bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, - Process *process, - std::string &output, - Status &error) { +bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( + const char *impl_function, Process *process, std::string &output, + Status &error) { bool ret_val; if (!process) { error.SetErrorString("no process"); @@ -2593,15 +2574,12 @@ error.SetErrorString("no function to execute"); return false; } - if (!g_swig_run_script_keyword_process) { - error.SetErrorString("internal helper function missing"); - return false; - } + { ProcessSP process_sp(process->shared_from_this()); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_run_script_keyword_process( + ret_val = LLDBSWIGPythonRunScriptKeywordProcess( impl_function, m_dictionary_name.c_str(), process_sp, output); if (!ret_val) error.SetErrorString("python script evaluation failed"); @@ -2609,10 +2587,9 @@ return ret_val; } -bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, - Thread *thread, - std::string &output, - Status &error) { +bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( + const char *impl_function, Thread *thread, std::string &output, + Status &error) { bool ret_val; if (!thread) { error.SetErrorString("no thread"); @@ -2622,15 +2599,12 @@ error.SetErrorString("no function to execute"); return false; } - if (!g_swig_run_script_keyword_thread) { - error.SetErrorString("internal helper function missing"); - return false; - } + { ThreadSP thread_sp(thread->shared_from_this()); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_run_script_keyword_thread( + ret_val = LLDBSWIGPythonRunScriptKeywordThread( impl_function, m_dictionary_name.c_str(), thread_sp, output); if (!ret_val) error.SetErrorString("python script evaluation failed"); @@ -2638,10 +2612,9 @@ return ret_val; } -bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, - Target *target, - std::string &output, - Status &error) { +bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( + const char *impl_function, Target *target, std::string &output, + Status &error) { bool ret_val; if (!target) { error.SetErrorString("no thread"); @@ -2651,15 +2624,12 @@ error.SetErrorString("no function to execute"); return false; } - if (!g_swig_run_script_keyword_target) { - error.SetErrorString("internal helper function missing"); - return false; - } + { TargetSP target_sp(target->shared_from_this()); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_run_script_keyword_target( + ret_val = LLDBSWIGPythonRunScriptKeywordTarget( impl_function, m_dictionary_name.c_str(), target_sp, output); if (!ret_val) error.SetErrorString("python script evaluation failed"); @@ -2667,10 +2637,9 @@ return ret_val; } -bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, - StackFrame *frame, - std::string &output, - Status &error) { +bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( + const char *impl_function, StackFrame *frame, std::string &output, + Status &error) { bool ret_val; if (!frame) { error.SetErrorString("no frame"); @@ -2680,15 +2649,12 @@ error.SetErrorString("no function to execute"); return false; } - if (!g_swig_run_script_keyword_frame) { - error.SetErrorString("internal helper function missing"); - return false; - } + { StackFrameSP frame_sp(frame->shared_from_this()); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_run_script_keyword_frame( + ret_val = LLDBSWIGPythonRunScriptKeywordFrame( impl_function, m_dictionary_name.c_str(), frame_sp, output); if (!ret_val) error.SetErrorString("python script evaluation failed"); @@ -2696,10 +2662,9 @@ return ret_val; } -bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, - ValueObject *value, - std::string &output, - Status &error) { +bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( + const char *impl_function, ValueObject *value, std::string &output, + Status &error) { bool ret_val; if (!value) { error.SetErrorString("no value"); @@ -2709,15 +2674,12 @@ error.SetErrorString("no function to execute"); return false; } - if (!g_swig_run_script_keyword_value) { - error.SetErrorString("internal helper function missing"); - return false; - } + { ValueObjectSP value_sp(value->GetSP()); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); - ret_val = g_swig_run_script_keyword_value( + ret_val = LLDBSWIGPythonRunScriptKeywordValue( impl_function, m_dictionary_name.c_str(), value_sp, output); if (!ret_val) error.SetErrorString("python script evaluation failed"); @@ -2737,7 +2699,7 @@ return matches; } -bool ScriptInterpreterPython::LoadScriptingModule( +bool ScriptInterpreterPythonImpl::LoadScriptingModule( const char *pathname, bool can_reload, bool init_session, lldb_private::Status &error, StructuredData::ObjectSP *module_sp) { if (!pathname || !pathname[0]) { @@ -2745,12 +2707,7 @@ return false; } - if (!g_swig_call_module_init) { - error.SetErrorString("internal helper function missing"); - return false; - } - - lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); + lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); { FileSpec target_file(pathname); @@ -2760,9 +2717,10 @@ StreamString command_stream; // Before executing Python code, lock the GIL. - Locker py_lock(this, Locker::AcquireLock | - (init_session ? Locker::InitSession : 0) | - Locker::NoSTDIN, + Locker py_lock(this, + Locker::AcquireLock | + (init_session ? Locker::InitSession : 0) | + Locker::NoSTDIN, Locker::FreeAcquiredLock | (init_session ? Locker::TearDownSession : 0)); namespace fs = llvm::sys::fs; @@ -2781,6 +2739,11 @@ basename = pathname; // not a filename, probably a package of some sort, // let it go through } else if (is_directory(st) || is_regular_file(st)) { + if (target_file.GetDirectory().IsEmpty()) { + error.SetErrorString("invalid directory name"); + return false; + } + std::string directory = target_file.GetDirectory().GetCString(); replace_all(directory, "\\", "\\\\"); replace_all(directory, "'", "\\'"); @@ -2823,7 +2786,7 @@ bool was_imported_globally = (ExecuteOneLineWithReturn( command_stream.GetData(), - ScriptInterpreterPython::eScriptReturnTypeBool, &does_contain, + ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, ScriptInterpreter::ExecuteScriptOptions() .SetEnableIO(false) .SetSetLLDBGlobals(false)) && @@ -2864,8 +2827,8 @@ // if we are here, everything worked // call __lldb_init_module(debugger,dict) - if (!g_swig_call_module_init(basename.c_str(), m_dictionary_name.c_str(), - debugger_sp)) { + if (!LLDBSwigPythonCallModuleInit(basename.c_str(), + m_dictionary_name.c_str(), debugger_sp)) { error.SetErrorString("calling __lldb_init_module failed"); return false; } @@ -2880,14 +2843,14 @@ ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj) && module_pyobj) - module_sp->reset(new StructuredPythonObject(module_pyobj)); + *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj); } return true; } } -bool ScriptInterpreterPython::IsReservedWord(const char *word) { +bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { if (!word || !word[0]) return false; @@ -2895,7 +2858,8 @@ // filter out a few characters that would just confuse us and that are // clearly not keyword material anyway - if (word_sr.find_first_of("'\"") != llvm::StringRef::npos) + if (word_sr.find('"') != llvm::StringRef::npos || + word_sr.find('\'') != llvm::StringRef::npos) return false; StreamString command_stream; @@ -2912,7 +2876,7 @@ return false; } -ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler( +ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), m_old_asynch(debugger_sp->GetAsyncExecution()) { @@ -2922,12 +2886,12 @@ m_debugger_sp->SetAsyncExecution(true); } -ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler() { +ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) m_debugger_sp->SetAsyncExecution(m_old_asynch); } -bool ScriptInterpreterPython::RunScriptBasedCommand( +bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( const char *impl_function, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, @@ -2937,12 +2901,7 @@ return false; } - if (!g_swig_call_command) { - error.SetErrorString("no helper function to run scripted commands"); - return false; - } - - lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); + lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); if (!debugger_sp.get()) { @@ -2963,9 +2922,9 @@ SynchronicityHandler synch_handler(debugger_sp, synchronicity); std::string args_str = args.str(); - ret_val = g_swig_call_command(impl_function, m_dictionary_name.c_str(), - debugger_sp, args_str.c_str(), cmd_retobj, - exe_ctx_ref_sp); + ret_val = LLDBSwigPythonCallCommand( + impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), + cmd_retobj, exe_ctx_ref_sp); } if (!ret_val) @@ -2976,7 +2935,7 @@ return ret_val; } -bool ScriptInterpreterPython::RunScriptBasedCommand( +bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, @@ -2986,12 +2945,7 @@ return false; } - if (!g_swig_call_command_object) { - error.SetErrorString("no helper function to run scripted commands"); - return false; - } - - lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); + lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); if (!debugger_sp.get()) { @@ -3012,9 +2966,9 @@ SynchronicityHandler synch_handler(debugger_sp, synchronicity); std::string args_str = args.str(); - ret_val = g_swig_call_command_object(impl_obj_sp->GetValue(), debugger_sp, - args_str.c_str(), cmd_retobj, - exe_ctx_ref_sp); + ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(), + debugger_sp, args_str.c_str(), + cmd_retobj, exe_ctx_ref_sp); } if (!ret_val) @@ -3028,8 +2982,8 @@ // in Python, a special attribute __doc__ contains the docstring for an object // (function, method, class, ...) if any is defined Otherwise, the attribute's // value is None -bool ScriptInterpreterPython::GetDocumentationForItem(const char *item, - std::string &dest) { +bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, + std::string &dest) { dest.clear(); if (!item || !*item) return false; @@ -3055,7 +3009,7 @@ } } -bool ScriptInterpreterPython::GetShortHelpForCommandObject( +bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( StructuredData::GenericSP cmd_obj_sp, std::string &dest) { bool got_string = false; dest.clear(); @@ -3111,7 +3065,7 @@ return got_string; } -uint32_t ScriptInterpreterPython::GetFlagsForCommandObject( +uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( StructuredData::GenericSP cmd_obj_sp) { uint32_t result = 0; @@ -3165,7 +3119,7 @@ return result; } -bool ScriptInterpreterPython::GetLongHelpForCommandObject( +bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( StructuredData::GenericSP cmd_obj_sp, std::string &dest) { bool got_string = false; dest.clear(); @@ -3224,78 +3178,14 @@ } std::unique_ptr<ScriptInterpreterLocker> -ScriptInterpreterPython::AcquireInterpreterLock() { +ScriptInterpreterPythonImpl::AcquireInterpreterLock() { std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, Locker::FreeLock | Locker::TearDownSession)); return py_lock; } -void ScriptInterpreterPython::InitializeInterpreter( - SWIGInitCallback swig_init_callback, - SWIGBreakpointCallbackFunction swig_breakpoint_callback, - SWIGWatchpointCallbackFunction swig_watchpoint_callback, - SWIGPythonTypeScriptCallbackFunction swig_typescript_callback, - SWIGPythonCreateSyntheticProvider swig_synthetic_script, - SWIGPythonCreateCommandObject swig_create_cmd, - SWIGPythonCalculateNumChildren swig_calc_children, - SWIGPythonGetChildAtIndex swig_get_child_index, - SWIGPythonGetIndexOfChildWithName swig_get_index_child, - SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue, - SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue, - SWIGPythonUpdateSynthProviderInstance swig_update_provider, - SWIGPythonMightHaveChildrenSynthProviderInstance - swig_mighthavechildren_provider, - SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider, - SWIGPythonCallCommand swig_call_command, - SWIGPythonCallCommandObject swig_call_command_object, - SWIGPythonCallModuleInit swig_call_module_init, - SWIGPythonCreateOSPlugin swig_create_os_plugin, - SWIGPythonCreateFrameRecognizer swig_create_frame_recognizer, - SWIGPythonGetRecognizedArguments swig_get_recognized_arguments, - SWIGPythonScriptKeyword_Process swig_run_script_keyword_process, - SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread, - SWIGPythonScriptKeyword_Target swig_run_script_keyword_target, - SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame, - SWIGPythonScriptKeyword_Value swig_run_script_keyword_value, - SWIGPython_GetDynamicSetting swig_plugin_get, - SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script, - SWIGPythonCallThreadPlan swig_call_thread_plan, - SWIGPythonCreateScriptedBreakpointResolver swig_bkpt_resolver_script, - SWIGPythonCallBreakpointResolver swig_call_bkpt_resolver) { - g_swig_init_callback = swig_init_callback; - g_swig_breakpoint_callback = swig_breakpoint_callback; - g_swig_watchpoint_callback = swig_watchpoint_callback; - g_swig_typescript_callback = swig_typescript_callback; - g_swig_synthetic_script = swig_synthetic_script; - g_swig_create_cmd = swig_create_cmd; - g_swig_calc_children = swig_calc_children; - g_swig_get_child_index = swig_get_child_index; - g_swig_get_index_child = swig_get_index_child; - g_swig_cast_to_sbvalue = swig_cast_to_sbvalue; - g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue; - g_swig_update_provider = swig_update_provider; - g_swig_mighthavechildren_provider = swig_mighthavechildren_provider; - g_swig_getvalue_provider = swig_getvalue_provider; - g_swig_call_command = swig_call_command; - g_swig_call_command_object = swig_call_command_object; - g_swig_call_module_init = swig_call_module_init; - g_swig_create_os_plugin = swig_create_os_plugin; - g_swig_create_frame_recognizer = swig_create_frame_recognizer; - g_swig_get_recognized_arguments = swig_get_recognized_arguments; - g_swig_run_script_keyword_process = swig_run_script_keyword_process; - g_swig_run_script_keyword_thread = swig_run_script_keyword_thread; - g_swig_run_script_keyword_target = swig_run_script_keyword_target; - g_swig_run_script_keyword_frame = swig_run_script_keyword_frame; - g_swig_run_script_keyword_value = swig_run_script_keyword_value; - g_swig_plugin_get = swig_plugin_get; - g_swig_thread_plan_script = swig_thread_plan_script; - g_swig_call_thread_plan = swig_call_thread_plan; - g_swig_bkpt_resolver_script = swig_bkpt_resolver_script; - g_swig_call_bkpt_resolver = swig_call_bkpt_resolver; -} - -void ScriptInterpreterPython::InitializePrivate() { +void ScriptInterpreterPythonImpl::InitializePrivate() { if (g_initialized) return; @@ -3310,8 +3200,7 @@ // initialization. InitializePythonRAII initialize_guard; - if (g_swig_init_callback) - g_swig_init_callback(); + LLDBSwigPyInit(); // Update the path python uses to search for modules to include the current // directory. @@ -3334,8 +3223,8 @@ "from lldb.embedded_interpreter import run_one_line"); } -void ScriptInterpreterPython::AddToSysPath(AddLocation location, - std::string path) { +void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, + std::string path) { std::string path_copy; std::string statement; @@ -3358,13 +3247,13 @@ // calls Py_Finalize, which calls all the 'at_exit' registered functions. // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, // which calls ScriptInterpreter::Terminate, which calls -// ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end -// up with Py_Finalize being called from within Py_Finalize, which results in a -// seg fault. Since this function only gets called when lldb is shutting down -// and going away anyway, the fact that we don't actually call Py_Finalize +// ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we +// end up with Py_Finalize being called from within Py_Finalize, which results +// in a seg fault. Since this function only gets called when lldb is shutting +// down and going away anyway, the fact that we don't actually call Py_Finalize // should not cause any problems (everything should shut down/go away anyway // when the process exits). // -// void ScriptInterpreterPython::Terminate() { Py_Finalize (); } +// void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } #endif // LLDB_DISABLE_PYTHON
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h index a047359..24941ec 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h
@@ -1,9 +1,8 @@ //===-- ScriptInterpreterPython.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,21 +15,17 @@ #else +#include "lldb/Breakpoint/BreakpointOptions.h" +#include "lldb/Core/IOHandler.h" +#include "lldb/Interpreter/ScriptInterpreter.h" +#include "lldb/lldb-private.h" + #include <memory> #include <string> #include <vector> -#include "PythonDataObjects.h" -#include "lldb/Breakpoint/BreakpointOptions.h" -#include "lldb/Core/IOHandler.h" -#include "lldb/Host/Terminal.h" -#include "lldb/Interpreter/ScriptInterpreter.h" -#include "lldb/lldb-private.h" - -class IOHandlerPythonInterpreter; - namespace lldb_private { - +/// Abstract interface for the Python script interpreter. class ScriptInterpreterPython : public ScriptInterpreter, public IOHandlerDelegateMultiline { public: @@ -41,570 +36,22 @@ } }; -#if PY_MAJOR_VERSION >= 3 - typedef PyObject *(*SWIGInitCallback)(void); -#else - typedef void (*SWIGInitCallback)(void); -#endif - - typedef bool (*SWIGBreakpointCallbackFunction)( - const char *python_function_name, const char *session_dictionary_name, - const lldb::StackFrameSP &frame_sp, - const lldb::BreakpointLocationSP &bp_loc_sp); - - typedef bool (*SWIGWatchpointCallbackFunction)( - const char *python_function_name, const char *session_dictionary_name, - const lldb::StackFrameSP &frame_sp, const lldb::WatchpointSP &wp_sp); - - typedef bool (*SWIGPythonTypeScriptCallbackFunction)( - const char *python_function_name, void *session_dictionary, - const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, - const lldb::TypeSummaryOptionsSP &options, std::string &retval); - - typedef void *(*SWIGPythonCreateSyntheticProvider)( - const char *python_class_name, const char *session_dictionary_name, - const lldb::ValueObjectSP &valobj_sp); - - typedef void *(*SWIGPythonCreateCommandObject)( - const char *python_class_name, const char *session_dictionary_name, - const lldb::DebuggerSP debugger_sp); - - typedef void *(*SWIGPythonCreateScriptedThreadPlan)( - const char *python_class_name, const char *session_dictionary_name, - const lldb::ThreadPlanSP &thread_plan_sp); - - typedef bool (*SWIGPythonCallThreadPlan)(void *implementor, - const char *method_name, - Event *event_sp, bool &got_error); - - typedef void *(*SWIGPythonCreateScriptedBreakpointResolver)( - const char *python_class_name, const char *session_dictionary_name, - lldb_private::StructuredDataImpl *args_impl, - lldb::BreakpointSP &bkpt_sp); - - typedef unsigned int (*SWIGPythonCallBreakpointResolver)(void *implementor, - const char *method_name, - lldb_private::SymbolContext *sym_ctx); - - typedef void *(*SWIGPythonCreateOSPlugin)(const char *python_class_name, - const char *session_dictionary_name, - const lldb::ProcessSP &process_sp); - - typedef void *(*SWIGPythonCreateFrameRecognizer)( - const char *python_class_name, const char *session_dictionary_name); - - typedef void *(*SWIGPythonGetRecognizedArguments)( - void *implementor, const lldb::StackFrameSP &frame_sp); - - typedef size_t (*SWIGPythonCalculateNumChildren)(void *implementor, - uint32_t max); - - typedef void *(*SWIGPythonGetChildAtIndex)(void *implementor, uint32_t idx); - - typedef int (*SWIGPythonGetIndexOfChildWithName)(void *implementor, - const char *child_name); - - typedef void *(*SWIGPythonCastPyObjectToSBValue)(void *data); - - typedef lldb::ValueObjectSP (*SWIGPythonGetValueObjectSPFromSBValue)( - void *data); - - typedef bool (*SWIGPythonUpdateSynthProviderInstance)(void *data); - - typedef bool (*SWIGPythonMightHaveChildrenSynthProviderInstance)(void *data); - - typedef void *(*SWIGPythonGetValueSynthProviderInstance)(void *implementor); - - typedef bool (*SWIGPythonCallCommand)( - const char *python_function_name, const char *session_dictionary_name, - lldb::DebuggerSP &debugger, const char *args, - lldb_private::CommandReturnObject &cmd_retobj, - lldb::ExecutionContextRefSP exe_ctx_ref_sp); - - typedef bool (*SWIGPythonCallCommandObject)( - void *implementor, lldb::DebuggerSP &debugger, const char *args, - lldb_private::CommandReturnObject &cmd_retobj, - lldb::ExecutionContextRefSP exe_ctx_ref_sp); - - typedef bool (*SWIGPythonCallModuleInit)(const char *python_module_name, - const char *session_dictionary_name, - lldb::DebuggerSP &debugger); - - typedef bool (*SWIGPythonScriptKeyword_Process)( - const char *python_function_name, const char *session_dictionary_name, - lldb::ProcessSP &process, std::string &output); - - typedef bool (*SWIGPythonScriptKeyword_Thread)( - const char *python_function_name, const char *session_dictionary_name, - lldb::ThreadSP &thread, std::string &output); - - typedef bool (*SWIGPythonScriptKeyword_Target)( - const char *python_function_name, const char *session_dictionary_name, - lldb::TargetSP &target, std::string &output); - - typedef bool (*SWIGPythonScriptKeyword_Frame)( - const char *python_function_name, const char *session_dictionary_name, - lldb::StackFrameSP &frame, std::string &output); - - typedef bool (*SWIGPythonScriptKeyword_Value)( - const char *python_function_name, const char *session_dictionary_name, - lldb::ValueObjectSP &value, std::string &output); - - typedef void *(*SWIGPython_GetDynamicSetting)( - void *module, const char *setting, const lldb::TargetSP &target_sp); - - friend class ::IOHandlerPythonInterpreter; - - ScriptInterpreterPython(CommandInterpreter &interpreter); - - ~ScriptInterpreterPython() override; - - bool Interrupt() override; - - bool ExecuteOneLine( - llvm::StringRef command, CommandReturnObject *result, - const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; - - void ExecuteInterpreterLoop() override; - - bool ExecuteOneLineWithReturn( - llvm::StringRef in_string, - ScriptInterpreter::ScriptReturnType return_type, void *ret_value, - const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; - - lldb_private::Status ExecuteMultipleLines( - const char *in_string, - const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; - - Status - ExportFunctionDefinitionToInterpreter(StringList &function_def) override; - - bool GenerateTypeScriptFunction(StringList &input, std::string &output, - const void *name_token = nullptr) override; - - bool GenerateTypeSynthClass(StringList &input, std::string &output, - const void *name_token = nullptr) override; - - bool GenerateTypeSynthClass(const char *oneliner, std::string &output, - const void *name_token = nullptr) override; - - // use this if the function code is just a one-liner script - bool GenerateTypeScriptFunction(const char *oneliner, std::string &output, - const void *name_token = nullptr) override; - - bool GenerateScriptAliasFunction(StringList &input, - std::string &output) override; - - StructuredData::ObjectSP - CreateSyntheticScriptedProvider(const char *class_name, - lldb::ValueObjectSP valobj) override; - - StructuredData::GenericSP - CreateScriptCommandObject(const char *class_name) override; - - StructuredData::ObjectSP - CreateScriptedThreadPlan(const char *class_name, - lldb::ThreadPlanSP thread_plan) override; - - bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp, - Event *event, - bool &script_error) override; - - bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp, - Event *event, bool &script_error) override; - - bool ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp, - bool &script_error) override; - - lldb::StateType - ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp, - bool &script_error) override; - - StructuredData::GenericSP - CreateScriptedBreakpointResolver(const char *class_name, - StructuredDataImpl *args_data, - lldb::BreakpointSP &bkpt_sp) override; - bool - ScriptedBreakpointResolverSearchCallback(StructuredData::GenericSP - implementor_sp, - SymbolContext *sym_ctx) override; - - lldb::SearchDepth - ScriptedBreakpointResolverSearchDepth(StructuredData::GenericSP - implementor_sp) override; - - StructuredData::GenericSP - CreateFrameRecognizer(const char *class_name) override; - - lldb::ValueObjectListSP - GetRecognizedArguments(const StructuredData::ObjectSP &implementor, - lldb::StackFrameSP frame_sp) override; - - StructuredData::GenericSP - OSPlugin_CreatePluginObject(const char *class_name, - lldb::ProcessSP process_sp) override; - - StructuredData::DictionarySP - OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override; - - StructuredData::ArraySP - OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override; - - StructuredData::StringSP - OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp, - lldb::tid_t thread_id) override; - - StructuredData::DictionarySP - OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp, - lldb::tid_t tid, lldb::addr_t context) override; - - StructuredData::ObjectSP - LoadPluginModule(const FileSpec &file_spec, - lldb_private::Status &error) override; - - StructuredData::DictionarySP - GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, - const char *setting_name, - lldb_private::Status &error) override; - - size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, - uint32_t max) override; - - lldb::ValueObjectSP - GetChildAtIndex(const StructuredData::ObjectSP &implementor, - uint32_t idx) override; - - int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, - const char *child_name) override; - - bool UpdateSynthProviderInstance( - const StructuredData::ObjectSP &implementor) override; - - bool MightHaveChildrenSynthProviderInstance( - const StructuredData::ObjectSP &implementor) override; - - lldb::ValueObjectSP - GetSyntheticValue(const StructuredData::ObjectSP &implementor) override; - - ConstString - GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override; - - bool - RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, - ScriptedCommandSynchronicity synchronicity, - lldb_private::CommandReturnObject &cmd_retobj, - Status &error, - const lldb_private::ExecutionContext &exe_ctx) override; - - bool RunScriptBasedCommand( - StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, - ScriptedCommandSynchronicity synchronicity, - lldb_private::CommandReturnObject &cmd_retobj, Status &error, - const lldb_private::ExecutionContext &exe_ctx) override; - - Status GenerateFunction(const char *signature, - const StringList &input) override; - - Status GenerateBreakpointCommandCallbackData(StringList &input, - std::string &output) override; - - bool GenerateWatchpointCommandCallbackData(StringList &input, - std::string &output) override; - - // static size_t - // GenerateBreakpointOptionsCommandCallback (void *baton, - // InputReader &reader, - // lldb::InputReaderAction - // notification, - // const char *bytes, - // size_t bytes_len); - // - // static size_t - // GenerateWatchpointOptionsCommandCallback (void *baton, - // InputReader &reader, - // lldb::InputReaderAction - // notification, - // const char *bytes, - // size_t bytes_len); - - static bool BreakpointCallbackFunction(void *baton, - StoppointCallbackContext *context, - lldb::user_id_t break_id, - lldb::user_id_t break_loc_id); - - static bool WatchpointCallbackFunction(void *baton, - StoppointCallbackContext *context, - lldb::user_id_t watch_id); - - bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, - StructuredData::ObjectSP &callee_wrapper_sp, - const TypeSummaryOptions &options, - std::string &retval) override; - - void Clear() override; - - bool GetDocumentationForItem(const char *item, std::string &dest) override; - - bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, - std::string &dest) override; - - uint32_t - GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override; - - bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, - std::string &dest) override; - - bool CheckObjectExists(const char *name) override { - if (!name || !name[0]) - return false; - std::string temp; - return GetDocumentationForItem(name, temp); - } - - bool RunScriptFormatKeyword(const char *impl_function, Process *process, - std::string &output, Status &error) override; - - bool RunScriptFormatKeyword(const char *impl_function, Thread *thread, - std::string &output, Status &error) override; - - bool RunScriptFormatKeyword(const char *impl_function, Target *target, - std::string &output, Status &error) override; - - bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame, - std::string &output, Status &error) override; - - bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value, - std::string &output, Status &error) override; - - bool - LoadScriptingModule(const char *filename, bool can_reload, bool init_session, - lldb_private::Status &error, - StructuredData::ObjectSP *module_sp = nullptr) override; - - bool IsReservedWord(const char *word) override; - - std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override; - - void CollectDataForBreakpointCommandCallback( - std::vector<BreakpointOptions *> &bp_options_vec, - CommandReturnObject &result) override; - - void - CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, - CommandReturnObject &result) override; - - /// Set the callback body text into the callback for the breakpoint. - Status SetBreakpointCommandCallback(BreakpointOptions *bp_options, - const char *callback_body) override; - - void SetBreakpointCommandCallbackFunction(BreakpointOptions *bp_options, - const char *function_name) override; - - /// This one is for deserialization: - Status SetBreakpointCommandCallback( - BreakpointOptions *bp_options, - std::unique_ptr<BreakpointOptions::CommandData> &data_up) override; - - /// Set a one-liner as the callback for the watchpoint. - void SetWatchpointCommandCallback(WatchpointOptions *wp_options, - const char *oneliner) override; - - StringList ReadCommandInputFromUser(FILE *in_file); - - void ResetOutputFileHandle(FILE *new_fh) override; - - static void InitializePrivate(); - - static void InitializeInterpreter( - SWIGInitCallback python_swig_init_callback, - SWIGBreakpointCallbackFunction swig_breakpoint_callback, - SWIGWatchpointCallbackFunction swig_watchpoint_callback, - SWIGPythonTypeScriptCallbackFunction swig_typescript_callback, - SWIGPythonCreateSyntheticProvider swig_synthetic_script, - SWIGPythonCreateCommandObject swig_create_cmd, - SWIGPythonCalculateNumChildren swig_calc_children, - SWIGPythonGetChildAtIndex swig_get_child_index, - SWIGPythonGetIndexOfChildWithName swig_get_index_child, - SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue, - SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue, - SWIGPythonUpdateSynthProviderInstance swig_update_provider, - SWIGPythonMightHaveChildrenSynthProviderInstance - swig_mighthavechildren_provider, - SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider, - SWIGPythonCallCommand swig_call_command, - SWIGPythonCallCommandObject swig_call_command_object, - SWIGPythonCallModuleInit swig_call_module_init, - SWIGPythonCreateOSPlugin swig_create_os_plugin, - SWIGPythonCreateFrameRecognizer swig_create_frame_recognizer, - SWIGPythonGetRecognizedArguments swig_get_recognized_arguments, - SWIGPythonScriptKeyword_Process swig_run_script_keyword_process, - SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread, - SWIGPythonScriptKeyword_Target swig_run_script_keyword_target, - SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame, - SWIGPythonScriptKeyword_Value swig_run_script_keyword_value, - SWIGPython_GetDynamicSetting swig_plugin_get, - SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script, - SWIGPythonCallThreadPlan swig_call_thread_plan, - SWIGPythonCreateScriptedBreakpointResolver swig_bkpt_resolver_script, - SWIGPythonCallBreakpointResolver swig_call_breakpoint_resolver); - - const char *GetDictionaryName() { return m_dictionary_name.c_str(); } - - PyThreadState *GetThreadState() { return m_command_thread_state; } - - void SetThreadState(PyThreadState *s) { - if (s) - m_command_thread_state = s; - } - - //---------------------------------------------------------------------- - // IOHandlerDelegate - //---------------------------------------------------------------------- - void IOHandlerActivated(IOHandler &io_handler) override; - - void IOHandlerInputComplete(IOHandler &io_handler, - std::string &data) override; + ScriptInterpreterPython(Debugger &debugger) + : ScriptInterpreter(debugger, lldb::eScriptLanguagePython), + IOHandlerDelegateMultiline("DONE") {} - //------------------------------------------------------------------ - // Static Functions - //------------------------------------------------------------------ static void Initialize(); - static void Terminate(); - - static lldb::ScriptInterpreterSP - CreateInstance(CommandInterpreter &interpreter); - static lldb_private::ConstString GetPluginNameStatic(); - static const char *GetPluginDescriptionStatic(); - static FileSpec GetPythonDir(); - //------------------------------------------------------------------ - // PluginInterface protocol - //------------------------------------------------------------------ - lldb_private::ConstString GetPluginName() override; - - uint32_t GetPluginVersion() override; - - class Locker : public ScriptInterpreterLocker { - public: - enum OnEntry { - AcquireLock = 0x0001, - InitSession = 0x0002, - InitGlobals = 0x0004, - NoSTDIN = 0x0008 - }; - - enum OnLeave { - FreeLock = 0x0001, - FreeAcquiredLock = 0x0002, // do not free the lock if we already held it - // when calling constructor - TearDownSession = 0x0004 - }; - - Locker(ScriptInterpreterPython *py_interpreter = nullptr, - uint16_t on_entry = AcquireLock | InitSession, - uint16_t on_leave = FreeLock | TearDownSession, FILE *in = nullptr, - FILE *out = nullptr, FILE *err = nullptr); - - ~Locker() override; - - private: - bool DoAcquireLock(); - - bool DoInitSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err); - - bool DoFreeLock(); - - bool DoTearDownSession(); - - static void ReleasePythonLock(); - - bool m_teardown_session; - ScriptInterpreterPython *m_python_interpreter; - // FILE* m_tmp_fh; - PyGILState_STATE m_GILState; - }; - protected: - class SynchronicityHandler { - private: - lldb::DebuggerSP m_debugger_sp; - ScriptedCommandSynchronicity m_synch_wanted; - bool m_old_asynch; - - public: - SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity); - - ~SynchronicityHandler(); - }; - - enum class AddLocation { Beginning, End }; - - static void AddToSysPath(AddLocation location, std::string path); - static void ComputePythonDirForApple(llvm::SmallVectorImpl<char> &path); static void ComputePythonDirForPosix(llvm::SmallVectorImpl<char> &path); static void ComputePythonDirForWindows(llvm::SmallVectorImpl<char> &path); - - bool EnterSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err); - - void LeaveSession(); - - void SaveTerminalState(int fd); - - void RestoreTerminalState(); - - uint32_t IsExecutingPython() const { return m_lock_count > 0; } - - uint32_t IncrementLockCount() { return ++m_lock_count; } - - uint32_t DecrementLockCount() { - if (m_lock_count > 0) - --m_lock_count; - return m_lock_count; - } - - enum ActiveIOHandler { - eIOHandlerNone, - eIOHandlerBreakpoint, - eIOHandlerWatchpoint - }; - - PythonObject &GetMainModule(); - - PythonDictionary &GetSessionDictionary(); - - PythonDictionary &GetSysModuleDictionary(); - - bool GetEmbeddedInterpreterModuleObjects(); - - bool SetStdHandle(File &file, const char *py_name, PythonFile &save_file, - const char *mode); - - PythonFile m_saved_stdin; - PythonFile m_saved_stdout; - PythonFile m_saved_stderr; - PythonObject m_main_module; - PythonObject m_lldb_module; - PythonDictionary m_session_dict; - PythonDictionary m_sys_module_dict; - PythonObject m_run_one_line_function; - PythonObject m_run_one_line_str_global; - std::string m_dictionary_name; - TerminalState m_terminal_state; - ActiveIOHandler m_active_io_handler; - bool m_session_is_active; - bool m_pty_slave_is_open; - bool m_valid_session; - uint32_t m_lock_count; - PyThreadState *m_command_thread_state; }; - } // namespace lldb_private #endif // LLDB_DISABLE_PYTHON - #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h new file mode 100644 index 0000000..a9993c4 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h
@@ -0,0 +1,473 @@ +//===-- ScriptInterpreterPythonImpl.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 +// +//===----------------------------------------------------------------------===// + +#ifdef LLDB_DISABLE_PYTHON + +// Python is disabled in this build + +#else + +#include "lldb-python.h" + +#include "PythonDataObjects.h" +#include "ScriptInterpreterPython.h" + +#include "lldb/Host/Terminal.h" +#include "lldb/Utility/StreamString.h" + +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringRef.h" + +namespace lldb_private { +class IOHandlerPythonInterpreter; +class ScriptInterpreterPythonImpl : public ScriptInterpreterPython { +public: + friend class IOHandlerPythonInterpreter; + + ScriptInterpreterPythonImpl(Debugger &debugger); + + ~ScriptInterpreterPythonImpl() override; + + bool Interrupt() override; + + bool ExecuteOneLine( + llvm::StringRef command, CommandReturnObject *result, + const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; + + void ExecuteInterpreterLoop() override; + + bool ExecuteOneLineWithReturn( + llvm::StringRef in_string, + ScriptInterpreter::ScriptReturnType return_type, void *ret_value, + const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; + + lldb_private::Status ExecuteMultipleLines( + const char *in_string, + const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; + + Status + ExportFunctionDefinitionToInterpreter(StringList &function_def) override; + + bool GenerateTypeScriptFunction(StringList &input, std::string &output, + const void *name_token = nullptr) override; + + bool GenerateTypeSynthClass(StringList &input, std::string &output, + const void *name_token = nullptr) override; + + bool GenerateTypeSynthClass(const char *oneliner, std::string &output, + const void *name_token = nullptr) override; + + // use this if the function code is just a one-liner script + bool GenerateTypeScriptFunction(const char *oneliner, std::string &output, + const void *name_token = nullptr) override; + + bool GenerateScriptAliasFunction(StringList &input, + std::string &output) override; + + StructuredData::ObjectSP + CreateSyntheticScriptedProvider(const char *class_name, + lldb::ValueObjectSP valobj) override; + + StructuredData::GenericSP + CreateScriptCommandObject(const char *class_name) override; + + StructuredData::ObjectSP + CreateScriptedThreadPlan(const char *class_name, + lldb::ThreadPlanSP thread_plan) override; + + bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp, + Event *event, + bool &script_error) override; + + bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp, + Event *event, bool &script_error) override; + + bool ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp, + bool &script_error) override; + + lldb::StateType + ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp, + bool &script_error) override; + + StructuredData::GenericSP + CreateScriptedBreakpointResolver(const char *class_name, + StructuredDataImpl *args_data, + lldb::BreakpointSP &bkpt_sp) override; + bool ScriptedBreakpointResolverSearchCallback( + StructuredData::GenericSP implementor_sp, + SymbolContext *sym_ctx) override; + + lldb::SearchDepth ScriptedBreakpointResolverSearchDepth( + StructuredData::GenericSP implementor_sp) override; + + StructuredData::GenericSP + CreateFrameRecognizer(const char *class_name) override; + + lldb::ValueObjectListSP + GetRecognizedArguments(const StructuredData::ObjectSP &implementor, + lldb::StackFrameSP frame_sp) override; + + StructuredData::GenericSP + OSPlugin_CreatePluginObject(const char *class_name, + lldb::ProcessSP process_sp) override; + + StructuredData::DictionarySP + OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override; + + StructuredData::ArraySP + OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override; + + StructuredData::StringSP + OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp, + lldb::tid_t thread_id) override; + + StructuredData::DictionarySP + OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp, + lldb::tid_t tid, lldb::addr_t context) override; + + StructuredData::ObjectSP + LoadPluginModule(const FileSpec &file_spec, + lldb_private::Status &error) override; + + StructuredData::DictionarySP + GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, + const char *setting_name, + lldb_private::Status &error) override; + + size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, + uint32_t max) override; + + lldb::ValueObjectSP + GetChildAtIndex(const StructuredData::ObjectSP &implementor, + uint32_t idx) override; + + int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, + const char *child_name) override; + + bool UpdateSynthProviderInstance( + const StructuredData::ObjectSP &implementor) override; + + bool MightHaveChildrenSynthProviderInstance( + const StructuredData::ObjectSP &implementor) override; + + lldb::ValueObjectSP + GetSyntheticValue(const StructuredData::ObjectSP &implementor) override; + + ConstString + GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override; + + bool + RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, + ScriptedCommandSynchronicity synchronicity, + lldb_private::CommandReturnObject &cmd_retobj, + Status &error, + const lldb_private::ExecutionContext &exe_ctx) override; + + bool RunScriptBasedCommand( + StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, + ScriptedCommandSynchronicity synchronicity, + lldb_private::CommandReturnObject &cmd_retobj, Status &error, + const lldb_private::ExecutionContext &exe_ctx) override; + + Status GenerateFunction(const char *signature, + const StringList &input) override; + + Status GenerateBreakpointCommandCallbackData(StringList &input, + std::string &output) override; + + bool GenerateWatchpointCommandCallbackData(StringList &input, + std::string &output) override; + + bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, + StructuredData::ObjectSP &callee_wrapper_sp, + const TypeSummaryOptions &options, + std::string &retval) override; + + void Clear() override; + + bool GetDocumentationForItem(const char *item, std::string &dest) override; + + bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, + std::string &dest) override; + + uint32_t + GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override; + + bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, + std::string &dest) override; + + bool CheckObjectExists(const char *name) override { + if (!name || !name[0]) + return false; + std::string temp; + return GetDocumentationForItem(name, temp); + } + + bool RunScriptFormatKeyword(const char *impl_function, Process *process, + std::string &output, Status &error) override; + + bool RunScriptFormatKeyword(const char *impl_function, Thread *thread, + std::string &output, Status &error) override; + + bool RunScriptFormatKeyword(const char *impl_function, Target *target, + std::string &output, Status &error) override; + + bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame, + std::string &output, Status &error) override; + + bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value, + std::string &output, Status &error) override; + + bool + LoadScriptingModule(const char *filename, bool can_reload, bool init_session, + lldb_private::Status &error, + StructuredData::ObjectSP *module_sp = nullptr) override; + + bool IsReservedWord(const char *word) override; + + std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override; + + void CollectDataForBreakpointCommandCallback( + std::vector<BreakpointOptions *> &bp_options_vec, + CommandReturnObject &result) override; + + void + CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, + CommandReturnObject &result) override; + + /// Set the callback body text into the callback for the breakpoint. + Status SetBreakpointCommandCallback(BreakpointOptions *bp_options, + const char *callback_body) override; + + void SetBreakpointCommandCallbackFunction(BreakpointOptions *bp_options, + const char *function_name) override; + + /// This one is for deserialization: + Status SetBreakpointCommandCallback( + BreakpointOptions *bp_options, + std::unique_ptr<BreakpointOptions::CommandData> &data_up) override; + + /// Set a one-liner as the callback for the watchpoint. + void SetWatchpointCommandCallback(WatchpointOptions *wp_options, + const char *oneliner) override; + + void ResetOutputFileHandle(FILE *new_fh) override; + + const char *GetDictionaryName() { return m_dictionary_name.c_str(); } + + PyThreadState *GetThreadState() { return m_command_thread_state; } + + void SetThreadState(PyThreadState *s) { + if (s) + m_command_thread_state = s; + } + + // IOHandlerDelegate + void IOHandlerActivated(IOHandler &io_handler, bool interactive) override; + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &data) override; + + static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger); + + // PluginInterface protocol + lldb_private::ConstString GetPluginName() override; + + uint32_t GetPluginVersion() override; + + class Locker : public ScriptInterpreterLocker { + public: + enum OnEntry { + AcquireLock = 0x0001, + InitSession = 0x0002, + InitGlobals = 0x0004, + NoSTDIN = 0x0008 + }; + + enum OnLeave { + FreeLock = 0x0001, + FreeAcquiredLock = 0x0002, // do not free the lock if we already held it + // when calling constructor + TearDownSession = 0x0004 + }; + + Locker(ScriptInterpreterPythonImpl *py_interpreter = nullptr, + uint16_t on_entry = AcquireLock | InitSession, + uint16_t on_leave = FreeLock | TearDownSession, FILE *in = nullptr, + FILE *out = nullptr, FILE *err = nullptr); + + ~Locker() override; + + private: + bool DoAcquireLock(); + + bool DoInitSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err); + + bool DoFreeLock(); + + bool DoTearDownSession(); + + bool m_teardown_session; + ScriptInterpreterPythonImpl *m_python_interpreter; + // FILE* m_tmp_fh; + PyGILState_STATE m_GILState; + }; + + static bool BreakpointCallbackFunction(void *baton, + StoppointCallbackContext *context, + lldb::user_id_t break_id, + lldb::user_id_t break_loc_id); + static bool WatchpointCallbackFunction(void *baton, + StoppointCallbackContext *context, + lldb::user_id_t watch_id); + static void InitializePrivate(); + + class SynchronicityHandler { + private: + lldb::DebuggerSP m_debugger_sp; + ScriptedCommandSynchronicity m_synch_wanted; + bool m_old_asynch; + + public: + SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity); + + ~SynchronicityHandler(); + }; + + enum class AddLocation { Beginning, End }; + + static void AddToSysPath(AddLocation location, std::string path); + + bool EnterSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err); + + void LeaveSession(); + + void SaveTerminalState(int fd); + + void RestoreTerminalState(); + + uint32_t IsExecutingPython() const { return m_lock_count > 0; } + + uint32_t IncrementLockCount() { return ++m_lock_count; } + + uint32_t DecrementLockCount() { + if (m_lock_count > 0) + --m_lock_count; + return m_lock_count; + } + + enum ActiveIOHandler { + eIOHandlerNone, + eIOHandlerBreakpoint, + eIOHandlerWatchpoint + }; + + PythonObject &GetMainModule(); + + PythonDictionary &GetSessionDictionary(); + + PythonDictionary &GetSysModuleDictionary(); + + bool GetEmbeddedInterpreterModuleObjects(); + + bool SetStdHandle(File &file, const char *py_name, PythonFile &save_file, + const char *mode); + + PythonFile m_saved_stdin; + PythonFile m_saved_stdout; + PythonFile m_saved_stderr; + PythonObject m_main_module; + PythonDictionary m_session_dict; + PythonDictionary m_sys_module_dict; + PythonObject m_run_one_line_function; + PythonObject m_run_one_line_str_global; + std::string m_dictionary_name; + TerminalState m_terminal_state; + ActiveIOHandler m_active_io_handler; + bool m_session_is_active; + bool m_pty_slave_is_open; + bool m_valid_session; + uint32_t m_lock_count; + PyThreadState *m_command_thread_state; +}; + +class IOHandlerPythonInterpreter : public IOHandler { +public: + IOHandlerPythonInterpreter(Debugger &debugger, + ScriptInterpreterPythonImpl *python) + : IOHandler(debugger, IOHandler::Type::PythonInterpreter), + m_python(python) {} + + ~IOHandlerPythonInterpreter() override {} + + ConstString GetControlSequence(char ch) override { + if (ch == 'd') + return ConstString("quit()\n"); + return ConstString(); + } + + void Run() override { + if (m_python) { + int stdin_fd = GetInputFD(); + if (stdin_fd >= 0) { + Terminal terminal(stdin_fd); + TerminalState terminal_state; + const bool is_a_tty = terminal.IsATerminal(); + + if (is_a_tty) { + terminal_state.Save(stdin_fd, false); + terminal.SetCanonical(false); + terminal.SetEcho(true); + } + + ScriptInterpreterPythonImpl::Locker locker( + m_python, + ScriptInterpreterPythonImpl::Locker::AcquireLock | + ScriptInterpreterPythonImpl::Locker::InitSession | + ScriptInterpreterPythonImpl::Locker::InitGlobals, + ScriptInterpreterPythonImpl::Locker::FreeAcquiredLock | + ScriptInterpreterPythonImpl::Locker::TearDownSession); + + // The following call drops into the embedded interpreter loop and + // stays there until the user chooses to exit from the Python + // interpreter. This embedded interpreter will, as any Python code that + // performs I/O, unlock the GIL before a system call that can hang, and + // lock it when the syscall has returned. + + // We need to surround the call to the embedded interpreter with calls + // to PyGILState_Ensure and PyGILState_Release (using the Locker + // above). This is because Python has a global lock which must be held + // whenever we want to touch any Python objects. Otherwise, if the user + // calls Python code, the interpreter state will be off, and things + // could hang (it's happened before). + + StreamString run_string; + run_string.Printf("run_python_interpreter (%s)", + m_python->GetDictionaryName()); + PyRun_SimpleString(run_string.GetData()); + + if (is_a_tty) + terminal_state.Restore(); + } + } + SetIsDone(true); + } + + void Cancel() override {} + + bool Interrupt() override { return m_python->Interrupt(); } + + void GotEOF() override {} + +protected: + ScriptInterpreterPythonImpl *m_python; +}; + +} // namespace lldb_private + +#endif
diff --git a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/lldb-python.h b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/lldb-python.h index f929baad..884514d 100644 --- a/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/lldb-python.h +++ b/src/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/lldb-python.h
@@ -1,9 +1,8 @@ //===-- lldb-python.h -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,6 +32,12 @@ #undef _XOPEN_SOURCE #endif +// Include locale before Python so _PY_PORT_CTYPE_UTF8_ISSUE doesn't cause +// macro redefinitions. +#if defined(__APPLE__) +#include <locale> +#endif + // Include python for non windows machines #include <Python.h> #endif // LLDB_DISABLE_PYTHON
diff --git a/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp b/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp index 6e3792b..81a2712 100644 --- a/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp +++ b/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp
@@ -1,18 +1,16 @@ //===-- StructuredDataDarwinLog.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "StructuredDataDarwinLog.h" -// C includes #include <string.h> -// C++ includes +#include <memory> #include <sstream> #include "lldb/Breakpoint/StoppointCallbackContext.h" @@ -41,9 +39,7 @@ #pragma mark - #pragma mark Anonymous Namespace -// ----------------------------------------------------------------------------- // Anonymous namespace -// ----------------------------------------------------------------------------- namespace sddarwinlog_private { const uint64_t NANOS_PER_MICRO = 1000; @@ -54,13 +50,11 @@ static bool DEFAULT_FILTER_FALLTHROUGH_ACCEPTS = true; -//------------------------------------------------------------------ /// Global, sticky enable switch. If true, the user has explicitly /// run the enable command. When a process launches or is attached to, /// we will enable DarwinLog if either the settings for auto-enable is /// on, or if the user had explicitly run enable at some point prior /// to the launch/attach. -//------------------------------------------------------------------ static bool s_is_explicitly_enabled; class EnableOptions; @@ -108,9 +102,7 @@ #pragma mark - #pragma mark Settings Handling -//------------------------------------------------------------------ /// Code to handle the StructuredDataDarwinLog settings -//------------------------------------------------------------------ static constexpr PropertyDefinition g_properties[] = { { @@ -145,11 +137,11 @@ } StructuredDataDarwinLogProperties() : Properties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); } - virtual ~StructuredDataDarwinLogProperties() {} + ~StructuredDataDarwinLogProperties() override {} bool GetEnableOnStartup() const { const uint32_t idx = ePropertyEnableOnStartup; @@ -172,7 +164,7 @@ static const StructuredDataDarwinLogPropertiesSP &GetGlobalProperties() { static StructuredDataDarwinLogPropertiesSP g_settings_sp; if (!g_settings_sp) - g_settings_sp.reset(new StructuredDataDarwinLogProperties()); + g_settings_sp = std::make_shared<StructuredDataDarwinLogProperties>(); return g_settings_sp; } @@ -189,12 +181,12 @@ // used to format message text }; -static const ConstString &GetDarwinLogTypeName() { +static ConstString GetDarwinLogTypeName() { static const ConstString s_key_name("DarwinLog"); return s_key_name; } -static const ConstString &GetLogEventType() { +static ConstString GetLogEventType() { static const ConstString s_event_type("log"); return s_event_type; } @@ -210,13 +202,13 @@ std::function<FilterRuleSP(bool accept, size_t attribute_index, const std::string &op_arg, Status &error)>; - static void RegisterOperation(const ConstString &operation, + static void RegisterOperation(ConstString operation, const OperationCreationFunc &creation_func) { GetCreationFuncMap().insert(std::make_pair(operation, creation_func)); } static FilterRuleSP CreateRule(bool match_accepts, size_t attribute, - const ConstString &operation, + ConstString operation, const std::string &op_arg, Status &error) { // Find the creation func for this type of filter rule. auto map = GetCreationFuncMap(); @@ -254,10 +246,10 @@ virtual void Dump(Stream &stream) const = 0; - const ConstString &GetOperationType() const { return m_operation; } + ConstString GetOperationType() const { return m_operation; } protected: - FilterRule(bool accept, size_t attribute_index, const ConstString &operation) + FilterRule(bool accept, size_t attribute_index, ConstString operation) : m_accept(accept), m_attribute_index(attribute_index), m_operation(operation) {} @@ -326,7 +318,7 @@ return FilterRuleSP(new RegexFilterRule(accept, attribute_index, op_arg)); } - static const ConstString &StaticGetOperation() { + static ConstString StaticGetOperation() { static ConstString s_operation("regex"); return s_operation; } @@ -371,7 +363,7 @@ new ExactMatchFilterRule(accept, attribute_index, op_arg)); } - static const ConstString &StaticGetOperation() { + static ConstString StaticGetOperation() { static ConstString s_operation("match"); return s_operation; } @@ -393,12 +385,10 @@ // Commands // ========================================================================= -// ------------------------------------------------------------------------- /// Provides the main on-off switch for enabling darwin logging. /// /// It is valid to run the enable command when logging is already enabled. /// This resets the logging with whatever settings are currently set. -// ------------------------------------------------------------------------- static constexpr OptionDefinition g_enable_option_table[] = { // Source stream include/exclude options (the first-level filter). This one @@ -858,7 +848,7 @@ // that logging be enabled for a process before libtrace is initialized // results in a scenario where no errors occur, but no logging is // captured, either. This step is to eliminate that possibility. - plugin.AddInitCompletionHook(*process_sp.get()); + plugin.AddInitCompletionHook(*process_sp); } // Send configuration to the feature by way of the process. Construct the @@ -892,9 +882,7 @@ EnableOptionsSP m_options_sp; }; -// ------------------------------------------------------------------------- /// Provides the status command. -// ------------------------------------------------------------------------- class StatusCommand : public CommandObjectParsed { public: StatusCommand(CommandInterpreter &interpreter) @@ -920,7 +908,7 @@ process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); stream.Printf("Availability: %s\n", plugin_sp ? "available" : "unavailable"); - auto &plugin_name = StructuredDataDarwinLog::GetStaticPluginName(); + ConstString plugin_name = StructuredDataDarwinLog::GetStaticPluginName(); const bool enabled = plugin_sp ? plugin_sp->GetEnabled(plugin_name) : false; stream.Printf("Enabled: %s\n", enabled ? "true" : "false"); @@ -970,9 +958,7 @@ } }; -// ------------------------------------------------------------------------- /// Provides the darwin-log base command -// ------------------------------------------------------------------------- class BaseCommand : public CommandObjectMultiword { public: BaseCommand(CommandInterpreter &interpreter) @@ -1084,9 +1070,7 @@ #pragma mark - #pragma mark Public static API -// ----------------------------------------------------------------------------- // Public static API -// ----------------------------------------------------------------------------- void StructuredDataDarwinLog::Initialize() { RegisterFilterOperations(); @@ -1099,7 +1083,7 @@ PluginManager::UnregisterPlugin(&CreateInstance); } -const ConstString &StructuredDataDarwinLog::GetStaticPluginName() { +ConstString StructuredDataDarwinLog::GetStaticPluginName() { static ConstString s_plugin_name("darwin-log"); return s_plugin_name; } @@ -1107,9 +1091,7 @@ #pragma mark - #pragma mark PluginInterface API -// ----------------------------------------------------------------------------- // PluginInterface API -// ----------------------------------------------------------------------------- ConstString StructuredDataDarwinLog::GetPluginName() { return GetStaticPluginName(); @@ -1120,17 +1102,15 @@ #pragma mark - #pragma mark StructuredDataPlugin API -// ----------------------------------------------------------------------------- // StructuredDataPlugin API -// ----------------------------------------------------------------------------- bool StructuredDataDarwinLog::SupportsStructuredDataType( - const ConstString &type_name) { + ConstString type_name) { return type_name == GetDarwinLogTypeName(); } void StructuredDataDarwinLog::HandleArrivalOfStructuredData( - Process &process, const ConstString &type_name, + Process &process, ConstString type_name, const StructuredData::ObjectSP &object_sp) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); if (log) { @@ -1269,7 +1249,7 @@ return error; } -bool StructuredDataDarwinLog::GetEnabled(const ConstString &type_name) const { +bool StructuredDataDarwinLog::GetEnabled(ConstString type_name) const { if (type_name == GetStaticPluginName()) return m_is_enabled; else @@ -1372,9 +1352,7 @@ EnableNow(); } -// ----------------------------------------------------------------------------- // public destructor -// ----------------------------------------------------------------------------- StructuredDataDarwinLog::~StructuredDataDarwinLog() { if (m_breakpoint_id != LLDB_INVALID_BREAK_ID) { @@ -1389,9 +1367,7 @@ #pragma mark - #pragma mark Private instance methods -// ----------------------------------------------------------------------------- // Private constructors -// ----------------------------------------------------------------------------- StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp) : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false), @@ -1399,9 +1375,7 @@ m_added_breakpoint_mutex(), m_added_breakpoint(), m_breakpoint_id(LLDB_INVALID_BREAK_ID) {} -// ----------------------------------------------------------------------------- // Private static methods -// ----------------------------------------------------------------------------- StructuredDataPluginSP StructuredDataDarwinLog::CreateInstance(Process &process) { @@ -1636,8 +1610,8 @@ } // Queue the thread plan. - auto thread_plan_sp = ThreadPlanSP( - new ThreadPlanCallOnFunctionExit(*thread_sp.get(), callback)); + auto thread_plan_sp = + ThreadPlanSP(new ThreadPlanCallOnFunctionExit(*thread_sp, callback)); const bool abort_other_plans = false; thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans); if (log)
diff --git a/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h b/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h index 77b6e7b..8fa1eed 100644 --- a/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h +++ b/src/llvm-project/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h
@@ -1,9 +1,8 @@ //===-- StructuredDataDarwinLog.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,17 +24,14 @@ friend sddarwinlog_private::EnableCommand; public: - // ------------------------------------------------------------------------- // Public static API - // ------------------------------------------------------------------------- static void Initialize(); static void Terminate(); - static const ConstString &GetStaticPluginName(); + static ConstString GetStaticPluginName(); - // ------------------------------------------------------------------------- /// Return whether the DarwinLog functionality is enabled. /// /// The DarwinLog functionality is enabled if the user expicitly enabled @@ -43,49 +39,40 @@ /// that controls if we always enable it for newly created/attached /// processes. /// - /// @return + /// \return /// True if DarwinLog support is/will be enabled for existing or /// newly launched/attached processes. - // ------------------------------------------------------------------------- static bool IsEnabled(); - // ------------------------------------------------------------------------- // PluginInterface API - // ------------------------------------------------------------------------- ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - // ------------------------------------------------------------------------- // StructuredDataPlugin API - // ------------------------------------------------------------------------- - bool SupportsStructuredDataType(const ConstString &type_name) override; + bool SupportsStructuredDataType(ConstString type_name) override; void HandleArrivalOfStructuredData( - Process &process, const ConstString &type_name, + Process &process, ConstString type_name, const StructuredData::ObjectSP &object_sp) override; Status GetDescription(const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) override; - bool GetEnabled(const ConstString &type_name) const override; + bool GetEnabled(ConstString type_name) const override; void ModulesDidLoad(Process &process, ModuleList &module_list) override; - ~StructuredDataDarwinLog(); + ~StructuredDataDarwinLog() override; private: - // ------------------------------------------------------------------------- // Private constructors - // ------------------------------------------------------------------------- StructuredDataDarwinLog(const lldb::ProcessWP &process_wp); - // ------------------------------------------------------------------------- // Private static methods - // ------------------------------------------------------------------------- static lldb::StructuredDataPluginSP CreateInstance(Process &process); @@ -99,16 +86,12 @@ static Status FilterLaunchInfo(ProcessLaunchInfo &launch_info, Target *target); - // ------------------------------------------------------------------------- // Internal helper methods used by friend classes - // ------------------------------------------------------------------------- void SetEnabled(bool enabled); void AddInitCompletionHook(Process &process); - // ------------------------------------------------------------------------- // Private methods - // ------------------------------------------------------------------------- void DumpTimestamp(Stream &stream, uint64_t timestamp); @@ -117,16 +100,12 @@ size_t HandleDisplayOfEvent(const StructuredData::Dictionary &event, Stream &stream); - // ------------------------------------------------------------------------- /// Call the enable command again, using whatever settings were initially /// made. - // ------------------------------------------------------------------------- void EnableNow(); - // ------------------------------------------------------------------------- // Private data - // ------------------------------------------------------------------------- bool m_recorded_first_timestamp; uint64_t m_first_timestamp_seen; bool m_is_enabled;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp index 2cca7a6..d425827 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp
@@ -1,84 +1,166 @@ //===-- SymbolFileBreakpad.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.h" +#include "Plugins/ObjectFile/Breakpad/BreakpadRecords.h" #include "Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Host/FileSystem.h" +#include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/PostfixExpression.h" +#include "lldb/Symbol/SymbolVendor.h" #include "lldb/Symbol/TypeMap.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/StreamString.h" #include "llvm/ADT/StringExtras.h" using namespace lldb; using namespace lldb_private; using namespace lldb_private::breakpad; -namespace { -class LineIterator { +class SymbolFileBreakpad::LineIterator { public: // begin iterator for sections of given type - LineIterator(ObjectFile &obj, ConstString section_type) - : m_obj(&obj), m_section_type(section_type), m_next_section_idx(0) { + LineIterator(ObjectFile &obj, Record::Kind section_type) + : m_obj(&obj), m_section_type(toString(section_type)), + m_next_section_idx(0), m_next_line(llvm::StringRef::npos) { ++*this; } + // An iterator starting at the position given by the bookmark. + LineIterator(ObjectFile &obj, Record::Kind section_type, Bookmark bookmark); + // end iterator explicit LineIterator(ObjectFile &obj) : m_obj(&obj), - m_next_section_idx(m_obj->GetSectionList()->GetNumSections(0)) {} + m_next_section_idx(m_obj->GetSectionList()->GetNumSections(0)), + m_current_line(llvm::StringRef::npos), + m_next_line(llvm::StringRef::npos) {} friend bool operator!=(const LineIterator &lhs, const LineIterator &rhs) { assert(lhs.m_obj == rhs.m_obj); if (lhs.m_next_section_idx != rhs.m_next_section_idx) return true; - if (lhs.m_next_text.data() != rhs.m_next_text.data()) + if (lhs.m_current_line != rhs.m_current_line) return true; - assert(lhs.m_current_text == rhs.m_current_text); - assert(rhs.m_next_text == rhs.m_next_text); + assert(lhs.m_next_line == rhs.m_next_line); return false; } const LineIterator &operator++(); - llvm::StringRef operator*() const { return m_current_text; } + llvm::StringRef operator*() const { + return m_section_text.slice(m_current_line, m_next_line); + } + + Bookmark GetBookmark() const { + return Bookmark{m_next_section_idx, m_current_line}; + } private: ObjectFile *m_obj; ConstString m_section_type; uint32_t m_next_section_idx; - llvm::StringRef m_current_text; - llvm::StringRef m_next_text; -}; -} // namespace + llvm::StringRef m_section_text; + size_t m_current_line; + size_t m_next_line; -const LineIterator &LineIterator::operator++() { + void FindNextLine() { + m_next_line = m_section_text.find('\n', m_current_line); + if (m_next_line != llvm::StringRef::npos) { + ++m_next_line; + if (m_next_line >= m_section_text.size()) + m_next_line = llvm::StringRef::npos; + } + } +}; + +SymbolFileBreakpad::LineIterator::LineIterator(ObjectFile &obj, + Record::Kind section_type, + Bookmark bookmark) + : m_obj(&obj), m_section_type(toString(section_type)), + m_next_section_idx(bookmark.section), m_current_line(bookmark.offset) { + Section § = + *obj.GetSectionList()->GetSectionAtIndex(m_next_section_idx - 1); + assert(sect.GetName() == m_section_type); + + DataExtractor data; + obj.ReadSectionData(§, data); + m_section_text = toStringRef(data.GetData()); + + assert(m_current_line < m_section_text.size()); + FindNextLine(); +} + +const SymbolFileBreakpad::LineIterator & +SymbolFileBreakpad::LineIterator::operator++() { const SectionList &list = *m_obj->GetSectionList(); size_t num_sections = list.GetNumSections(0); - while (m_next_text.empty() && m_next_section_idx < num_sections) { + while (m_next_line != llvm::StringRef::npos || + m_next_section_idx < num_sections) { + if (m_next_line != llvm::StringRef::npos) { + m_current_line = m_next_line; + FindNextLine(); + return *this; + } + Section § = *list.GetSectionAtIndex(m_next_section_idx++); if (sect.GetName() != m_section_type) continue; DataExtractor data; m_obj->ReadSectionData(§, data); - m_next_text = - llvm::StringRef(reinterpret_cast<const char *>(data.GetDataStart()), - data.GetByteSize()); + m_section_text = toStringRef(data.GetData()); + m_next_line = 0; } - std::tie(m_current_text, m_next_text) = m_next_text.split('\n'); + // We've reached the end. + m_current_line = m_next_line; return *this; } -static llvm::iterator_range<LineIterator> lines(ObjectFile &obj, - ConstString section_type) { - return llvm::make_range(LineIterator(obj, section_type), LineIterator(obj)); +llvm::iterator_range<SymbolFileBreakpad::LineIterator> +SymbolFileBreakpad::lines(Record::Kind section_type) { + return llvm::make_range(LineIterator(*m_obj_file, section_type), + LineIterator(*m_obj_file)); +} + +namespace { +// A helper class for constructing the list of support files for a given compile +// unit. +class SupportFileMap { +public: + // Given a breakpad file ID, return a file ID to be used in the support files + // for this compile unit. + size_t operator[](size_t file) { + return m_map.try_emplace(file, m_map.size() + 1).first->second; + } + + // Construct a FileSpecList containing only the support files relevant for + // this compile unit (in the correct order). + FileSpecList translate(const FileSpec &cu_spec, + llvm::ArrayRef<FileSpec> all_files); + +private: + llvm::DenseMap<size_t, size_t> m_map; +}; +} // namespace + +FileSpecList SupportFileMap::translate(const FileSpec &cu_spec, + llvm::ArrayRef<FileSpec> all_files) { + std::vector<FileSpec> result; + result.resize(m_map.size() + 1); + result[0] = cu_spec; + for (const auto &KV : m_map) { + if (KV.first < all_files.size()) + result[KV.second] = all_files[KV.first]; + } + return FileSpecList(std::move(result)); } void SymbolFileBreakpad::Initialize() { @@ -102,17 +184,42 @@ if (m_obj_file->GetPluginName() != ObjectFileBreakpad::GetPluginNameStatic()) return 0; - return CompileUnits | Functions; + return CompileUnits | Functions | LineTables; } uint32_t SymbolFileBreakpad::GetNumCompileUnits() { - // TODO - return 0; + ParseCUData(); + return m_cu_data->GetSize(); } CompUnitSP SymbolFileBreakpad::ParseCompileUnitAtIndex(uint32_t index) { - // TODO - return nullptr; + if (index >= m_cu_data->GetSize()) + return nullptr; + + CompUnitData &data = m_cu_data->GetEntryRef(index).data; + + ParseFileRecords(); + + FileSpec spec; + + // The FileSpec of the compile unit will be the file corresponding to the + // first LINE record. + LineIterator It(*m_obj_file, Record::Func, data.bookmark), End(*m_obj_file); + assert(Record::classify(*It) == Record::Func); + ++It; // Skip FUNC record. + if (It != End) { + auto record = LineRecord::parse(*It); + if (record && record->FileNum < m_files->size()) + spec = (*m_files)[record->FileNum]; + } + + auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), + /*user_data*/ nullptr, spec, index, + eLanguageTypeUnknown, + /*is_optimized*/ eLazyBoolNo); + + GetSymbolVendor().SetCompileUnitAtIndex(index, cu_sp); + return cu_sp; } size_t SymbolFileBreakpad::ParseFunctions(CompileUnit &comp_unit) { @@ -121,20 +228,67 @@ } bool SymbolFileBreakpad::ParseLineTable(CompileUnit &comp_unit) { - // TODO - return 0; + CompUnitData &data = m_cu_data->GetEntryRef(comp_unit.GetID()).data; + + if (!data.line_table_up) + ParseLineTableAndSupportFiles(comp_unit, data); + + comp_unit.SetLineTable(data.line_table_up.release()); + return true; +} + +bool SymbolFileBreakpad::ParseSupportFiles(CompileUnit &comp_unit, + FileSpecList &support_files) { + CompUnitData &data = m_cu_data->GetEntryRef(comp_unit.GetID()).data; + if (!data.support_files) + ParseLineTableAndSupportFiles(comp_unit, data); + + support_files = std::move(*data.support_files); + return true; } uint32_t SymbolFileBreakpad::ResolveSymbolContext(const Address &so_addr, SymbolContextItem resolve_scope, SymbolContext &sc) { - // TODO - return 0; + if (!(resolve_scope & (eSymbolContextCompUnit | eSymbolContextLineEntry))) + return 0; + + ParseCUData(); + uint32_t idx = + m_cu_data->FindEntryIndexThatContains(so_addr.GetFileAddress()); + if (idx == UINT32_MAX) + return 0; + + sc.comp_unit = GetSymbolVendor().GetCompileUnitAtIndex(idx).get(); + SymbolContextItem result = eSymbolContextCompUnit; + if (resolve_scope & eSymbolContextLineEntry) { + if (sc.comp_unit->GetLineTable()->FindLineEntryByAddress(so_addr, + sc.line_entry)) { + result |= eSymbolContextLineEntry; + } + } + + return result; +} + +uint32_t SymbolFileBreakpad::ResolveSymbolContext( + const FileSpec &file_spec, uint32_t line, bool check_inlines, + lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) { + if (!(resolve_scope & eSymbolContextCompUnit)) + return 0; + + uint32_t old_size = sc_list.GetSize(); + for (size_t i = 0, size = GetNumCompileUnits(); i < size; ++i) { + CompileUnit &cu = *GetSymbolVendor().GetCompileUnitAtIndex(i); + cu.ResolveSymbolContext(file_spec, line, check_inlines, + /*exact*/ false, resolve_scope, sc_list); + } + return sc_list.GetSize() - old_size; } uint32_t SymbolFileBreakpad::FindFunctions( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, FunctionNameType name_type_mask, bool include_inlines, bool append, SymbolContextList &sc_list) { // TODO @@ -153,7 +307,7 @@ } uint32_t SymbolFileBreakpad::FindTypes( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) { if (!append) @@ -172,7 +326,7 @@ void SymbolFileBreakpad::AddSymbols(Symtab &symtab) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS); Module &module = *m_obj_file->GetModule(); - addr_t base = module.GetObjectFile()->GetBaseAddress().GetFileAddress(); + addr_t base = GetBaseFileAddress(); if (base == LLDB_INVALID_ADDRESS) { LLDB_LOG(log, "Unable to fetch the base address of object file. Skipping " "symtab population."); @@ -180,44 +334,320 @@ } const SectionList &list = *module.GetSectionList(); - for (llvm::StringRef line : lines(*m_obj_file, ConstString("PUBLIC"))) { - // PUBLIC [m] address param_size name - // skip PUBLIC keyword - line = getToken(line).second; - llvm::StringRef token; - std::tie(token, line) = getToken(line); - if (token == "m") - std::tie(token, line) = getToken(line); - - addr_t address; - if (!to_integer(token, address, 16)) - continue; + llvm::DenseMap<addr_t, Symbol> symbols; + auto add_symbol = [&](addr_t address, llvm::Optional<addr_t> size, + llvm::StringRef name) { address += base; - - // skip param_size - line = getToken(line).second; - - llvm::StringRef name = line.trim(); - SectionSP section_sp = list.FindSectionContainingFileAddress(address); if (!section_sp) { LLDB_LOG(log, "Ignoring symbol {0}, whose address ({1}) is outside of the " "object file. Mismatched symbol file?", name, address); + return; + } + symbols.try_emplace( + address, /*symID*/ 0, Mangled(name, /*is_mangled*/ false), + eSymbolTypeCode, /*is_global*/ true, /*is_debug*/ false, + /*is_trampoline*/ false, /*is_artificial*/ false, + AddressRange(section_sp, address - section_sp->GetFileAddress(), + size.getValueOr(0)), + size.hasValue(), /*contains_linker_annotations*/ false, /*flags*/ 0); + }; + + for (llvm::StringRef line : lines(Record::Func)) { + if (auto record = FuncRecord::parse(line)) + add_symbol(record->Address, record->Size, record->Name); + } + + for (llvm::StringRef line : lines(Record::Public)) { + if (auto record = PublicRecord::parse(line)) + add_symbol(record->Address, llvm::None, record->Name); + else + LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", line); + } + + for (auto &KV : symbols) + symtab.AddSymbol(std::move(KV.second)); + symtab.CalculateSymbolSizes(); +} + +static llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>> +GetRule(llvm::StringRef &unwind_rules) { + // Unwind rules are of the form + // register1: expression1 register2: expression2 ... + // We assume none of the tokens in expression<n> end with a colon. + + llvm::StringRef lhs, rest; + std::tie(lhs, rest) = getToken(unwind_rules); + if (!lhs.consume_back(":")) + return llvm::None; + + // Seek forward to the next register: expression pair + llvm::StringRef::size_type pos = rest.find(": "); + if (pos == llvm::StringRef::npos) { + // No pair found, this means the rest of the string is a single expression. + unwind_rules = llvm::StringRef(); + return std::make_pair(lhs, rest); + } + + // Go back one token to find the end of the current rule. + pos = rest.rfind(' ', pos); + if (pos == llvm::StringRef::npos) + return llvm::None; + + llvm::StringRef rhs = rest.take_front(pos); + unwind_rules = rest.drop_front(pos); + return std::make_pair(lhs, rhs); +} + +static const RegisterInfo * +ResolveRegister(const SymbolFile::RegisterInfoResolver &resolver, + llvm::StringRef name) { + if (name.consume_front("$")) + return resolver.ResolveName(name); + + return nullptr; +} + +static const RegisterInfo * +ResolveRegisterOrRA(const SymbolFile::RegisterInfoResolver &resolver, + llvm::StringRef name) { + if (name == ".ra") + return resolver.ResolveNumber(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); + return ResolveRegister(resolver, name); +} + +bool SymbolFileBreakpad::ParseUnwindRow(llvm::StringRef unwind_rules, + const RegisterInfoResolver &resolver, + UnwindPlan::Row &row) { + Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS); + + llvm::BumpPtrAllocator node_alloc; + while (auto rule = GetRule(unwind_rules)) { + node_alloc.Reset(); + llvm::StringRef lhs = rule->first; + postfix::Node *rhs = postfix::Parse(rule->second, node_alloc); + if (!rhs) { + LLDB_LOG(log, "Could not parse `{0}` as unwind rhs.", rule->second); + return false; + } + + bool success = postfix::ResolveSymbols( + rhs, [&](postfix::SymbolNode &symbol) -> postfix::Node * { + llvm::StringRef name = symbol.GetName(); + if (name == ".cfa" && lhs != ".cfa") + return postfix::MakeNode<postfix::InitialValueNode>(node_alloc); + + if (const RegisterInfo *info = ResolveRegister(resolver, name)) { + return postfix::MakeNode<postfix::RegisterNode>( + node_alloc, info->kinds[eRegisterKindLLDB]); + } + return nullptr; + }); + + if (!success) { + LLDB_LOG(log, "Resolving symbols in `{0}` failed.", rule->second); + return false; + } + + ArchSpec arch = m_obj_file->GetArchitecture(); + StreamString dwarf(Stream::eBinary, arch.GetAddressByteSize(), + arch.GetByteOrder()); + ToDWARF(*rhs, dwarf); + uint8_t *saved = m_allocator.Allocate<uint8_t>(dwarf.GetSize()); + std::memcpy(saved, dwarf.GetData(), dwarf.GetSize()); + + if (lhs == ".cfa") { + row.GetCFAValue().SetIsDWARFExpression(saved, dwarf.GetSize()); + } else if (const RegisterInfo *info = ResolveRegisterOrRA(resolver, lhs)) { + UnwindPlan::Row::RegisterLocation loc; + loc.SetIsDWARFExpression(saved, dwarf.GetSize()); + row.SetRegisterInfo(info->kinds[eRegisterKindLLDB], loc); + } else + LLDB_LOG(log, "Invalid register `{0}` in unwind rule.", lhs); + } + if (unwind_rules.empty()) + return true; + + LLDB_LOG(log, "Could not parse `{0}` as an unwind rule.", unwind_rules); + return false; +} + +UnwindPlanSP +SymbolFileBreakpad::GetUnwindPlan(const Address &address, + const RegisterInfoResolver &resolver) { + ParseUnwindData(); + const UnwindMap::Entry *entry = + m_unwind_data->FindEntryThatContains(address.GetFileAddress()); + if (!entry) + return nullptr; + + addr_t base = GetBaseFileAddress(); + if (base == LLDB_INVALID_ADDRESS) + return nullptr; + + LineIterator It(*m_obj_file, Record::StackCFI, entry->data), End(*m_obj_file); + llvm::Optional<StackCFIRecord> init_record = StackCFIRecord::parse(*It); + assert(init_record.hasValue()); + assert(init_record->Size.hasValue()); + + auto plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindLLDB); + plan_sp->SetSourceName("breakpad STACK CFI"); + plan_sp->SetUnwindPlanValidAtAllInstructions(eLazyBoolNo); + plan_sp->SetSourcedFromCompiler(eLazyBoolYes); + plan_sp->SetPlanValidAddressRange( + AddressRange(base + init_record->Address, *init_record->Size, + m_obj_file->GetModule()->GetSectionList())); + + auto row_sp = std::make_shared<UnwindPlan::Row>(); + row_sp->SetOffset(0); + if (!ParseUnwindRow(init_record->UnwindRules, resolver, *row_sp)) + return nullptr; + plan_sp->AppendRow(row_sp); + for (++It; It != End; ++It) { + llvm::Optional<StackCFIRecord> record = StackCFIRecord::parse(*It); + if (!record.hasValue()) + return nullptr; + if (record->Size.hasValue()) + break; + + row_sp = std::make_shared<UnwindPlan::Row>(*row_sp); + row_sp->SetOffset(record->Address - init_record->Address); + if (!ParseUnwindRow(record->UnwindRules, resolver, *row_sp)) + return nullptr; + plan_sp->AppendRow(row_sp); + } + return plan_sp; +} + +SymbolVendor &SymbolFileBreakpad::GetSymbolVendor() { + return *m_obj_file->GetModule()->GetSymbolVendor(); +} + +addr_t SymbolFileBreakpad::GetBaseFileAddress() { + return m_obj_file->GetModule() + ->GetObjectFile() + ->GetBaseAddress() + .GetFileAddress(); +} + +// Parse out all the FILE records from the breakpad file. These will be needed +// when constructing the support file lists for individual compile units. +void SymbolFileBreakpad::ParseFileRecords() { + if (m_files) + return; + m_files.emplace(); + + Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS); + for (llvm::StringRef line : lines(Record::File)) { + auto record = FileRecord::parse(line); + if (!record) { + LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", line); continue; } - symtab.AddSymbol(Symbol( - /*symID*/ 0, Mangled(name, /*is_mangled*/ false), eSymbolTypeCode, - /*is_global*/ true, /*is_debug*/ false, /*is_trampoline*/ false, - /*is_artificial*/ false, - AddressRange(section_sp, address - section_sp->GetFileAddress(), 0), - /*size_is_valid*/ 0, /*contains_linker_annotations*/ false, - /*flags*/ 0)); + if (record->Number >= m_files->size()) + m_files->resize(record->Number + 1); + FileSpec::Style style = FileSpec::GuessPathStyle(record->Name) + .getValueOr(FileSpec::Style::native); + (*m_files)[record->Number] = FileSpec(record->Name, style); + } +} + +void SymbolFileBreakpad::ParseCUData() { + if (m_cu_data) + return; + + m_cu_data.emplace(); + Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS); + addr_t base = GetBaseFileAddress(); + if (base == LLDB_INVALID_ADDRESS) { + LLDB_LOG(log, "SymbolFile parsing failed: Unable to fetch the base address " + "of object file."); } - // TODO: Process FUNC records as well. + // We shall create one compile unit for each FUNC record. So, count the number + // of FUNC records, and store them in m_cu_data, together with their ranges. + for (LineIterator It(*m_obj_file, Record::Func), End(*m_obj_file); It != End; + ++It) { + if (auto record = FuncRecord::parse(*It)) { + m_cu_data->Append(CompUnitMap::Entry(base + record->Address, record->Size, + CompUnitData(It.GetBookmark()))); + } else + LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It); + } + m_cu_data->Sort(); +} - symtab.CalculateSymbolSizes(); +// Construct the list of support files and line table entries for the given +// compile unit. +void SymbolFileBreakpad::ParseLineTableAndSupportFiles(CompileUnit &cu, + CompUnitData &data) { + addr_t base = GetBaseFileAddress(); + assert(base != LLDB_INVALID_ADDRESS && + "How did we create compile units without a base address?"); + + SupportFileMap map; + data.line_table_up = llvm::make_unique<LineTable>(&cu); + std::unique_ptr<LineSequence> line_seq_up( + data.line_table_up->CreateLineSequenceContainer()); + llvm::Optional<addr_t> next_addr; + auto finish_sequence = [&]() { + data.line_table_up->AppendLineEntryToSequence( + line_seq_up.get(), *next_addr, /*line*/ 0, /*column*/ 0, + /*file_idx*/ 0, /*is_start_of_statement*/ false, + /*is_start_of_basic_block*/ false, /*is_prologue_end*/ false, + /*is_epilogue_begin*/ false, /*is_terminal_entry*/ true); + data.line_table_up->InsertSequence(line_seq_up.get()); + line_seq_up->Clear(); + }; + + LineIterator It(*m_obj_file, Record::Func, data.bookmark), End(*m_obj_file); + assert(Record::classify(*It) == Record::Func); + for (++It; It != End; ++It) { + auto record = LineRecord::parse(*It); + if (!record) + break; + + record->Address += base; + + if (next_addr && *next_addr != record->Address) { + // Discontiguous entries. Finish off the previous sequence and reset. + finish_sequence(); + } + data.line_table_up->AppendLineEntryToSequence( + line_seq_up.get(), record->Address, record->LineNum, /*column*/ 0, + map[record->FileNum], /*is_start_of_statement*/ true, + /*is_start_of_basic_block*/ false, /*is_prologue_end*/ false, + /*is_epilogue_begin*/ false, /*is_terminal_entry*/ false); + next_addr = record->Address + record->Size; + } + if (next_addr) + finish_sequence(); + data.support_files = map.translate(cu, *m_files); +} + +void SymbolFileBreakpad::ParseUnwindData() { + if (m_unwind_data) + return; + + m_unwind_data.emplace(); + Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS); + addr_t base = GetBaseFileAddress(); + if (base == LLDB_INVALID_ADDRESS) { + LLDB_LOG(log, "SymbolFile parsing failed: Unable to fetch the base address " + "of object file."); + } + + for (LineIterator It(*m_obj_file, Record::StackCFI), End(*m_obj_file); + It != End; ++It) { + if (auto record = StackCFIRecord::parse(*It)) { + if (record->Size) + m_unwind_data->Append(UnwindMap::Entry( + base + record->Address, *record->Size, It.GetBookmark())); + } else + LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It); + } + m_unwind_data->Sort(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.h index 68e8d11..8a0b764 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.h
@@ -1,16 +1,19 @@ //===-- SymbolFileBreakpad.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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_PLUGINS_SYMBOLFILE_BREAKPAD_SYMBOLFILEBREAKPAD_H #define LLDB_PLUGINS_SYMBOLFILE_BREAKPAD_SYMBOLFILEBREAKPAD_H +#include "Plugins/ObjectFile/Breakpad/BreakpadRecords.h" +#include "lldb/Core/FileSpecList.h" +#include "lldb/Symbol/LineTable.h" #include "lldb/Symbol/SymbolFile.h" +#include "lldb/Symbol/UnwindPlan.h" namespace lldb_private { @@ -18,9 +21,7 @@ class SymbolFileBreakpad : public SymbolFile { public: - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); static void DebuggerInitialize(Debugger &debugger) {} @@ -34,9 +35,7 @@ return new SymbolFileBreakpad(obj_file); } - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ SymbolFileBreakpad(ObjectFile *object_file) : SymbolFile(object_file) {} ~SymbolFileBreakpad() override {} @@ -45,9 +44,7 @@ void InitializeObject() override {} - //------------------------------------------------------------------ // Compile Unit function calls - //------------------------------------------------------------------ uint32_t GetNumCompileUnits() override; @@ -64,20 +61,18 @@ bool ParseDebugMacros(CompileUnit &comp_unit) override { return false; } bool ParseSupportFiles(CompileUnit &comp_unit, - FileSpecList &support_files) override { - return false; - } + FileSpecList &support_files) override; size_t ParseTypes(CompileUnit &cu) override { return 0; } - bool - ParseImportedModules(const SymbolContext &sc, - std::vector<ConstString> &imported_modules) override { + bool ParseImportedModules( + const SymbolContext &sc, + std::vector<lldb_private::SourceModule> &imported_modules) override { return false; } size_t ParseBlocksRecursive(Function &func) override { return 0; } - uint32_t FindGlobalVariables(const ConstString &name, + uint32_t FindGlobalVariables(ConstString name, const CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, VariableList &variables) override { @@ -99,12 +94,17 @@ lldb::SymbolContextItem resolve_scope, SymbolContext &sc) override; + uint32_t ResolveSymbolContext(const FileSpec &file_spec, uint32_t line, + bool check_inlines, + lldb::SymbolContextItem resolve_scope, + SymbolContextList &sc_list) override; + size_t GetTypes(SymbolContextScope *sc_scope, lldb::TypeClass type_mask, TypeList &type_list) override { return 0; } - uint32_t FindFunctions(const ConstString &name, + uint32_t FindFunctions(ConstString name, const CompilerDeclContext *parent_decl_ctx, lldb::FunctionNameType name_type_mask, bool include_inlines, bool append, @@ -113,7 +113,7 @@ uint32_t FindFunctions(const RegularExpression ®ex, bool include_inlines, bool append, SymbolContextList &sc_list) override; - uint32_t FindTypes(const ConstString &name, + uint32_t FindTypes(ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, @@ -127,17 +127,93 @@ } CompilerDeclContext - FindNamespace(const ConstString &name, + FindNamespace(ConstString name, const CompilerDeclContext *parent_decl_ctx) override { return CompilerDeclContext(); } void AddSymbols(Symtab &symtab) override; + lldb::UnwindPlanSP + GetUnwindPlan(const Address &address, + const RegisterInfoResolver &resolver) override; + ConstString GetPluginName() override { return GetPluginNameStatic(); } uint32_t GetPluginVersion() override { return 1; } private: + // A class representing a position in the breakpad file. Useful for + // remembering the position so we can go back to it later and parse more data. + // Can be converted to/from a LineIterator, but it has a much smaller memory + // footprint. + struct Bookmark { + uint32_t section; + size_t offset; + + friend bool operator<(const Bookmark &lhs, const Bookmark &rhs) { + return std::tie(lhs.section, lhs.offset) < + std::tie(rhs.section, rhs.offset); + } + }; + + // At iterator class for simplifying algorithms reading data from the breakpad + // file. It iterates over all records (lines) in the sections of a given type. + // It also supports saving a specific position (via the GetBookmark() method) + // and then resuming from it afterwards. + class LineIterator; + + // Return an iterator range for all records in the given object file of the + // given type. + llvm::iterator_range<LineIterator> lines(Record::Kind section_type); + + // Breakpad files do not contain sufficient information to correctly + // reconstruct compile units. The approach chosen here is to treat each + // function as a compile unit. The compile unit name is the name if the first + // line entry belonging to this function. + // This class is our internal representation of a compile unit. It stores the + // CompileUnit object and a bookmark pointing to the FUNC record of the + // compile unit function. It also lazily construct the list of support files + // and line table entries for the compile unit, when these are needed. + class CompUnitData { + public: + CompUnitData(Bookmark bookmark) : bookmark(bookmark) {} + + CompUnitData() = default; + CompUnitData(const CompUnitData &rhs) : bookmark(rhs.bookmark) {} + CompUnitData &operator=(const CompUnitData &rhs) { + bookmark = rhs.bookmark; + support_files.reset(); + line_table_up.reset(); + return *this; + } + friend bool operator<(const CompUnitData &lhs, const CompUnitData &rhs) { + return lhs.bookmark < rhs.bookmark; + } + + Bookmark bookmark; + llvm::Optional<FileSpecList> support_files; + std::unique_ptr<LineTable> line_table_up; + + }; + + SymbolVendor &GetSymbolVendor(); + lldb::addr_t GetBaseFileAddress(); + void ParseFileRecords(); + void ParseCUData(); + void ParseLineTableAndSupportFiles(CompileUnit &cu, CompUnitData &data); + void ParseUnwindData(); + bool ParseUnwindRow(llvm::StringRef unwind_rules, + const RegisterInfoResolver &resolver, + UnwindPlan::Row &row); + + using CompUnitMap = RangeDataVector<lldb::addr_t, lldb::addr_t, CompUnitData>; + + llvm::Optional<std::vector<FileSpec>> m_files; + llvm::Optional<CompUnitMap> m_cu_data; + + using UnwindMap = RangeDataVector<lldb::addr_t, lldb::addr_t, Bookmark>; + llvm::Optional<UnwindMap> m_unwind_data; + llvm::BumpPtrAllocator m_allocator; }; } // namespace breakpad
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.cpp index db75cf9..9ae047d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.cpp
@@ -1,14 +1,12 @@ //===-- AppleDWARFIndex.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "Plugins/SymbolFile/DWARF/AppleDWARFIndex.h" -#include "Plugins/SymbolFile/DWARF/DWARFDebugInfo.h" #include "Plugins/SymbolFile/DWARF/DWARFDeclContext.h" #include "Plugins/SymbolFile/DWARF/DWARFUnit.h" #include "Plugins/SymbolFile/DWARF/LogChannelDWARF.h" @@ -75,8 +73,8 @@ return; DWARFMappedHash::DIEInfoArray hash_data; - if (m_apple_names_up->AppendAllDIEsInRange( - cu.GetOffset(), cu.GetNextCompileUnitOffset(), hash_data)) + if (m_apple_names_up->AppendAllDIEsInRange(cu.GetOffset(), + cu.GetNextUnitOffset(), hash_data)) DWARFMappedHash::ExtractDIEArray(hash_data, offsets); } @@ -134,14 +132,14 @@ m_apple_namespaces_up->FindByName(name.GetStringRef(), offsets); } -void AppleDWARFIndex::GetFunctions(ConstString name, DWARFDebugInfo &info, +void AppleDWARFIndex::GetFunctions(ConstString name, SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) { DIEArray offsets; m_apple_names_up->FindByName(name.GetStringRef(), offsets); for (const DIERef &die_ref : offsets) { - ProcessFunctionDIE(name.GetStringRef(), die_ref, info, parent_decl_ctx, + ProcessFunctionDIE(name.GetStringRef(), die_ref, dwarf, parent_decl_ctx, name_type_mask, dies); } } @@ -156,12 +154,12 @@ DWARFMappedHash::ExtractDIEArray(hash_data, offsets); } -void AppleDWARFIndex::ReportInvalidDIEOffset(dw_offset_t offset, - llvm::StringRef name) { +void AppleDWARFIndex::ReportInvalidDIERef(const DIERef &ref, + llvm::StringRef name) { m_module.ReportErrorIfModifyDetected( "the DWARF debug information has been modified (accelerator table had " "bad die 0x%8.8x for '%s')\n", - offset, name.str().c_str()); + ref.die_offset(), name.str().c_str()); } void AppleDWARFIndex::Dump(Stream &s) {
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.h index ea133d0..d15d61e 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/AppleDWARFIndex.h
@@ -1,9 +1,8 @@ //===-- AppleDWARFIndex.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -43,14 +42,13 @@ void GetTypes(ConstString name, DIEArray &offsets) override; void GetTypes(const DWARFDeclContext &context, DIEArray &offsets) override; void GetNamespaces(ConstString name, DIEArray &offsets) override; - void GetFunctions(ConstString name, DWARFDebugInfo &info, + void GetFunctions(ConstString name, SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) override; void GetFunctions(const RegularExpression ®ex, DIEArray &offsets) override; - void ReportInvalidDIEOffset(dw_offset_t offset, - llvm::StringRef name) override; + void ReportInvalidDIERef(const DIERef &ref, llvm::StringRef name) override; void Dump(Stream &s) override; private:
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/CMakeLists.txt index 0a376e2..cd588cb 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/CMakeLists.txt
@@ -4,10 +4,10 @@ DIERef.cpp DWARFAbbreviationDeclaration.cpp DWARFASTParserClang.cpp - DWARFASTParserRust.cpp DWARFAttribute.cpp DWARFBaseDIE.cpp DWARFCompileUnit.cpp + DWARFContext.cpp DWARFDataExtractor.cpp DWARFDebugAbbrev.cpp DWARFDebugAranges.cpp @@ -16,15 +16,13 @@ DWARFDebugInfoEntry.cpp DWARFDebugLine.cpp DWARFDebugMacro.cpp - DWARFDebugMacinfo.cpp - DWARFDebugMacinfoEntry.cpp DWARFDebugRanges.cpp DWARFDeclContext.cpp DWARFDefines.cpp DWARFDIE.cpp - DWARFDIECollection.cpp DWARFFormValue.cpp DWARFIndex.cpp + DWARFTypeUnit.cpp DWARFUnit.cpp HashedNameToDIE.cpp LogChannelDWARF.cpp
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.cpp index 0cd0f0c..f7f2a5b 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.cpp
@@ -1,67 +1,18 @@ //===-- DIERef.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DIERef.h" -#include "DWARFUnit.h" -#include "DWARFDebugInfo.h" -#include "DWARFFormValue.h" -#include "SymbolFileDWARF.h" -#include "SymbolFileDWARFDebugMap.h" +#include "llvm/Support/Format.h" -DIERef::DIERef(lldb::user_id_t uid, SymbolFileDWARF *dwarf) - : cu_offset(DW_INVALID_OFFSET), die_offset(uid & 0xffffffff) { - SymbolFileDWARFDebugMap *debug_map = dwarf->GetDebugMapSymfile(); - if (debug_map) { - const uint32_t oso_idx = debug_map->GetOSOIndexFromUserID(uid); - SymbolFileDWARF *actual_dwarf = debug_map->GetSymbolFileByOSOIndex(oso_idx); - if (actual_dwarf) { - DWARFDebugInfo *debug_info = actual_dwarf->DebugInfo(); - if (debug_info) { - DWARFUnit *dwarf_cu = - debug_info->GetCompileUnitContainingDIEOffset(die_offset); - if (dwarf_cu) { - cu_offset = dwarf_cu->GetOffset(); - return; - } - } - } - die_offset = DW_INVALID_OFFSET; - } else { - cu_offset = uid >> 32; - } -} - -DIERef::DIERef(const DWARFFormValue &form_value) - : cu_offset(DW_INVALID_OFFSET), die_offset(DW_INVALID_OFFSET) { - if (form_value.IsValid()) { - const DWARFUnit *dwarf_cu = form_value.GetCompileUnit(); - if (dwarf_cu) { - if (dwarf_cu->GetBaseObjOffset() != DW_INVALID_OFFSET) - cu_offset = dwarf_cu->GetBaseObjOffset(); - else - cu_offset = dwarf_cu->GetOffset(); - } - die_offset = form_value.Reference(); - } -} - -lldb::user_id_t DIERef::GetUID(SymbolFileDWARF *dwarf) const { - //---------------------------------------------------------------------- - // Each SymbolFileDWARF will set its ID to what is expected. - // - // SymbolFileDWARF, when used for DWARF with .o files on MacOSX, has the - // ID set to the compile unit index. - // - // SymbolFileDWARFDwo sets the ID to the compile unit offset. - //---------------------------------------------------------------------- - if (dwarf && die_offset != DW_INVALID_OFFSET) - return dwarf->GetID() | die_offset; - else - return LLDB_INVALID_UID; +void llvm::format_provider<DIERef>::format(const DIERef &ref, raw_ostream &OS, + StringRef Style) { + if (ref.dwo_num()) + OS << format_hex_no_prefix(*ref.dwo_num(), 8) << "/"; + OS << (ref.section() == DIERef::DebugInfo ? "INFO" : "TYPE"); + OS << "/" << format_hex_no_prefix(ref.die_offset(), 8); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.h index df17e14..5546bb7 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DIERef.h
@@ -1,9 +1,8 @@ //===-- DIERef.h ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,50 +10,54 @@ #define SymbolFileDWARF_DIERef_h_ #include "lldb/Core/dwarf.h" -#include "lldb/lldb-defines.h" +#include "llvm/ADT/Optional.h" +#include "llvm/Support/FormatProviders.h" +#include <cassert> +#include <vector> -class DWARFFormValue; -class SymbolFileDWARF; +/// Identifies a DWARF debug info entry within a given Module. It contains three +/// "coordinates": +/// - dwo_num: identifies the dwo file in the Module. If this field is not set, +/// the DIERef references the main file. +/// - section: identifies the section of the debug info entry in the given file: +/// debug_info or debug_types. +/// - die_offset: The offset of the debug info entry as an absolute offset from +/// the beginning of the section specified in the section field. +class DIERef { +public: + enum Section : uint8_t { DebugInfo, DebugTypes }; -struct DIERef { - DIERef() = default; - - DIERef(dw_offset_t c, dw_offset_t d) : cu_offset(c), die_offset(d) {} - - //---------------------------------------------------------------------- - // In order to properly decode a lldb::user_id_t back into a DIERef we - // need the DWARF file since it knows if DWARF in .o files is being used - // (MacOSX) or if DWO files are being used. The encoding of the user ID - // differs between the two types of DWARF. - //---------------------------------------------------------------------- - explicit DIERef(lldb::user_id_t uid, SymbolFileDWARF *dwarf); - - explicit DIERef(const DWARFFormValue &form_value); - - //---------------------------------------------------------------------- - // In order to properly encode a DIERef unto a lldb::user_id_t we need - // the DWARF file since it knows if DWARF in .o files is being used - // (MacOSX) or if DWO files are being used. The encoding of the user ID - // differs between the two types of DWARF. - //---------------------------------------------------------------------- - lldb::user_id_t GetUID(SymbolFileDWARF *dwarf) const; - - bool operator<(const DIERef &ref) const { - return die_offset < ref.die_offset; + DIERef(llvm::Optional<uint32_t> dwo_num, Section section, + dw_offset_t die_offset) + : m_dwo_num(dwo_num.getValueOr(0)), m_dwo_num_valid(bool(dwo_num)), + m_section(section), m_die_offset(die_offset) { + assert(this->dwo_num() == dwo_num && "Dwo number out of range?"); } - bool operator<(const DIERef &ref) { return die_offset < ref.die_offset; } - - explicit operator bool() const { - return cu_offset != DW_INVALID_OFFSET || die_offset != DW_INVALID_OFFSET; + llvm::Optional<uint32_t> dwo_num() const { + if (m_dwo_num_valid) + return m_dwo_num; + return llvm::None; } - bool operator==(const DIERef &ref) const { return die_offset == ref.die_offset; } + Section section() const { return static_cast<Section>(m_section); } - dw_offset_t cu_offset = DW_INVALID_OFFSET; - dw_offset_t die_offset = DW_INVALID_OFFSET; + dw_offset_t die_offset() const { return m_die_offset; } + +private: + uint32_t m_dwo_num : 30; + uint32_t m_dwo_num_valid : 1; + uint32_t m_section : 1; + dw_offset_t m_die_offset; }; +static_assert(sizeof(DIERef) == 8, ""); typedef std::vector<DIERef> DIEArray; +namespace llvm { +template<> struct format_provider<DIERef> { + static void format(const DIERef &ref, raw_ostream &OS, StringRef Style); +}; +} // namespace llvm + #endif // SymbolFileDWARF_DIERef_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParser.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParser.h index 24d5f26..e7927b31 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParser.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParser.h
@@ -1,9 +1,8 @@ //===-- DWARFASTParser.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp index 70d48e5..b85ab54 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp
@@ -1,9 +1,8 @@ //===-- DWARFASTParserClang.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,7 +10,6 @@ #include "DWARFASTParserClang.h" #include "DWARFDIE.h" -#include "DWARFDIECollection.h" #include "DWARFDebugInfo.h" #include "DWARFDeclContext.h" #include "DWARFDefines.h" @@ -44,6 +42,7 @@ #include "clang/AST/DeclTemplate.h" #include <map> +#include <memory> #include <vector> //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN @@ -118,10 +117,10 @@ }; ClangASTImporter &DWARFASTParserClang::GetClangASTImporter() { - if (!m_clang_ast_importer_ap) { - m_clang_ast_importer_ap.reset(new ClangASTImporter); + if (!m_clang_ast_importer_up) { + m_clang_ast_importer_up.reset(new ClangASTImporter); } - return *m_clang_ast_importer_ap; + return *m_clang_ast_importer_up; } /// Detect a forward declaration that is nested in a DW_TAG_module. @@ -156,8 +155,8 @@ // Since this this type is defined in one of the Clang modules imported by // this symbol file, search all of them. - auto *sym_file = die.GetCU()->GetSymbolFileDWARF(); - for (const auto &name_module : sym_file->getExternalTypeModules()) { + auto &sym_file = die.GetCU()->GetSymbolFileDWARF(); + for (const auto &name_module : sym_file.getExternalTypeModules()) { if (!name_module.second) continue; SymbolVendor *sym_vendor = name_module.second->GetSymbolVendor(); @@ -186,7 +185,7 @@ SymbolFileDWARF *dwarf = die.GetDWARF(); TypeSP type_sp(new Type( die.GetID(), dwarf, dwo_type_sp->GetName(), dwo_type_sp->GetByteSize(), - NULL, LLDB_INVALID_UID, Type::eEncodingInvalid, + nullptr, LLDB_INVALID_UID, Type::eEncodingInvalid, &dwo_type_sp->GetDeclaration(), type, Type::eResolveStateForward)); dwarf->GetTypeList()->Insert(type_sp); @@ -229,1676 +228,1454 @@ } } +namespace { +/// Parsed form of all attributes that are relevant for type reconstruction. +/// Some attributes are relevant for all kinds of types (declaration), while +/// others are only meaningful to a specific type (is_virtual) +struct ParsedTypeAttributes { + explicit ParsedTypeAttributes(const DWARFDIE &die); + + AccessType accessibility = eAccessNone; + bool is_artificial = false; + bool is_complete_objc_class = false; + bool is_explicit = false; + bool is_forward_declaration = false; + bool is_inline = false; + bool is_scoped_enum = false; + bool is_vector = false; + bool is_virtual = false; + clang::StorageClass storage = clang::SC_None; + const char *mangled_name = nullptr; + ConstString name; + Declaration decl; + DWARFDIE object_pointer; + DWARFFormValue abstract_origin; + DWARFFormValue containing_type; + DWARFFormValue signature; + DWARFFormValue specification; + DWARFFormValue type; + LanguageType class_language = eLanguageTypeUnknown; + llvm::Optional<uint64_t> byte_size; + size_t calling_convention = llvm::dwarf::DW_CC_normal; + uint32_t bit_stride = 0; + uint32_t byte_stride = 0; + uint32_t encoding = 0; +}; +} // namespace + +ParsedTypeAttributes::ParsedTypeAttributes(const DWARFDIE &die) { + DWARFAttributes attributes; + size_t num_attributes = die.GetAttributes(attributes); + for (size_t i = 0; i < num_attributes; ++i) { + dw_attr_t attr = attributes.AttributeAtIndex(i); + DWARFFormValue form_value; + if (!attributes.ExtractFormValueAtIndex(i, form_value)) + continue; + switch (attr) { + case DW_AT_abstract_origin: + abstract_origin = form_value; + break; + + case DW_AT_accessibility: + accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); + break; + + case DW_AT_artificial: + is_artificial = form_value.Boolean(); + break; + + case DW_AT_bit_stride: + bit_stride = form_value.Unsigned(); + break; + + case DW_AT_byte_size: + byte_size = form_value.Unsigned(); + break; + + case DW_AT_byte_stride: + byte_stride = form_value.Unsigned(); + break; + + case DW_AT_calling_convention: + calling_convention = form_value.Unsigned(); + break; + + case DW_AT_containing_type: + containing_type = form_value; + break; + + case DW_AT_decl_file: + decl.SetFile(die.GetCU()->GetFile(form_value.Unsigned())); + break; + case DW_AT_decl_line: + decl.SetLine(form_value.Unsigned()); + break; + case DW_AT_decl_column: + decl.SetColumn(form_value.Unsigned()); + break; + + case DW_AT_declaration: + is_forward_declaration = form_value.Boolean(); + break; + + case DW_AT_encoding: + encoding = form_value.Unsigned(); + break; + + case DW_AT_enum_class: + is_scoped_enum = form_value.Boolean(); + break; + + case DW_AT_explicit: + is_explicit = form_value.Boolean(); + break; + + case DW_AT_external: + if (form_value.Unsigned()) + storage = clang::SC_Extern; + break; + + case DW_AT_inline: + is_inline = form_value.Boolean(); + break; + + case DW_AT_linkage_name: + case DW_AT_MIPS_linkage_name: + mangled_name = form_value.AsCString(); + break; + + case DW_AT_name: + name.SetCString(form_value.AsCString()); + break; + + case DW_AT_object_pointer: + object_pointer = form_value.Reference(); + break; + + case DW_AT_signature: + signature = form_value; + break; + + case DW_AT_specification: + specification = form_value; + break; + + case DW_AT_type: + type = form_value; + break; + + case DW_AT_virtuality: + is_virtual = form_value.Boolean(); + break; + + case DW_AT_APPLE_objc_complete_type: + is_complete_objc_class = form_value.Signed(); + break; + + case DW_AT_APPLE_runtime_class: + class_language = (LanguageType)form_value.Signed(); + break; + + case DW_AT_GNU_vector: + is_vector = form_value.Boolean(); + break; + } + } +} + +static std::string GetUnitName(const DWARFDIE &die) { + if (DWARFUnit *unit = die.GetCU()) + return unit->GetAbsolutePath().GetPath(); + return "<missing DWARF unit path>"; +} + TypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc, const DWARFDIE &die, Log *log, bool *type_is_new_ptr) { - TypeSP type_sp; - if (type_is_new_ptr) *type_is_new_ptr = false; - AccessType accessibility = eAccessNone; - if (die) { - SymbolFileDWARF *dwarf = die.GetDWARF(); - if (log) { - DWARFDIE context_die; - clang::DeclContext *context = - GetClangDeclContextContainingDIE(die, &context_die); + if (!die) + return nullptr; + SymbolFileDWARF *dwarf = die.GetDWARF(); + if (log) { + DWARFDIE context_die; + clang::DeclContext *context = + GetClangDeclContextContainingDIE(die, &context_die); - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die " - "0x%8.8x)) %s name = '%s')", - die.GetOffset(), static_cast<void *>(context), - context_die.GetOffset(), die.GetTagAsCString(), die.GetName()); + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die " + "0x%8.8x)) %s name = '%s')", + die.GetOffset(), static_cast<void *>(context), context_die.GetOffset(), + die.GetTagAsCString(), die.GetName()); + } + + + Type *type_ptr = dwarf->GetDIEToType().lookup(die.GetDIE()); + if (type_ptr == DIE_IS_BEING_PARSED) + return nullptr; + if (type_ptr) + return type_ptr->shared_from_this(); + // Set a bit that lets us know that we are currently parsing this + dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED; + + ParsedTypeAttributes attrs(die); + + if (DWARFDIE signature_die = attrs.signature.Reference()) { + if (TypeSP type_sp = + ParseTypeFromDWARF(sc, signature_die, log, type_is_new_ptr)) { + dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); + if (clang::DeclContext *decl_ctx = + GetCachedClangDeclContextForDIE(signature_die)) + LinkDeclContextToDIE(decl_ctx, die); + return type_sp; } - Type *type_ptr = dwarf->GetDIEToType().lookup(die.GetDIE()); - TypeList *type_list = dwarf->GetTypeList(); - if (type_ptr == NULL) { - if (type_is_new_ptr) - *type_is_new_ptr = true; + return nullptr; + } - const dw_tag_t tag = die.Tag(); + TypeList *type_list = dwarf->GetTypeList(); + if (type_is_new_ptr) + *type_is_new_ptr = true; - bool is_forward_declaration = false; - DWARFAttributes attributes; - const char *type_name_cstr = NULL; - const char *mangled_name_cstr = NULL; - ConstString type_name_const_str; - Type::ResolveState resolve_state = Type::eResolveStateUnresolved; - uint64_t byte_size = 0; - Declaration decl; + const dw_tag_t tag = die.Tag(); - Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID; - CompilerType clang_type; - DWARFFormValue form_value; + Type::ResolveState resolve_state = Type::eResolveStateUnresolved; - dw_attr_t attr; + Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID; + CompilerType clang_type; - switch (tag) { - case DW_TAG_typedef: - case DW_TAG_base_type: - case DW_TAG_pointer_type: - case DW_TAG_reference_type: - case DW_TAG_rvalue_reference_type: - case DW_TAG_const_type: - case DW_TAG_restrict_type: - case DW_TAG_volatile_type: - case DW_TAG_unspecified_type: { - // Set a bit that lets us know that we are currently parsing this - dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED; + TypeSP type_sp; + LanguageType cu_language = die.GetLanguage(); + switch (tag) { + case DW_TAG_typedef: + case DW_TAG_base_type: + case DW_TAG_pointer_type: + case DW_TAG_reference_type: + case DW_TAG_rvalue_reference_type: + case DW_TAG_const_type: + case DW_TAG_restrict_type: + case DW_TAG_volatile_type: + case DW_TAG_unspecified_type: { + if (tag == DW_TAG_typedef && attrs.type.IsValid()) { + // Try to parse a typedef from the DWO file first as modules can + // contain typedef'ed structures that have no names like: + // + // typedef struct { int a; } Foo; + // + // In this case we will have a structure with no name and a typedef + // named "Foo" that points to this unnamed structure. The name in the + // typedef is the only identifier for the struct, so always try to + // get typedefs from DWO files if possible. + // + // The type_sp returned will be empty if the typedef doesn't exist in + // a DWO file, so it is cheap to call this function just to check. + // + // If we don't do this we end up creating a TypeSP that says this is + // a typedef to type 0x123 (the DW_AT_type value would be 0x123 in + // the DW_TAG_typedef), and this is the unnamed structure type. We + // will have a hard time tracking down an unnammed structure type in + // the module DWO file, so we make sure we don't get into this + // situation by always resolving typedefs from the DWO file. + const DWARFDIE encoding_die = attrs.type.Reference(); - const size_t num_attributes = die.GetAttributes(attributes); - uint32_t encoding = 0; - DWARFFormValue encoding_uid; + // First make sure that the die that this is typedef'ed to _is_ just + // a declaration (DW_AT_declaration == 1), not a full definition + // since template types can't be represented in modules since only + // concrete instances of templates are ever emitted and modules won't + // contain those + if (encoding_die && + encoding_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) { + type_sp = ParseTypeFromDWO(die, log); + if (type_sp) + return type_sp; + } + } - if (num_attributes > 0) { - uint32_t i; - for (i = 0; i < num_attributes; ++i) { - attr = attributes.AttributeAtIndex(i); - if (attributes.ExtractFormValueAtIndex(i, form_value)) { - switch (attr) { - case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; - case DW_AT_name: - type_name_cstr = form_value.AsCString(); - if (type_name_cstr) - type_name_const_str.SetCString(type_name_cstr); - break; - case DW_AT_byte_size: - byte_size = form_value.Unsigned(); - break; - case DW_AT_encoding: - encoding = form_value.Unsigned(); - break; - case DW_AT_type: - encoding_uid = form_value; - break; - default: - case DW_AT_sibling: - break; + DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n", + die.GetID(), DW_TAG_value_to_name(tag), type_name_cstr, + encoding_uid.Reference()); + + switch (tag) { + default: + break; + + case DW_TAG_unspecified_type: + if (attrs.name == "nullptr_t" || attrs.name == "decltype(nullptr)") { + resolve_state = Type::eResolveStateFull; + clang_type = m_ast.GetBasicType(eBasicTypeNullPtr); + break; + } + // Fall through to base type below in case we can handle the type + // there... + LLVM_FALLTHROUGH; + + case DW_TAG_base_type: + resolve_state = Type::eResolveStateFull; + clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize( + attrs.name.GetCString(), attrs.encoding, + attrs.byte_size.getValueOr(0) * 8); + break; + + case DW_TAG_pointer_type: + encoding_data_type = Type::eEncodingIsPointerUID; + break; + case DW_TAG_reference_type: + encoding_data_type = Type::eEncodingIsLValueReferenceUID; + break; + case DW_TAG_rvalue_reference_type: + encoding_data_type = Type::eEncodingIsRValueReferenceUID; + break; + case DW_TAG_typedef: + encoding_data_type = Type::eEncodingIsTypedefUID; + break; + case DW_TAG_const_type: + encoding_data_type = Type::eEncodingIsConstUID; + break; + case DW_TAG_restrict_type: + encoding_data_type = Type::eEncodingIsRestrictUID; + break; + case DW_TAG_volatile_type: + encoding_data_type = Type::eEncodingIsVolatileUID; + break; + } + + if (!clang_type && (encoding_data_type == Type::eEncodingIsPointerUID || + encoding_data_type == Type::eEncodingIsTypedefUID)) { + if (tag == DW_TAG_pointer_type) { + DWARFDIE target_die = die.GetReferencedDIE(DW_AT_type); + + if (target_die.GetAttributeValueAsUnsigned(DW_AT_APPLE_block, 0)) { + // Blocks have a __FuncPtr inside them which is a pointer to a + // function of the proper type. + + for (DWARFDIE child_die = target_die.GetFirstChild(); + child_die.IsValid(); child_die = child_die.GetSibling()) { + if (!strcmp(child_die.GetAttributeValueAsString(DW_AT_name, ""), + "__FuncPtr")) { + DWARFDIE function_pointer_type = + child_die.GetReferencedDIE(DW_AT_type); + + if (function_pointer_type) { + DWARFDIE function_type = + function_pointer_type.GetReferencedDIE(DW_AT_type); + + bool function_type_is_new_pointer; + TypeSP lldb_function_type_sp = ParseTypeFromDWARF( + sc, function_type, log, &function_type_is_new_pointer); + + if (lldb_function_type_sp) { + clang_type = m_ast.CreateBlockPointerType( + lldb_function_type_sp->GetForwardCompilerType()); + encoding_data_type = Type::eEncodingIsUID; + attrs.type.Clear(); + resolve_state = Type::eResolveStateFull; + } + } + + break; + } + } + } + } + + if (cu_language == eLanguageTypeObjC || + cu_language == eLanguageTypeObjC_plus_plus) { + if (attrs.name) { + static ConstString g_objc_type_name_id("id"); + static ConstString g_objc_type_name_Class("Class"); + static ConstString g_objc_type_name_selector("SEL"); + + if (attrs.name == g_objc_type_name_id) { + if (log) + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' " + "is Objective-C 'id' built-in type.", + die.GetOffset(), die.GetTagAsCString(), die.GetName()); + clang_type = m_ast.GetBasicType(eBasicTypeObjCID); + encoding_data_type = Type::eEncodingIsUID; + attrs.type.Clear(); + resolve_state = Type::eResolveStateFull; + + } else if (attrs.name == g_objc_type_name_Class) { + if (log) + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' " + "is Objective-C 'Class' built-in type.", + die.GetOffset(), die.GetTagAsCString(), die.GetName()); + clang_type = m_ast.GetBasicType(eBasicTypeObjCClass); + encoding_data_type = Type::eEncodingIsUID; + attrs.type.Clear(); + resolve_state = Type::eResolveStateFull; + } else if (attrs.name == g_objc_type_name_selector) { + if (log) + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' " + "is Objective-C 'selector' built-in type.", + die.GetOffset(), die.GetTagAsCString(), die.GetName()); + clang_type = m_ast.GetBasicType(eBasicTypeObjCSel); + encoding_data_type = Type::eEncodingIsUID; + attrs.type.Clear(); + resolve_state = Type::eResolveStateFull; + } + } else if (encoding_data_type == Type::eEncodingIsPointerUID && + attrs.type.IsValid()) { + // Clang sometimes erroneously emits id as objc_object*. In that + // case we fix up the type to "id". + + const DWARFDIE encoding_die = attrs.type.Reference(); + + if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) { + if (const char *struct_name = encoding_die.GetName()) { + if (!strcmp(struct_name, "objc_object")) { + if (log) + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s " + "'%s' is 'objc_object*', which we overrode to " + "'id'.", + die.GetOffset(), die.GetTagAsCString(), die.GetName()); + clang_type = m_ast.GetBasicType(eBasicTypeObjCID); + encoding_data_type = Type::eEncodingIsUID; + attrs.type.Clear(); + resolve_state = Type::eResolveStateFull; } } } } + } + } - if (tag == DW_TAG_typedef && encoding_uid.IsValid()) { - // Try to parse a typedef from the DWO file first as modules can - // contain typedef'ed structures that have no names like: - // - // typedef struct { int a; } Foo; - // - // In this case we will have a structure with no name and a typedef - // named "Foo" that points to this unnamed structure. The name in the - // typedef is the only identifier for the struct, so always try to - // get typedefs from DWO files if possible. - // - // The type_sp returned will be empty if the typedef doesn't exist in - // a DWO file, so it is cheap to call this function just to check. - // - // If we don't do this we end up creating a TypeSP that says this is - // a typedef to type 0x123 (the DW_AT_type value would be 0x123 in - // the DW_TAG_typedef), and this is the unnamed structure type. We - // will have a hard time tracking down an unnammed structure type in - // the module DWO file, so we make sure we don't get into this - // situation by always resolving typedefs from the DWO file. - const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid)); + type_sp = std::make_shared<Type>( + die.GetID(), dwarf, attrs.name, attrs.byte_size, nullptr, + dwarf->GetUID(attrs.type.Reference()), encoding_data_type, &attrs.decl, + clang_type, resolve_state); - // First make sure that the die that this is typedef'ed to _is_ just - // a declaration (DW_AT_declaration == 1), not a full definition - // since template types can't be represented in modules since only - // concrete instances of templates are ever emitted and modules won't - // contain those - if (encoding_die && - encoding_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == - 1) { - type_sp = ParseTypeFromDWO(die, log); - if (type_sp) - return type_sp; + dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); + } break; + + case DW_TAG_structure_type: + case DW_TAG_union_type: + case DW_TAG_class_type: { + // UniqueDWARFASTType is large, so don't create a local variables on + // the stack, put it on the heap. This function is often called + // recursively and clang isn't good and sharing the stack space for + // variables in different blocks. + std::unique_ptr<UniqueDWARFASTType> unique_ast_entry_up( + new UniqueDWARFASTType()); + + ConstString unique_typename(attrs.name); + Declaration unique_decl(attrs.decl); + + if (attrs.name) { + if (Language::LanguageIsCPlusPlus(cu_language)) { + // For C++, we rely solely upon the one definition rule that says + // only one thing can exist at a given decl context. We ignore the + // file and line that things are declared on. + std::string qualified_name; + if (die.GetQualifiedName(qualified_name)) + unique_typename = ConstString(qualified_name); + unique_decl.Clear(); + } + + if (dwarf->GetUniqueDWARFASTTypeMap().Find( + unique_typename, die, unique_decl, attrs.byte_size.getValueOr(-1), + *unique_ast_entry_up)) { + type_sp = unique_ast_entry_up->m_type_sp; + if (type_sp) { + dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); + return type_sp; + } + } + } + + DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), + DW_TAG_value_to_name(tag), type_name_cstr); + + int tag_decl_kind = -1; + AccessType default_accessibility = eAccessNone; + if (tag == DW_TAG_structure_type) { + tag_decl_kind = clang::TTK_Struct; + default_accessibility = eAccessPublic; + } else if (tag == DW_TAG_union_type) { + tag_decl_kind = clang::TTK_Union; + default_accessibility = eAccessPublic; + } else if (tag == DW_TAG_class_type) { + tag_decl_kind = clang::TTK_Class; + default_accessibility = eAccessPrivate; + } + + if (attrs.byte_size && *attrs.byte_size == 0 && attrs.name && + !die.HasChildren() && cu_language == eLanguageTypeObjC) { + // Work around an issue with clang at the moment where forward + // declarations for objective C classes are emitted as: + // DW_TAG_structure_type [2] + // DW_AT_name( "ForwardObjcClass" ) + // DW_AT_byte_size( 0x00 ) + // DW_AT_decl_file( "..." ) + // DW_AT_decl_line( 1 ) + // + // Note that there is no DW_AT_declaration and there are no children, + // and the byte size is zero. + attrs.is_forward_declaration = true; + } + + if (attrs.class_language == eLanguageTypeObjC || + attrs.class_language == eLanguageTypeObjC_plus_plus) { + if (!attrs.is_complete_objc_class && + die.Supports_DW_AT_APPLE_objc_complete_type()) { + // We have a valid eSymbolTypeObjCClass class symbol whose name + // matches the current objective C class that we are trying to find + // and this DIE isn't the complete definition (we checked + // is_complete_objc_class above and know it is false), so the real + // definition is in here somewhere + type_sp = + dwarf->FindCompleteObjCDefinitionTypeForDIE(die, attrs.name, true); + + if (!type_sp) { + SymbolFileDWARFDebugMap *debug_map_symfile = + dwarf->GetDebugMapSymfile(); + if (debug_map_symfile) { + // We weren't able to find a full declaration in this DWARF, + // see if we have a declaration anywhere else... + type_sp = debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE( + die, attrs.name, true); } } - DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n", - die.GetID(), DW_TAG_value_to_name(tag), type_name_cstr, - encoding_uid.Reference()); - - switch (tag) { - default: - break; - - case DW_TAG_unspecified_type: - if (strcmp(type_name_cstr, "nullptr_t") == 0 || - strcmp(type_name_cstr, "decltype(nullptr)") == 0) { - resolve_state = Type::eResolveStateFull; - clang_type = m_ast.GetBasicType(eBasicTypeNullPtr); - break; + if (type_sp) { + if (log) { + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an " + "incomplete objc type, complete type is 0x%8.8" PRIx64, + static_cast<void *>(this), die.GetOffset(), + DW_TAG_value_to_name(tag), attrs.name.GetCString(), + type_sp->GetID()); } - // Fall through to base type below in case we can handle the type - // there... - LLVM_FALLTHROUGH; - case DW_TAG_base_type: - resolve_state = Type::eResolveStateFull; - clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize( - type_name_cstr, encoding, byte_size * 8); - break; + // We found a real definition for this type elsewhere so lets use + // it and cache the fact that we found a complete type for this + // die + dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); + return type_sp; + } + } + } - case DW_TAG_pointer_type: - encoding_data_type = Type::eEncodingIsPointerUID; - break; - case DW_TAG_reference_type: - encoding_data_type = Type::eEncodingIsLValueReferenceUID; - break; - case DW_TAG_rvalue_reference_type: - encoding_data_type = Type::eEncodingIsRValueReferenceUID; - break; + if (attrs.is_forward_declaration) { + // We have a forward declaration to a type and we need to try and + // find a full declaration. We look in the current type index just in + // case we have a forward declaration followed by an actual + // declarations in the DWARF. If this fails, we need to look + // elsewhere... + if (log) { + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a " + "forward declaration, trying to find complete type", + static_cast<void *>(this), die.GetOffset(), + DW_TAG_value_to_name(tag), attrs.name.GetCString()); + } + + // See if the type comes from a DWO module and if so, track down that + // type. + type_sp = ParseTypeFromDWO(die, log); + if (type_sp) + return type_sp; + + DWARFDeclContext die_decl_ctx; + die.GetDWARFDeclContext(die_decl_ctx); + + // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, + // type_name_const_str); + type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx); + + if (!type_sp) { + SymbolFileDWARFDebugMap *debug_map_symfile = + dwarf->GetDebugMapSymfile(); + if (debug_map_symfile) { + // We weren't able to find a full declaration in this DWARF, see + // if we have a declaration anywhere else... + type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext( + die_decl_ctx); + } + } + + if (type_sp) { + if (log) { + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a " + "forward declaration, complete type is 0x%8.8" PRIx64, + static_cast<void *>(this), die.GetOffset(), + DW_TAG_value_to_name(tag), attrs.name.GetCString(), + type_sp->GetID()); + } + + // We found a real definition for this type elsewhere so lets use + // it and cache the fact that we found a complete type for this die + dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); + clang::DeclContext *defn_decl_ctx = + GetCachedClangDeclContextForDIE(dwarf->GetDIE(type_sp->GetID())); + if (defn_decl_ctx) + LinkDeclContextToDIE(defn_decl_ctx, die); + return type_sp; + } + } + assert(tag_decl_kind != -1); + bool clang_type_was_created = false; + clang_type.SetCompilerType( + &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE())); + if (!clang_type) { + clang::DeclContext *decl_ctx = + GetClangDeclContextContainingDIE(die, nullptr); + + // If your decl context is a record that was imported from another + // AST context (in the gmodules case), we need to make sure the type + // backing the Decl is complete before adding children to it. This is + // not an issue in the non-gmodules case because the debug info will + // always contain a full definition of parent types in that case. + CompleteExternalTagDeclType(GetClangASTImporter(), decl_ctx, die, + attrs.name.GetCString()); + + if (attrs.accessibility == eAccessNone && decl_ctx) { + // Check the decl context that contains this class/struct/union. If + // it is a class we must give it an accessibility. + const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind(); + if (DeclKindIsCXXClass(containing_decl_kind)) + attrs.accessibility = default_accessibility; + } + + ClangASTMetadata metadata; + metadata.SetUserID(die.GetID()); + metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die)); + + if (attrs.name.GetStringRef().contains('<')) { + ClangASTContext::TemplateParameterInfos template_param_infos; + if (ParseTemplateParameterInfos(die, template_param_infos)) { + clang::ClassTemplateDecl *class_template_decl = + m_ast.ParseClassTemplateDecl(decl_ctx, attrs.accessibility, + attrs.name.GetCString(), + tag_decl_kind, template_param_infos); + if (!class_template_decl) { + if (log) { + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" " + "clang::ClassTemplateDecl failed to return a decl.", + static_cast<void *>(this), die.GetOffset(), + DW_TAG_value_to_name(tag), attrs.name.GetCString()); + } + return TypeSP(); + } + + clang::ClassTemplateSpecializationDecl *class_specialization_decl = + m_ast.CreateClassTemplateSpecializationDecl( + decl_ctx, class_template_decl, tag_decl_kind, + template_param_infos); + clang_type = m_ast.CreateClassTemplateSpecializationType( + class_specialization_decl); + clang_type_was_created = true; + + m_ast.SetMetadata(class_template_decl, metadata); + m_ast.SetMetadata(class_specialization_decl, metadata); + } + } + + if (!clang_type_was_created) { + clang_type_was_created = true; + clang_type = m_ast.CreateRecordType( + decl_ctx, attrs.accessibility, attrs.name.GetCString(), + tag_decl_kind, attrs.class_language, &metadata); + } + } + + // Store a forward declaration to this class type in case any + // parameters in any class methods need it for the clang types for + // function prototypes. + LinkDeclContextToDIE(m_ast.GetDeclContextForType(clang_type), die); + type_sp = std::make_shared<Type>(die.GetID(), dwarf, attrs.name, + attrs.byte_size, nullptr, LLDB_INVALID_UID, + Type::eEncodingIsUID, &attrs.decl, clang_type, + Type::eResolveStateForward); + + type_sp->SetIsCompleteObjCClass(attrs.is_complete_objc_class); + + // Add our type to the unique type map so we don't end up creating many + // copies of the same type over and over in the ASTContext for our + // module + unique_ast_entry_up->m_type_sp = type_sp; + unique_ast_entry_up->m_die = die; + unique_ast_entry_up->m_declaration = unique_decl; + unique_ast_entry_up->m_byte_size = attrs.byte_size.getValueOr(0); + dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename, + *unique_ast_entry_up); + + if (attrs.is_forward_declaration && die.HasChildren()) { + // Check to see if the DIE actually has a definition, some version of + // GCC will + // emit DIEs with DW_AT_declaration set to true, but yet still have + // subprogram, members, or inheritance, so we can't trust it + DWARFDIE child_die = die.GetFirstChild(); + while (child_die) { + switch (child_die.Tag()) { + case DW_TAG_inheritance: + case DW_TAG_subprogram: + case DW_TAG_member: + case DW_TAG_APPLE_property: + case DW_TAG_class_type: + case DW_TAG_structure_type: + case DW_TAG_enumeration_type: case DW_TAG_typedef: - encoding_data_type = Type::eEncodingIsTypedefUID; + case DW_TAG_union_type: + child_die.Clear(); + attrs.is_forward_declaration = false; break; - case DW_TAG_const_type: - encoding_data_type = Type::eEncodingIsConstUID; - break; - case DW_TAG_restrict_type: - encoding_data_type = Type::eEncodingIsRestrictUID; - break; - case DW_TAG_volatile_type: - encoding_data_type = Type::eEncodingIsVolatileUID; + default: + child_die = child_die.GetSibling(); break; } + } + } - if (!clang_type && - (encoding_data_type == Type::eEncodingIsPointerUID || - encoding_data_type == Type::eEncodingIsTypedefUID)) { - if (tag == DW_TAG_pointer_type) { - DWARFDIE target_die = die.GetReferencedDIE(DW_AT_type); + if (!attrs.is_forward_declaration) { + // Always start the definition for a class type so that if the class + // has child classes or types that require the class to be created + // for use as their decl contexts the class will be ready to accept + // these child definitions. + if (!die.HasChildren()) { + // No children for this struct/union/class, lets finish it + if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) { + ClangASTContext::CompleteTagDeclarationDefinition(clang_type); + } else { + dwarf->GetObjectFile()->GetModule()->ReportError( + "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its " + "definition.\nPlease file a bug and attach the file at the " + "start of this error message", + die.GetOffset(), attrs.name.GetCString()); + } - if (target_die.GetAttributeValueAsUnsigned(DW_AT_APPLE_block, 0)) { - // Blocks have a __FuncPtr inside them which is a pointer to a - // function of the proper type. + if (tag == DW_TAG_structure_type) // this only applies in C + { + clang::RecordDecl *record_decl = + ClangASTContext::GetAsRecordDecl(clang_type); - for (DWARFDIE child_die = target_die.GetFirstChild(); - child_die.IsValid(); child_die = child_die.GetSibling()) { - if (!strcmp(child_die.GetAttributeValueAsString(DW_AT_name, ""), - "__FuncPtr")) { - DWARFDIE function_pointer_type = - child_die.GetReferencedDIE(DW_AT_type); + if (record_decl) { + GetClangASTImporter().InsertRecordDecl( + record_decl, ClangASTImporter::LayoutInfo()); + } + } + } else if (clang_type_was_created) { + // Start the definition if the class is not objective C since the + // underlying decls respond to isCompleteDefinition(). Objective + // C decls don't respond to isCompleteDefinition() so we can't + // start the declaration definition right away. For C++ + // class/union/structs we want to start the definition in case the + // class is needed as the declaration context for a contained class + // or type without the need to complete that type.. - if (function_pointer_type) { - DWARFDIE function_type = - function_pointer_type.GetReferencedDIE(DW_AT_type); + if (attrs.class_language != eLanguageTypeObjC && + attrs.class_language != eLanguageTypeObjC_plus_plus) + ClangASTContext::StartTagDeclarationDefinition(clang_type); - bool function_type_is_new_pointer; - TypeSP lldb_function_type_sp = ParseTypeFromDWARF( - sc, function_type, log, &function_type_is_new_pointer); + // Leave this as a forward declaration until we need to know the + // details of the type. lldb_private::Type will automatically call + // the SymbolFile virtual function + // "SymbolFileDWARF::CompleteType(Type *)" When the definition + // needs to be defined. + assert(!dwarf->GetForwardDeclClangTypeToDie().count( + ClangUtil::RemoveFastQualifiers(clang_type) + .GetOpaqueQualType()) && + "Type already in the forward declaration map!"); + // Can't assume m_ast.GetSymbolFile() is actually a + // SymbolFileDWARF, it can be a SymbolFileDWARFDebugMap for Apple + // binaries. + dwarf->GetForwardDeclDieToClangType()[die.GetDIE()] = + clang_type.GetOpaqueQualType(); + dwarf->GetForwardDeclClangTypeToDie() + [ClangUtil::RemoveFastQualifiers(clang_type).GetOpaqueQualType()] = + die.GetID(); + m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true); + } + } - if (lldb_function_type_sp) { - clang_type = m_ast.CreateBlockPointerType( - lldb_function_type_sp->GetForwardCompilerType()); - encoding_data_type = Type::eEncodingIsUID; - encoding_uid.Clear(); - resolve_state = Type::eResolveStateFull; - } - } + // If we made a clang type, set the trivial abi if applicable: We only + // do this for pass by value - which implies the Trivial ABI. There + // isn't a way to assert that something that would normally be pass by + // value is pass by reference, so we ignore that attribute if set. + if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_value) { + clang::CXXRecordDecl *record_decl = + m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType()); + if (record_decl) { + record_decl->setHasTrivialSpecialMemberForCall(); + } + } + if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_reference) { + clang::CXXRecordDecl *record_decl = + m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType()); + if (record_decl) + record_decl->setArgPassingRestrictions( + clang::RecordDecl::APK_CannotPassInRegs); + } + + } break; + + case DW_TAG_enumeration_type: { + if (attrs.is_forward_declaration) { + type_sp = ParseTypeFromDWO(die, log); + if (type_sp) + return type_sp; + + DWARFDeclContext die_decl_ctx; + die.GetDWARFDeclContext(die_decl_ctx); + + type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx); + + if (!type_sp) { + SymbolFileDWARFDebugMap *debug_map_symfile = + dwarf->GetDebugMapSymfile(); + if (debug_map_symfile) { + // We weren't able to find a full declaration in this DWARF, + // see if we have a declaration anywhere else... + type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext( + die_decl_ctx); + } + } + + if (type_sp) { + if (log) { + dwarf->GetObjectFile()->GetModule()->LogMessage( + log, + "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a " + "forward declaration, complete type is 0x%8.8" PRIx64, + static_cast<void *>(this), die.GetOffset(), + DW_TAG_value_to_name(tag), attrs.name.GetCString(), + type_sp->GetID()); + } + + // We found a real definition for this type elsewhere so lets use + // it and cache the fact that we found a complete type for this + // die + dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); + clang::DeclContext *defn_decl_ctx = + GetCachedClangDeclContextForDIE(dwarf->GetDIE(type_sp->GetID())); + if (defn_decl_ctx) + LinkDeclContextToDIE(defn_decl_ctx, die); + return type_sp; + } + } + DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), + DW_TAG_value_to_name(tag), type_name_cstr); + + CompilerType enumerator_clang_type; + clang_type.SetCompilerType( + &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE())); + if (!clang_type) { + if (attrs.type.IsValid()) { + Type *enumerator_type = + dwarf->ResolveTypeUID(attrs.type.Reference(), true); + if (enumerator_type) + enumerator_clang_type = enumerator_type->GetFullCompilerType(); + } + + if (!enumerator_clang_type) { + if (attrs.byte_size) { + enumerator_clang_type = + m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize( + NULL, DW_ATE_signed, *attrs.byte_size * 8); + } else { + enumerator_clang_type = m_ast.GetBasicType(eBasicTypeInt); + } + } + + clang_type = m_ast.CreateEnumerationType( + attrs.name.GetCString(), + GetClangDeclContextContainingDIE(die, nullptr), attrs.decl, + enumerator_clang_type, attrs.is_scoped_enum); + } else { + enumerator_clang_type = + m_ast.GetEnumerationIntegerType(clang_type.GetOpaqueQualType()); + } + + LinkDeclContextToDIE(ClangASTContext::GetDeclContextForType(clang_type), + die); + + type_sp = std::make_shared<Type>( + die.GetID(), dwarf, attrs.name, attrs.byte_size, nullptr, + dwarf->GetUID(attrs.type.Reference()), Type::eEncodingIsUID, + &attrs.decl, clang_type, Type::eResolveStateForward); + + if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) { + if (die.HasChildren()) { + bool is_signed = false; + enumerator_clang_type.IsIntegerType(is_signed); + ParseChildEnumerators(clang_type, is_signed, + type_sp->GetByteSize().getValueOr(0), die); + } + ClangASTContext::CompleteTagDeclarationDefinition(clang_type); + } else { + dwarf->GetObjectFile()->GetModule()->ReportError( + "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its " + "definition.\nPlease file a bug and attach the file at the " + "start of this error message", + die.GetOffset(), attrs.name.GetCString()); + } + } break; + + case DW_TAG_inlined_subroutine: + case DW_TAG_subprogram: + case DW_TAG_subroutine_type: { + bool is_variadic = false; + bool is_static = false; + bool has_template_params = false; + + unsigned type_quals = 0; + + std::string object_pointer_name; + if (attrs.object_pointer) { + const char *object_pointer_name_cstr = attrs.object_pointer.GetName(); + if (object_pointer_name_cstr) + object_pointer_name = object_pointer_name_cstr; + } + + DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), + DW_TAG_value_to_name(tag), type_name_cstr); + + CompilerType return_clang_type; + Type *func_type = NULL; + + if (attrs.type.IsValid()) + func_type = dwarf->ResolveTypeUID(attrs.type.Reference(), true); + + if (func_type) + return_clang_type = func_type->GetForwardCompilerType(); + else + return_clang_type = m_ast.GetBasicType(eBasicTypeVoid); + + std::vector<CompilerType> function_param_types; + std::vector<clang::ParmVarDecl *> function_param_decls; + + // Parse the function children for the parameters + + DWARFDIE decl_ctx_die; + clang::DeclContext *containing_decl_ctx = + GetClangDeclContextContainingDIE(die, &decl_ctx_die); + const clang::Decl::Kind containing_decl_kind = + containing_decl_ctx->getDeclKind(); + + bool is_cxx_method = DeclKindIsCXXClass(containing_decl_kind); + // Start off static. This will be set to false in + // ParseChildParameters(...) if we find a "this" parameters as the + // first parameter + if (is_cxx_method) { + is_static = true; + } + + if (die.HasChildren()) { + bool skip_artificial = true; + ParseChildParameters(containing_decl_ctx, die, skip_artificial, is_static, + is_variadic, has_template_params, + function_param_types, function_param_decls, + type_quals); + } + + bool ignore_containing_context = false; + // Check for templatized class member functions. If we had any + // DW_TAG_template_type_parameter or DW_TAG_template_value_parameter + // the DW_TAG_subprogram DIE, then we can't let this become a method in + // a class. Why? Because templatized functions are only emitted if one + // of the templatized methods is used in the current compile unit and + // we will end up with classes that may or may not include these member + // functions and this means one class won't match another class + // definition and it affects our ability to use a class in the clang + // expression parser. So for the greater good, we currently must not + // allow any template member functions in a class definition. + if (is_cxx_method && has_template_params) { + ignore_containing_context = true; + is_cxx_method = false; + } + + // clang_type will get the function prototype clang type after this + // call + clang_type = m_ast.CreateFunctionType( + return_clang_type, function_param_types.data(), + function_param_types.size(), is_variadic, type_quals); + + if (attrs.name) { + bool type_handled = false; + if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) { + ObjCLanguage::MethodName objc_method(attrs.name.GetStringRef(), true); + if (objc_method.IsValid(true)) { + CompilerType class_opaque_type; + ConstString class_name(objc_method.GetClassName()); + if (class_name) { + TypeSP complete_objc_class_type_sp( + dwarf->FindCompleteObjCDefinitionTypeForDIE(DWARFDIE(), + class_name, false)); + + if (complete_objc_class_type_sp) { + CompilerType type_clang_forward_type = + complete_objc_class_type_sp->GetForwardCompilerType(); + if (ClangASTContext::IsObjCObjectOrInterfaceType( + type_clang_forward_type)) + class_opaque_type = type_clang_forward_type; + } + } + + if (class_opaque_type) { + // If accessibility isn't set to anything valid, assume public + // for now... + if (attrs.accessibility == eAccessNone) + attrs.accessibility = eAccessPublic; + + clang::ObjCMethodDecl *objc_method_decl = + m_ast.AddMethodToObjCObjectType( + class_opaque_type, attrs.name.GetCString(), clang_type, + attrs.accessibility, attrs.is_artificial, is_variadic); + type_handled = objc_method_decl != NULL; + if (type_handled) { + LinkDeclContextToDIE( + ClangASTContext::GetAsDeclContext(objc_method_decl), die); + m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID()); + } else { + dwarf->GetObjectFile()->GetModule()->ReportError( + "{0x%8.8x}: invalid Objective-C method 0x%4.4x (%s), " + "please file a bug and attach the file at the start of " + "this error message", + die.GetOffset(), tag, DW_TAG_value_to_name(tag)); + } + } + } else if (is_cxx_method) { + // Look at the parent of this DIE and see if is is a class or + // struct and see if this is actually a C++ method + Type *class_type = dwarf->ResolveType(decl_ctx_die); + if (class_type) { + bool alternate_defn = false; + if (class_type->GetID() != decl_ctx_die.GetID() || + decl_ctx_die.GetContainingDWOModuleDIE()) { + alternate_defn = true; + + // We uniqued the parent class of this function to another + // class so we now need to associate all dies under + // "decl_ctx_die" to DIEs in the DIE for "class_type"... + DWARFDIE class_type_die = dwarf->GetDIE(class_type->GetID()); + + if (class_type_die) { + std::vector<DWARFDIE> failures; + + CopyUniqueClassMethodTypes(decl_ctx_die, class_type_die, + class_type, failures); + + // FIXME do something with these failures that's smarter + // than + // just dropping them on the ground. Unfortunately classes + // don't like having stuff added to them after their + // definitions are complete... + + type_ptr = dwarf->GetDIEToType()[die.GetDIE()]; + if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) { + type_sp = type_ptr->shared_from_this(); break; } } } - } - bool translation_unit_is_objc = - (sc.comp_unit->GetLanguage() == eLanguageTypeObjC || - sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus); - - if (translation_unit_is_objc) { - if (type_name_cstr != NULL) { - static ConstString g_objc_type_name_id("id"); - static ConstString g_objc_type_name_Class("Class"); - static ConstString g_objc_type_name_selector("SEL"); - - if (type_name_const_str == g_objc_type_name_id) { - if (log) - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' " - "is Objective-C 'id' built-in type.", - die.GetOffset(), die.GetTagAsCString(), die.GetName()); - clang_type = m_ast.GetBasicType(eBasicTypeObjCID); - encoding_data_type = Type::eEncodingIsUID; - encoding_uid.Clear(); - resolve_state = Type::eResolveStateFull; - - } else if (type_name_const_str == g_objc_type_name_Class) { - if (log) - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' " - "is Objective-C 'Class' built-in type.", - die.GetOffset(), die.GetTagAsCString(), die.GetName()); - clang_type = m_ast.GetBasicType(eBasicTypeObjCClass); - encoding_data_type = Type::eEncodingIsUID; - encoding_uid.Clear(); - resolve_state = Type::eResolveStateFull; - } else if (type_name_const_str == g_objc_type_name_selector) { - if (log) - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' " - "is Objective-C 'selector' built-in type.", - die.GetOffset(), die.GetTagAsCString(), die.GetName()); - clang_type = m_ast.GetBasicType(eBasicTypeObjCSel); - encoding_data_type = Type::eEncodingIsUID; - encoding_uid.Clear(); - resolve_state = Type::eResolveStateFull; - } - } else if (encoding_data_type == Type::eEncodingIsPointerUID && - encoding_uid.IsValid()) { - // Clang sometimes erroneously emits id as objc_object*. In that - // case we fix up the type to "id". - - const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid)); - - if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) { - if (const char *struct_name = encoding_die.GetName()) { - if (!strcmp(struct_name, "objc_object")) { - if (log) - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s " - "'%s' is 'objc_object*', which we overrode to " - "'id'.", - die.GetOffset(), die.GetTagAsCString(), - die.GetName()); - clang_type = m_ast.GetBasicType(eBasicTypeObjCID); - encoding_data_type = Type::eEncodingIsUID; - encoding_uid.Clear(); - resolve_state = Type::eResolveStateFull; - } - } - } - } - } - } - - type_sp.reset( - new Type(die.GetID(), dwarf, type_name_const_str, byte_size, NULL, - DIERef(encoding_uid).GetUID(dwarf), encoding_data_type, - &decl, clang_type, resolve_state)); - - dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); - } break; - - case DW_TAG_structure_type: - case DW_TAG_union_type: - case DW_TAG_class_type: { - // Set a bit that lets us know that we are currently parsing this - dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED; - bool byte_size_valid = false; - - LanguageType class_language = eLanguageTypeUnknown; - bool is_complete_objc_class = false; - size_t calling_convention - = llvm::dwarf::CallingConvention::DW_CC_normal; - - const size_t num_attributes = die.GetAttributes(attributes); - if (num_attributes > 0) { - uint32_t i; - for (i = 0; i < num_attributes; ++i) { - attr = attributes.AttributeAtIndex(i); - if (attributes.ExtractFormValueAtIndex(i, form_value)) { - switch (attr) { - case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; - - case DW_AT_name: - type_name_cstr = form_value.AsCString(); - type_name_const_str.SetCString(type_name_cstr); - break; - - case DW_AT_byte_size: - byte_size = form_value.Unsigned(); - byte_size_valid = true; - break; - - case DW_AT_accessibility: - accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); - break; - - case DW_AT_declaration: - is_forward_declaration = form_value.Boolean(); - break; - - case DW_AT_APPLE_runtime_class: - class_language = (LanguageType)form_value.Signed(); - break; - - case DW_AT_APPLE_objc_complete_type: - is_complete_objc_class = form_value.Signed(); - break; - case DW_AT_calling_convention: - calling_convention = form_value.Unsigned(); - break; - - case DW_AT_allocated: - case DW_AT_associated: - case DW_AT_data_location: - case DW_AT_description: - case DW_AT_start_scope: - case DW_AT_visibility: - default: - case DW_AT_sibling: - break; - } - } - } - } - - // UniqueDWARFASTType is large, so don't create a local variables on - // the stack, put it on the heap. This function is often called - // recursively and clang isn't good and sharing the stack space for - // variables in different blocks. - std::unique_ptr<UniqueDWARFASTType> unique_ast_entry_ap( - new UniqueDWARFASTType()); - - ConstString unique_typename(type_name_const_str); - Declaration unique_decl(decl); - - if (type_name_const_str) { - LanguageType die_language = die.GetLanguage(); - if (Language::LanguageIsCPlusPlus(die_language)) { - // For C++, we rely solely upon the one definition rule that says - // only one thing can exist at a given decl context. We ignore the - // file and line that things are declared on. - std::string qualified_name; - if (die.GetQualifiedName(qualified_name)) - unique_typename = ConstString(qualified_name); - unique_decl.Clear(); - } - - if (dwarf->GetUniqueDWARFASTTypeMap().Find( - unique_typename, die, unique_decl, - byte_size_valid ? byte_size : -1, *unique_ast_entry_ap)) { - type_sp = unique_ast_entry_ap->m_type_sp; - if (type_sp) { - dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); - return type_sp; - } - } - } - - DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), - DW_TAG_value_to_name(tag), type_name_cstr); - - int tag_decl_kind = -1; - AccessType default_accessibility = eAccessNone; - if (tag == DW_TAG_structure_type) { - tag_decl_kind = clang::TTK_Struct; - default_accessibility = eAccessPublic; - } else if (tag == DW_TAG_union_type) { - tag_decl_kind = clang::TTK_Union; - default_accessibility = eAccessPublic; - } else if (tag == DW_TAG_class_type) { - tag_decl_kind = clang::TTK_Class; - default_accessibility = eAccessPrivate; - } - - if (byte_size_valid && byte_size == 0 && type_name_cstr && - !die.HasChildren() && - sc.comp_unit->GetLanguage() == eLanguageTypeObjC) { - // Work around an issue with clang at the moment where forward - // declarations for objective C classes are emitted as: - // DW_TAG_structure_type [2] - // DW_AT_name( "ForwardObjcClass" ) - // DW_AT_byte_size( 0x00 ) - // DW_AT_decl_file( "..." ) - // DW_AT_decl_line( 1 ) - // - // Note that there is no DW_AT_declaration and there are no children, - // and the byte size is zero. - is_forward_declaration = true; - } - - if (class_language == eLanguageTypeObjC || - class_language == eLanguageTypeObjC_plus_plus) { - if (!is_complete_objc_class && - die.Supports_DW_AT_APPLE_objc_complete_type()) { - // We have a valid eSymbolTypeObjCClass class symbol whose name - // matches the current objective C class that we are trying to find - // and this DIE isn't the complete definition (we checked - // is_complete_objc_class above and know it is false), so the real - // definition is in here somewhere - type_sp = dwarf->FindCompleteObjCDefinitionTypeForDIE( - die, type_name_const_str, true); - - if (!type_sp) { - SymbolFileDWARFDebugMap *debug_map_symfile = - dwarf->GetDebugMapSymfile(); - if (debug_map_symfile) { - // We weren't able to find a full declaration in this DWARF, - // see if we have a declaration anywhere else... - type_sp = - debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE( - die, type_name_const_str, true); - } - } - - if (type_sp) { - if (log) { - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an " - "incomplete objc type, complete type is 0x%8.8" PRIx64, - static_cast<void *>(this), die.GetOffset(), - DW_TAG_value_to_name(tag), type_name_cstr, - type_sp->GetID()); - } - - // We found a real definition for this type elsewhere so lets use - // it and cache the fact that we found a complete type for this - // die - dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); - return type_sp; - } - } - } - - if (is_forward_declaration) { - // We have a forward declaration to a type and we need to try and - // find a full declaration. We look in the current type index just in - // case we have a forward declaration followed by an actual - // declarations in the DWARF. If this fails, we need to look - // elsewhere... - if (log) { - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a " - "forward declaration, trying to find complete type", - static_cast<void *>(this), die.GetOffset(), - DW_TAG_value_to_name(tag), type_name_cstr); - } - - // See if the type comes from a DWO module and if so, track down that - // type. - type_sp = ParseTypeFromDWO(die, log); - if (type_sp) - return type_sp; - - DWARFDeclContext die_decl_ctx; - die.GetDWARFDeclContext(die_decl_ctx); - - // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, - // type_name_const_str); - type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx); - - if (!type_sp) { - SymbolFileDWARFDebugMap *debug_map_symfile = - dwarf->GetDebugMapSymfile(); - if (debug_map_symfile) { - // We weren't able to find a full declaration in this DWARF, see - // if we have a declaration anywhere else... - type_sp = - debug_map_symfile->FindDefinitionTypeForDWARFDeclContext( - die_decl_ctx); - } - } - - if (type_sp) { - if (log) { - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a " - "forward declaration, complete type is 0x%8.8" PRIx64, - static_cast<void *>(this), die.GetOffset(), - DW_TAG_value_to_name(tag), type_name_cstr, type_sp->GetID()); - } - - // We found a real definition for this type elsewhere so lets use - // it and cache the fact that we found a complete type for this die - dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); - clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE( - dwarf->DebugInfo()->GetDIE(DIERef(type_sp->GetID(), dwarf))); - if (defn_decl_ctx) - LinkDeclContextToDIE(defn_decl_ctx, die); - return type_sp; - } - } - assert(tag_decl_kind != -1); - bool clang_type_was_created = false; - clang_type.SetCompilerType( - &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE())); - if (!clang_type) { - clang::DeclContext *decl_ctx = - GetClangDeclContextContainingDIE(die, nullptr); - - // If your decl context is a record that was imported from another - // AST context (in the gmodules case), we need to make sure the type - // backing the Decl is complete before adding children to it. This is - // not an issue in the non-gmodules case because the debug info will - // always contain a full definition of parent types in that case. - CompleteExternalTagDeclType(GetClangASTImporter(), decl_ctx, die, - type_name_cstr); - - if (accessibility == eAccessNone && decl_ctx) { - // Check the decl context that contains this class/struct/union. If - // it is a class we must give it an accessibility. - const clang::Decl::Kind containing_decl_kind = - decl_ctx->getDeclKind(); - if (DeclKindIsCXXClass(containing_decl_kind)) - accessibility = default_accessibility; - } - - ClangASTMetadata metadata; - metadata.SetUserID(die.GetID()); - metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die)); - - if (type_name_cstr && strchr(type_name_cstr, '<')) { - ClangASTContext::TemplateParameterInfos template_param_infos; - if (ParseTemplateParameterInfos(die, template_param_infos)) { - clang::ClassTemplateDecl *class_template_decl = - m_ast.ParseClassTemplateDecl(decl_ctx, accessibility, - type_name_cstr, tag_decl_kind, - template_param_infos); - if (!class_template_decl) { - if (log) { - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" " - "clang::ClassTemplateDecl failed to return a decl.", - static_cast<void *>(this), die.GetOffset(), - DW_TAG_value_to_name(tag), type_name_cstr); - } - return TypeSP(); - } - - clang::ClassTemplateSpecializationDecl - *class_specialization_decl = - m_ast.CreateClassTemplateSpecializationDecl( - decl_ctx, class_template_decl, tag_decl_kind, - template_param_infos); - clang_type = m_ast.CreateClassTemplateSpecializationType( - class_specialization_decl); - clang_type_was_created = true; - - m_ast.SetMetadata(class_template_decl, metadata); - m_ast.SetMetadata(class_specialization_decl, metadata); - } - } - - if (!clang_type_was_created) { - clang_type_was_created = true; - clang_type = m_ast.CreateRecordType(decl_ctx, accessibility, - type_name_cstr, tag_decl_kind, - class_language, &metadata); - } - } - - // Store a forward declaration to this class type in case any - // parameters in any class methods need it for the clang types for - // function prototypes. - LinkDeclContextToDIE(m_ast.GetDeclContextForType(clang_type), die); - type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str, - byte_size, NULL, LLDB_INVALID_UID, - Type::eEncodingIsUID, &decl, clang_type, - Type::eResolveStateForward)); - - type_sp->SetIsCompleteObjCClass(is_complete_objc_class); - - // Add our type to the unique type map so we don't end up creating many - // copies of the same type over and over in the ASTContext for our - // module - unique_ast_entry_ap->m_type_sp = type_sp; - unique_ast_entry_ap->m_die = die; - unique_ast_entry_ap->m_declaration = unique_decl; - unique_ast_entry_ap->m_byte_size = byte_size; - dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename, - *unique_ast_entry_ap); - - if (is_forward_declaration && die.HasChildren()) { - // Check to see if the DIE actually has a definition, some version of - // GCC will - // emit DIEs with DW_AT_declaration set to true, but yet still have - // subprogram, members, or inheritance, so we can't trust it - DWARFDIE child_die = die.GetFirstChild(); - while (child_die) { - switch (child_die.Tag()) { - case DW_TAG_inheritance: - case DW_TAG_subprogram: - case DW_TAG_member: - case DW_TAG_APPLE_property: - case DW_TAG_class_type: - case DW_TAG_structure_type: - case DW_TAG_enumeration_type: - case DW_TAG_typedef: - case DW_TAG_union_type: - child_die.Clear(); - is_forward_declaration = false; - break; - default: - child_die = child_die.GetSibling(); - break; - } - } - } - - if (!is_forward_declaration) { - // Always start the definition for a class type so that if the class - // has child classes or types that require the class to be created - // for use as their decl contexts the class will be ready to accept - // these child definitions. - if (!die.HasChildren()) { - // No children for this struct/union/class, lets finish it - if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) { - ClangASTContext::CompleteTagDeclarationDefinition(clang_type); - } else { - dwarf->GetObjectFile()->GetModule()->ReportError( - "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its " - "definition.\nPlease file a bug and attach the file at the " - "start of this error message", - die.GetOffset(), type_name_cstr); - } - - if (tag == DW_TAG_structure_type) // this only applies in C - { - clang::RecordDecl *record_decl = - ClangASTContext::GetAsRecordDecl(clang_type); - - if (record_decl) { - GetClangASTImporter().InsertRecordDecl( - record_decl, ClangASTImporter::LayoutInfo()); - } - } - } else if (clang_type_was_created) { - // Start the definition if the class is not objective C since the - // underlying decls respond to isCompleteDefinition(). Objective - // C decls don't respond to isCompleteDefinition() so we can't - // start the declaration definition right away. For C++ - // class/union/structs we want to start the definition in case the - // class is needed as the declaration context for a contained class - // or type without the need to complete that type.. - - if (class_language != eLanguageTypeObjC && - class_language != eLanguageTypeObjC_plus_plus) - ClangASTContext::StartTagDeclarationDefinition(clang_type); - - // Leave this as a forward declaration until we need to know the - // details of the type. lldb_private::Type will automatically call - // the SymbolFile virtual function - // "SymbolFileDWARF::CompleteType(Type *)" When the definition - // needs to be defined. - assert(!dwarf->GetForwardDeclClangTypeToDie().count( - ClangUtil::RemoveFastQualifiers(clang_type) - .GetOpaqueQualType()) && - "Type already in the forward declaration map!"); - // Can't assume m_ast.GetSymbolFile() is actually a - // SymbolFileDWARF, it can be a SymbolFileDWARFDebugMap for Apple - // binaries. - dwarf->GetForwardDeclDieToClangType()[die.GetDIE()] = - clang_type.GetOpaqueQualType(); - dwarf->GetForwardDeclClangTypeToDie() - [ClangUtil::RemoveFastQualifiers(clang_type) - .GetOpaqueQualType()] = die.GetDIERef(); - m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true); - } - } - - // If we made a clang type, set the trivial abi if applicable: We only - // do this for pass by value - which implies the Trivial ABI. There - // isn't a way to assert that something that would normally be pass by - // value is pass by reference, so we ignore that attribute if set. - if (calling_convention == llvm::dwarf::DW_CC_pass_by_value) { - clang::CXXRecordDecl *record_decl = - m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType()); - if (record_decl) { - record_decl->setHasTrivialSpecialMemberForCall(); - } - } - - } break; - - case DW_TAG_enumeration_type: { - // Set a bit that lets us know that we are currently parsing this - dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED; - - bool is_scoped = false; - DWARFFormValue encoding_form; - - const size_t num_attributes = die.GetAttributes(attributes); - if (num_attributes > 0) { - uint32_t i; - - for (i = 0; i < num_attributes; ++i) { - attr = attributes.AttributeAtIndex(i); - if (attributes.ExtractFormValueAtIndex(i, form_value)) { - switch (attr) { - case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; - case DW_AT_name: - type_name_cstr = form_value.AsCString(); - type_name_const_str.SetCString(type_name_cstr); - break; - case DW_AT_type: - encoding_form = form_value; - break; - case DW_AT_byte_size: - byte_size = form_value.Unsigned(); - break; - case DW_AT_accessibility: - break; // accessibility = - // DW_ACCESS_to_AccessType(form_value.Unsigned()); break; - case DW_AT_declaration: - is_forward_declaration = form_value.Boolean(); - break; - case DW_AT_enum_class: - is_scoped = form_value.Boolean(); - break; - case DW_AT_allocated: - case DW_AT_associated: - case DW_AT_bit_stride: - case DW_AT_byte_stride: - case DW_AT_data_location: - case DW_AT_description: - case DW_AT_start_scope: - case DW_AT_visibility: - case DW_AT_specification: - case DW_AT_abstract_origin: - case DW_AT_sibling: - break; - } - } - } - - if (is_forward_declaration) { - type_sp = ParseTypeFromDWO(die, log); - if (type_sp) - return type_sp; - - DWARFDeclContext die_decl_ctx; - die.GetDWARFDeclContext(die_decl_ctx); - - type_sp = - dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx); - - if (!type_sp) { - SymbolFileDWARFDebugMap *debug_map_symfile = - dwarf->GetDebugMapSymfile(); - if (debug_map_symfile) { - // We weren't able to find a full declaration in this DWARF, - // see if we have a declaration anywhere else... - type_sp = - debug_map_symfile->FindDefinitionTypeForDWARFDeclContext( - die_decl_ctx); - } - } - - if (type_sp) { - if (log) { - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a " - "forward declaration, complete type is 0x%8.8" PRIx64, - static_cast<void *>(this), die.GetOffset(), - DW_TAG_value_to_name(tag), type_name_cstr, - type_sp->GetID()); - } - - // We found a real definition for this type elsewhere so lets use - // it and cache the fact that we found a complete type for this - // die - dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); - clang::DeclContext *defn_decl_ctx = - GetCachedClangDeclContextForDIE(dwarf->DebugInfo()->GetDIE( - DIERef(type_sp->GetID(), dwarf))); - if (defn_decl_ctx) - LinkDeclContextToDIE(defn_decl_ctx, die); - return type_sp; - } - } - DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), - DW_TAG_value_to_name(tag), type_name_cstr); - - CompilerType enumerator_clang_type; - clang_type.SetCompilerType( - &m_ast, - dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE())); - if (!clang_type) { - if (encoding_form.IsValid()) { - Type *enumerator_type = - dwarf->ResolveTypeUID(DIERef(encoding_form)); - if (enumerator_type) - enumerator_clang_type = enumerator_type->GetFullCompilerType(); - } - - if (!enumerator_clang_type) { - if (byte_size > 0) { - enumerator_clang_type = - m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize( - NULL, DW_ATE_signed, byte_size * 8); + if (attrs.specification.IsValid()) { + // We have a specification which we are going to base our + // function prototype off of, so we need this type to be + // completed so that the m_die_to_decl_ctx for the method in + // the specification has a valid clang decl context. + class_type->GetForwardCompilerType(); + // If we have a specification, then the function type should + // have been made with the specification and not with this + // die. + DWARFDIE spec_die = attrs.specification.Reference(); + clang::DeclContext *spec_clang_decl_ctx = + GetClangDeclContextForDIE(spec_die); + if (spec_clang_decl_ctx) { + LinkDeclContextToDIE(spec_clang_decl_ctx, die); } else { - enumerator_clang_type = m_ast.GetBasicType(eBasicTypeInt); + dwarf->GetObjectFile()->GetModule()->ReportWarning( + "0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8x" + ") has no decl\n", + die.GetID(), spec_die.GetOffset()); } - } + type_handled = true; + } else if (attrs.abstract_origin.IsValid()) { + // We have a specification which we are going to base our + // function prototype off of, so we need this type to be + // completed so that the m_die_to_decl_ctx for the method in + // the abstract origin has a valid clang decl context. + class_type->GetForwardCompilerType(); - clang_type = m_ast.CreateEnumerationType( - type_name_cstr, GetClangDeclContextContainingDIE(die, nullptr), - decl, enumerator_clang_type, is_scoped); - } else { - enumerator_clang_type = - m_ast.GetEnumerationIntegerType(clang_type.GetOpaqueQualType()); - } - - LinkDeclContextToDIE( - ClangASTContext::GetDeclContextForType(clang_type), die); - - type_sp.reset(new Type( - die.GetID(), dwarf, type_name_const_str, byte_size, NULL, - DIERef(encoding_form).GetUID(dwarf), Type::eEncodingIsUID, &decl, - clang_type, Type::eResolveStateForward)); - - if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) { - if (die.HasChildren()) { - SymbolContext cu_sc(die.GetLLDBCompileUnit()); - bool is_signed = false; - enumerator_clang_type.IsIntegerType(is_signed); - ParseChildEnumerators(cu_sc, clang_type, is_signed, - type_sp->GetByteSize(), die); - } - ClangASTContext::CompleteTagDeclarationDefinition(clang_type); - } else { - dwarf->GetObjectFile()->GetModule()->ReportError( - "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its " - "definition.\nPlease file a bug and attach the file at the " - "start of this error message", - die.GetOffset(), type_name_cstr); - } - } - } break; - - case DW_TAG_inlined_subroutine: - case DW_TAG_subprogram: - case DW_TAG_subroutine_type: { - // Set a bit that lets us know that we are currently parsing this - dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED; - - DWARFFormValue type_die_form; - bool is_variadic = false; - bool is_inline = false; - bool is_static = false; - bool is_virtual = false; - bool is_explicit = false; - bool is_artificial = false; - bool has_template_params = false; - DWARFFormValue specification_die_form; - DWARFFormValue abstract_origin_die_form; - dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET; - - unsigned type_quals = 0; - clang::StorageClass storage = - clang::SC_None; //, Extern, Static, PrivateExtern - - const size_t num_attributes = die.GetAttributes(attributes); - if (num_attributes > 0) { - uint32_t i; - for (i = 0; i < num_attributes; ++i) { - attr = attributes.AttributeAtIndex(i); - if (attributes.ExtractFormValueAtIndex(i, form_value)) { - switch (attr) { - case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; - case DW_AT_name: - type_name_cstr = form_value.AsCString(); - type_name_const_str.SetCString(type_name_cstr); - break; - - case DW_AT_linkage_name: - case DW_AT_MIPS_linkage_name: - mangled_name_cstr = form_value.AsCString(); - break; - case DW_AT_type: - type_die_form = form_value; - break; - case DW_AT_accessibility: - accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); - break; - case DW_AT_declaration: - break; // is_forward_declaration = form_value.Boolean(); break; - case DW_AT_inline: - is_inline = form_value.Boolean(); - break; - case DW_AT_virtuality: - is_virtual = form_value.Boolean(); - break; - case DW_AT_explicit: - is_explicit = form_value.Boolean(); - break; - case DW_AT_artificial: - is_artificial = form_value.Boolean(); - break; - - case DW_AT_external: - if (form_value.Unsigned()) { - if (storage == clang::SC_None) - storage = clang::SC_Extern; - else - storage = clang::SC_PrivateExtern; - } - break; - - case DW_AT_specification: - specification_die_form = form_value; - break; - - case DW_AT_abstract_origin: - abstract_origin_die_form = form_value; - break; - - case DW_AT_object_pointer: - object_pointer_die_offset = form_value.Reference(); - break; - - case DW_AT_allocated: - case DW_AT_associated: - case DW_AT_address_class: - case DW_AT_calling_convention: - case DW_AT_data_location: - case DW_AT_elemental: - case DW_AT_entry_pc: - case DW_AT_frame_base: - case DW_AT_high_pc: - case DW_AT_low_pc: - case DW_AT_prototyped: - case DW_AT_pure: - case DW_AT_ranges: - case DW_AT_recursive: - case DW_AT_return_addr: - case DW_AT_segment: - case DW_AT_start_scope: - case DW_AT_static_link: - case DW_AT_trampoline: - case DW_AT_visibility: - case DW_AT_vtable_elem_location: - case DW_AT_description: - case DW_AT_sibling: - break; + DWARFDIE abs_die = attrs.abstract_origin.Reference(); + clang::DeclContext *abs_clang_decl_ctx = + GetClangDeclContextForDIE(abs_die); + if (abs_clang_decl_ctx) { + LinkDeclContextToDIE(abs_clang_decl_ctx, die); + } else { + dwarf->GetObjectFile()->GetModule()->ReportWarning( + "0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8x" + ") has no decl\n", + die.GetID(), abs_die.GetOffset()); } - } - } - } - - std::string object_pointer_name; - if (object_pointer_die_offset != DW_INVALID_OFFSET) { - DWARFDIE object_pointer_die = die.GetDIE(object_pointer_die_offset); - if (object_pointer_die) { - const char *object_pointer_name_cstr = object_pointer_die.GetName(); - if (object_pointer_name_cstr) - object_pointer_name = object_pointer_name_cstr; - } - } - - DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), - DW_TAG_value_to_name(tag), type_name_cstr); - - CompilerType return_clang_type; - Type *func_type = NULL; - - if (type_die_form.IsValid()) - func_type = dwarf->ResolveTypeUID(DIERef(type_die_form)); - - if (func_type) - return_clang_type = func_type->GetForwardCompilerType(); - else - return_clang_type = m_ast.GetBasicType(eBasicTypeVoid); - - std::vector<CompilerType> function_param_types; - std::vector<clang::ParmVarDecl *> function_param_decls; - - // Parse the function children for the parameters - - DWARFDIE decl_ctx_die; - clang::DeclContext *containing_decl_ctx = - GetClangDeclContextContainingDIE(die, &decl_ctx_die); - const clang::Decl::Kind containing_decl_kind = - containing_decl_ctx->getDeclKind(); - - bool is_cxx_method = DeclKindIsCXXClass(containing_decl_kind); - // Start off static. This will be set to false in - // ParseChildParameters(...) if we find a "this" parameters as the - // first parameter - if (is_cxx_method) { - is_static = true; - } - - if (die.HasChildren()) { - bool skip_artificial = true; - ParseChildParameters(*sc.comp_unit, containing_decl_ctx, die, - skip_artificial, is_static, is_variadic, - has_template_params, function_param_types, - function_param_decls, type_quals); - } - - bool ignore_containing_context = false; - // Check for templatized class member functions. If we had any - // DW_TAG_template_type_parameter or DW_TAG_template_value_parameter - // the DW_TAG_subprogram DIE, then we can't let this become a method in - // a class. Why? Because templatized functions are only emitted if one - // of the templatized methods is used in the current compile unit and - // we will end up with classes that may or may not include these member - // functions and this means one class won't match another class - // definition and it affects our ability to use a class in the clang - // expression parser. So for the greater good, we currently must not - // allow any template member functions in a class definition. - if (is_cxx_method && has_template_params) { - ignore_containing_context = true; - is_cxx_method = false; - } - - // clang_type will get the function prototype clang type after this - // call - clang_type = m_ast.CreateFunctionType( - return_clang_type, function_param_types.data(), - function_param_types.size(), is_variadic, type_quals); - - if (type_name_cstr) { - bool type_handled = false; - if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) { - ObjCLanguage::MethodName objc_method(type_name_cstr, true); - if (objc_method.IsValid(true)) { - CompilerType class_opaque_type; - ConstString class_name(objc_method.GetClassName()); - if (class_name) { - TypeSP complete_objc_class_type_sp( - dwarf->FindCompleteObjCDefinitionTypeForDIE( - DWARFDIE(), class_name, false)); - - if (complete_objc_class_type_sp) { - CompilerType type_clang_forward_type = - complete_objc_class_type_sp->GetForwardCompilerType(); - if (ClangASTContext::IsObjCObjectOrInterfaceType( - type_clang_forward_type)) - class_opaque_type = type_clang_forward_type; - } - } - - if (class_opaque_type) { - // If accessibility isn't set to anything valid, assume public - // for now... - if (accessibility == eAccessNone) - accessibility = eAccessPublic; - - clang::ObjCMethodDecl *objc_method_decl = - m_ast.AddMethodToObjCObjectType( - class_opaque_type, type_name_cstr, clang_type, - accessibility, is_artificial, is_variadic); - type_handled = objc_method_decl != NULL; - if (type_handled) { - LinkDeclContextToDIE( - ClangASTContext::GetAsDeclContext(objc_method_decl), die); - m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID()); - } else { - dwarf->GetObjectFile()->GetModule()->ReportError( - "{0x%8.8x}: invalid Objective-C method 0x%4.4x (%s), " - "please file a bug and attach the file at the start of " - "this error message", - die.GetOffset(), tag, DW_TAG_value_to_name(tag)); - } - } - } else if (is_cxx_method) { - // Look at the parent of this DIE and see if is is a class or - // struct and see if this is actually a C++ method - Type *class_type = dwarf->ResolveType(decl_ctx_die); - if (class_type) { - bool alternate_defn = false; - if (class_type->GetID() != decl_ctx_die.GetID() || - decl_ctx_die.GetContainingDWOModuleDIE()) { - alternate_defn = true; - - // We uniqued the parent class of this function to another - // class so we now need to associate all dies under - // "decl_ctx_die" to DIEs in the DIE for "class_type"... - SymbolFileDWARF *class_symfile = NULL; - DWARFDIE class_type_die; - - SymbolFileDWARFDebugMap *debug_map_symfile = - dwarf->GetDebugMapSymfile(); - if (debug_map_symfile) { - class_symfile = debug_map_symfile->GetSymbolFileByOSOIndex( - SymbolFileDWARFDebugMap::GetOSOIndexFromUserID( - class_type->GetID())); - class_type_die = class_symfile->DebugInfo()->GetDIE( - DIERef(class_type->GetID(), dwarf)); - } else { - class_symfile = dwarf; - class_type_die = dwarf->DebugInfo()->GetDIE( - DIERef(class_type->GetID(), dwarf)); - } - if (class_type_die) { - DWARFDIECollection failures; - - CopyUniqueClassMethodTypes(decl_ctx_die, class_type_die, - class_type, failures); - - // FIXME do something with these failures that's smarter - // than - // just dropping them on the ground. Unfortunately classes - // don't like having stuff added to them after their - // definitions are complete... - - type_ptr = dwarf->GetDIEToType()[die.GetDIE()]; - if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) { - type_sp = type_ptr->shared_from_this(); - break; - } - } - } - - if (specification_die_form.IsValid()) { - // We have a specification which we are going to base our - // function prototype off of, so we need this type to be - // completed so that the m_die_to_decl_ctx for the method in - // the specification has a valid clang decl context. + type_handled = true; + } else { + CompilerType class_opaque_type = class_type->GetForwardCompilerType(); - // If we have a specification, then the function type should - // have been made with the specification and not with this - // die. - DWARFDIE spec_die = dwarf->DebugInfo()->GetDIE( - DIERef(specification_die_form)); - clang::DeclContext *spec_clang_decl_ctx = - GetClangDeclContextForDIE(spec_die); - if (spec_clang_decl_ctx) { - LinkDeclContextToDIE(spec_clang_decl_ctx, die); + if (ClangASTContext::IsCXXClassType(class_opaque_type)) { + if (class_opaque_type.IsBeingDefined() || alternate_defn) { + if (!is_static && !die.HasChildren()) { + // We have a C++ member function with no children (this + // pointer!) and clang will get mad if we try and make + // a function that isn't well formed in the DWARF, so + // we will just skip it... + type_handled = true; } else { - dwarf->GetObjectFile()->GetModule()->ReportWarning( - "0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8" PRIx64 - ") has no decl\n", - die.GetID(), specification_die_form.Reference()); - } - type_handled = true; - } else if (abstract_origin_die_form.IsValid()) { - // We have a specification which we are going to base our - // function prototype off of, so we need this type to be - // completed so that the m_die_to_decl_ctx for the method in - // the abstract origin has a valid clang decl context. - class_type->GetForwardCompilerType(); + bool add_method = true; + if (alternate_defn) { + // If an alternate definition for the class exists, + // then add the method only if an equivalent is not + // already present. + clang::CXXRecordDecl *record_decl = + m_ast.GetAsCXXRecordDecl( + class_opaque_type.GetOpaqueQualType()); + if (record_decl) { + for (auto method_iter = record_decl->method_begin(); + method_iter != record_decl->method_end(); + method_iter++) { + clang::CXXMethodDecl *method_decl = *method_iter; + if (method_decl->getNameInfo().getAsString() == + attrs.name.GetStringRef()) { + if (method_decl->getType() == + ClangUtil::GetQualType(clang_type)) { + add_method = false; + LinkDeclContextToDIE( + ClangASTContext::GetAsDeclContext( + method_decl), + die); + type_handled = true; - DWARFDIE abs_die = dwarf->DebugInfo()->GetDIE( - DIERef(abstract_origin_die_form)); - clang::DeclContext *abs_clang_decl_ctx = - GetClangDeclContextForDIE(abs_die); - if (abs_clang_decl_ctx) { - LinkDeclContextToDIE(abs_clang_decl_ctx, die); - } else { - dwarf->GetObjectFile()->GetModule()->ReportWarning( - "0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8" PRIx64 - ") has no decl\n", - die.GetID(), abstract_origin_die_form.Reference()); - } - type_handled = true; - } else { - CompilerType class_opaque_type = - class_type->GetForwardCompilerType(); - if (ClangASTContext::IsCXXClassType(class_opaque_type)) { - if (class_opaque_type.IsBeingDefined() || alternate_defn) { - if (!is_static && !die.HasChildren()) { - // We have a C++ member function with no children (this - // pointer!) and clang will get mad if we try and make - // a function that isn't well formed in the DWARF, so - // we will just skip it... - type_handled = true; - } else { - bool add_method = true; - if (alternate_defn) { - // If an alternate definition for the class exists, - // then add the method only if an equivalent is not - // already present. - clang::CXXRecordDecl *record_decl = - m_ast.GetAsCXXRecordDecl( - class_opaque_type.GetOpaqueQualType()); - if (record_decl) { - for (auto method_iter = record_decl->method_begin(); - method_iter != record_decl->method_end(); - method_iter++) { - clang::CXXMethodDecl *method_decl = *method_iter; - if (method_decl->getNameInfo().getAsString() == - std::string(type_name_cstr)) { - if (method_decl->getType() == - ClangUtil::GetQualType(clang_type)) { - add_method = false; - LinkDeclContextToDIE( - ClangASTContext::GetAsDeclContext( - method_decl), - die); - type_handled = true; - - break; - } - } + break; } } } - - if (add_method) { - llvm::PrettyStackTraceFormat stack_trace( - "SymbolFileDWARF::ParseType() is adding a method " - "%s to class %s in DIE 0x%8.8" PRIx64 " from %s", - type_name_cstr, - class_type->GetName().GetCString(), die.GetID(), - dwarf->GetObjectFile() - ->GetFileSpec() - .GetPath() - .c_str()); - - const bool is_attr_used = false; - // Neither GCC 4.2 nor clang++ currently set a valid - // accessibility in the DWARF for C++ methods... - // Default to public for now... - if (accessibility == eAccessNone) - accessibility = eAccessPublic; - - clang::CXXMethodDecl *cxx_method_decl = - m_ast.AddMethodToCXXRecordType( - class_opaque_type.GetOpaqueQualType(), - type_name_cstr, mangled_name_cstr, clang_type, - accessibility, is_virtual, is_static, - is_inline, is_explicit, is_attr_used, - is_artificial); - - type_handled = cxx_method_decl != NULL; - - if (type_handled) { - LinkDeclContextToDIE( - ClangASTContext::GetAsDeclContext( - cxx_method_decl), - die); - - ClangASTMetadata metadata; - metadata.SetUserID(die.GetID()); - - if (!object_pointer_name.empty()) { - metadata.SetObjectPtrName( - object_pointer_name.c_str()); - if (log) - log->Printf( - "Setting object pointer name: %s on method " - "object %p.\n", - object_pointer_name.c_str(), - static_cast<void *>(cxx_method_decl)); - } - m_ast.SetMetadata(cxx_method_decl, metadata); - } else { - ignore_containing_context = true; - } - } } - } else { - // We were asked to parse the type for a method in a - // class, yet the class hasn't been asked to complete - // itself through the clang::ExternalASTSource protocol, - // so we need to just have the class complete itself and - // do things the right way, then our - // DIE should then have an entry in the - // dwarf->GetDIEToType() map. First - // we need to modify the dwarf->GetDIEToType() so it - // doesn't think we are trying to parse this DIE - // anymore... - dwarf->GetDIEToType()[die.GetDIE()] = NULL; - - // Now we get the full type to force our class type to - // complete itself using the clang::ExternalASTSource - // protocol which will parse all base classes and all - // methods (including the method for this DIE). - class_type->GetFullCompilerType(); - - // The type for this DIE should have been filled in the - // function call above - type_ptr = dwarf->GetDIEToType()[die.GetDIE()]; - if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) { - type_sp = type_ptr->shared_from_this(); - break; - } - - // FIXME This is fixing some even uglier behavior but we - // really need to - // uniq the methods of each class as well as the class - // itself. <rdar://problem/11240464> - type_handled = true; } - } - } - } - } - } - if (!type_handled) { - clang::FunctionDecl *function_decl = nullptr; + if (add_method) { + llvm::PrettyStackTraceFormat stack_trace( + "SymbolFileDWARF::ParseType() is adding a method " + "%s to class %s in DIE 0x%8.8" PRIx64 " from %s", + attrs.name.GetCString(), + class_type->GetName().GetCString(), die.GetID(), + dwarf->GetObjectFile() + ->GetFileSpec() + .GetPath() + .c_str()); - if (abstract_origin_die_form.IsValid()) { - DWARFDIE abs_die = - dwarf->DebugInfo()->GetDIE(DIERef(abstract_origin_die_form)); + const bool is_attr_used = false; + // Neither GCC 4.2 nor clang++ currently set a valid + // accessibility in the DWARF for C++ methods... + // Default to public for now... + if (attrs.accessibility == eAccessNone) + attrs.accessibility = eAccessPublic; - SymbolContext sc; + clang::CXXMethodDecl *cxx_method_decl = + m_ast.AddMethodToCXXRecordType( + class_opaque_type.GetOpaqueQualType(), + attrs.name.GetCString(), attrs.mangled_name, + clang_type, attrs.accessibility, attrs.is_virtual, + is_static, attrs.is_inline, attrs.is_explicit, + is_attr_used, attrs.is_artificial); - if (dwarf->ResolveType(abs_die)) { - function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>( - GetCachedClangDeclContextForDIE(abs_die)); + type_handled = cxx_method_decl != NULL; - if (function_decl) { - LinkDeclContextToDIE(function_decl, die); - } - } - } + if (type_handled) { + LinkDeclContextToDIE( + ClangASTContext::GetAsDeclContext(cxx_method_decl), + die); - if (!function_decl) { - // We just have a function that isn't part of a class - function_decl = m_ast.CreateFunctionDeclaration( - ignore_containing_context ? m_ast.GetTranslationUnitDecl() - : containing_decl_ctx, - type_name_cstr, clang_type, storage, is_inline); + ClangASTMetadata metadata; + metadata.SetUserID(die.GetID()); - if (has_template_params) { - ClangASTContext::TemplateParameterInfos template_param_infos; - ParseTemplateParameterInfos(die, template_param_infos); - clang::FunctionTemplateDecl *func_template_decl = - m_ast.CreateFunctionTemplateDecl( - containing_decl_ctx, function_decl, type_name_cstr, - template_param_infos); - m_ast.CreateFunctionTemplateSpecializationInfo( - function_decl, func_template_decl, template_param_infos); - } - - lldbassert(function_decl); - - if (function_decl) { - LinkDeclContextToDIE(function_decl, die); - - if (!function_param_decls.empty()) - m_ast.SetFunctionParameters(function_decl, - &function_param_decls.front(), - function_param_decls.size()); - - ClangASTMetadata metadata; - metadata.SetUserID(die.GetID()); - - if (!object_pointer_name.empty()) { - metadata.SetObjectPtrName(object_pointer_name.c_str()); - if (log) - log->Printf("Setting object pointer name: %s on function " - "object %p.", + if (!object_pointer_name.empty()) { + metadata.SetObjectPtrName( + object_pointer_name.c_str()); + if (log) + log->Printf( + "Setting object pointer name: %s on method " + "object %p.\n", object_pointer_name.c_str(), - static_cast<void *>(function_decl)); + static_cast<void *>(cxx_method_decl)); + } + m_ast.SetMetadata(cxx_method_decl, metadata); + } else { + ignore_containing_context = true; + } + } + } + } else { + // We were asked to parse the type for a method in a + // class, yet the class hasn't been asked to complete + // itself through the clang::ExternalASTSource protocol, + // so we need to just have the class complete itself and + // do things the right way, then our + // DIE should then have an entry in the + // dwarf->GetDIEToType() map. First + // we need to modify the dwarf->GetDIEToType() so it + // doesn't think we are trying to parse this DIE + // anymore... + dwarf->GetDIEToType()[die.GetDIE()] = NULL; + + // Now we get the full type to force our class type to + // complete itself using the clang::ExternalASTSource + // protocol which will parse all base classes and all + // methods (including the method for this DIE). + class_type->GetFullCompilerType(); + + // The type for this DIE should have been filled in the + // function call above + type_ptr = dwarf->GetDIEToType()[die.GetDIE()]; + if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) { + type_sp = type_ptr->shared_from_this(); + break; + } + + // FIXME This is fixing some even uglier behavior but we + // really need to + // uniq the methods of each class as well as the class + // itself. <rdar://problem/11240464> + type_handled = true; } - m_ast.SetMetadata(function_decl, metadata); } } } } - type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str, 0, NULL, - LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, - clang_type, Type::eResolveStateFull)); - assert(type_sp.get()); - } break; - - case DW_TAG_array_type: { - // Set a bit that lets us know that we are currently parsing this - dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED; - - DWARFFormValue type_die_form; - int64_t first_index = 0; - uint32_t byte_stride = 0; - uint32_t bit_stride = 0; - bool is_vector = false; - const size_t num_attributes = die.GetAttributes(attributes); - - if (num_attributes > 0) { - uint32_t i; - for (i = 0; i < num_attributes; ++i) { - attr = attributes.AttributeAtIndex(i); - if (attributes.ExtractFormValueAtIndex(i, form_value)) { - switch (attr) { - case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; - case DW_AT_name: - type_name_cstr = form_value.AsCString(); - type_name_const_str.SetCString(type_name_cstr); - break; - - case DW_AT_type: - type_die_form = form_value; - break; - case DW_AT_byte_size: - break; // byte_size = form_value.Unsigned(); break; - case DW_AT_byte_stride: - byte_stride = form_value.Unsigned(); - break; - case DW_AT_bit_stride: - bit_stride = form_value.Unsigned(); - break; - case DW_AT_GNU_vector: - is_vector = form_value.Boolean(); - break; - case DW_AT_accessibility: - break; // accessibility = - // DW_ACCESS_to_AccessType(form_value.Unsigned()); break; - case DW_AT_declaration: - break; // is_forward_declaration = form_value.Boolean(); break; - case DW_AT_allocated: - case DW_AT_associated: - case DW_AT_data_location: - case DW_AT_description: - case DW_AT_ordering: - case DW_AT_start_scope: - case DW_AT_visibility: - case DW_AT_specification: - case DW_AT_abstract_origin: - case DW_AT_sibling: - break; - } - } - } - - DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), - DW_TAG_value_to_name(tag), type_name_cstr); - - DIERef type_die_ref(type_die_form); - Type *element_type = dwarf->ResolveTypeUID(type_die_ref); - - if (element_type) { - auto array_info = ParseChildArrayInfo(die); - if (array_info) { - first_index = array_info->first_index; - byte_stride = array_info->byte_stride; - bit_stride = array_info->bit_stride; - } - if (byte_stride == 0 && bit_stride == 0) - byte_stride = element_type->GetByteSize(); - CompilerType array_element_type = - element_type->GetForwardCompilerType(); - - if (ClangASTContext::IsCXXClassType(array_element_type) && - !array_element_type.GetCompleteType()) { - ModuleSP module_sp = die.GetModule(); - if (module_sp) { - if (die.GetCU()->GetProducer() == eProducerClang) - module_sp->ReportError( - "DWARF DW_TAG_array_type DIE at 0x%8.8x has a " - "class/union/struct element type DIE 0x%8.8x that is a " - "forward declaration, not a complete definition.\nTry " - "compiling the source file with -fstandalone-debug or " - "disable -gmodules", - die.GetOffset(), type_die_ref.die_offset); - else - module_sp->ReportError( - "DWARF DW_TAG_array_type DIE at 0x%8.8x has a " - "class/union/struct element type DIE 0x%8.8x that is a " - "forward declaration, not a complete definition.\nPlease " - "file a bug against the compiler and include the " - "preprocessed output for %s", - die.GetOffset(), type_die_ref.die_offset, - die.GetLLDBCompileUnit() - ? die.GetLLDBCompileUnit()->GetPath().c_str() - : "the source file"); - } - - // We have no choice other than to pretend that the element class - // type is complete. If we don't do this, clang will crash when - // trying to layout the class. Since we provide layout - // assistance, all ivars in this class and other classes will be - // fine, this is the best we can do short of crashing. - if (ClangASTContext::StartTagDeclarationDefinition( - array_element_type)) { - ClangASTContext::CompleteTagDeclarationDefinition( - array_element_type); - } else { - module_sp->ReportError("DWARF DIE at 0x%8.8x was not able to " - "start its definition.\nPlease file a " - "bug and attach the file at the start " - "of this error message", - type_die_ref.die_offset); - } - } - - uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride; - if (array_info && array_info->element_orders.size() > 0) { - uint64_t num_elements = 0; - auto end = array_info->element_orders.rend(); - for (auto pos = array_info->element_orders.rbegin(); pos != end; - ++pos) { - num_elements = *pos; - clang_type = m_ast.CreateArrayType(array_element_type, - num_elements, is_vector); - array_element_type = clang_type; - array_element_bit_stride = - num_elements ? array_element_bit_stride * num_elements - : array_element_bit_stride; - } - } else { - clang_type = - m_ast.CreateArrayType(array_element_type, 0, is_vector); - } - ConstString empty_name; - type_sp.reset(new Type( - die.GetID(), dwarf, empty_name, array_element_bit_stride / 8, - NULL, DIERef(type_die_form).GetUID(dwarf), Type::eEncodingIsUID, - &decl, clang_type, Type::eResolveStateFull)); - type_sp->SetEncodingType(element_type); - m_ast.SetMetadataAsUserID(clang_type.GetOpaqueQualType(), - die.GetID()); - } - } - } break; - - case DW_TAG_ptr_to_member_type: { - DWARFFormValue type_die_form; - DWARFFormValue containing_type_die_form; - - const size_t num_attributes = die.GetAttributes(attributes); - - if (num_attributes > 0) { - uint32_t i; - for (i = 0; i < num_attributes; ++i) { - attr = attributes.AttributeAtIndex(i); - if (attributes.ExtractFormValueAtIndex(i, form_value)) { - switch (attr) { - case DW_AT_type: - type_die_form = form_value; - break; - case DW_AT_containing_type: - containing_type_die_form = form_value; - break; - } - } - } - - Type *pointee_type = dwarf->ResolveTypeUID(DIERef(type_die_form)); - Type *class_type = - dwarf->ResolveTypeUID(DIERef(containing_type_die_form)); - - CompilerType pointee_clang_type = - pointee_type->GetForwardCompilerType(); - CompilerType class_clang_type = class_type->GetLayoutCompilerType(); - - clang_type = ClangASTContext::CreateMemberPointerType( - class_clang_type, pointee_clang_type); - - if (llvm::Optional<uint64_t> clang_type_size = - clang_type.GetByteSize(nullptr)) { - byte_size = *clang_type_size; - type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str, - byte_size, NULL, LLDB_INVALID_UID, - Type::eEncodingIsUID, NULL, clang_type, - Type::eResolveStateForward)); - } - } - - break; - } - default: - dwarf->GetObjectFile()->GetModule()->ReportError( - "{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and " - "attach the file at the start of this error message", - die.GetOffset(), tag, DW_TAG_value_to_name(tag)); - break; } - if (type_sp.get()) { - DWARFDIE sc_parent_die = - SymbolFileDWARF::GetParentSymbolContextDIE(die); - dw_tag_t sc_parent_tag = sc_parent_die.Tag(); + if (!type_handled) { + clang::FunctionDecl *function_decl = nullptr; + clang::FunctionDecl *template_function_decl = nullptr; - SymbolContextScope *symbol_context_scope = NULL; - if (sc_parent_tag == DW_TAG_compile_unit || - sc_parent_tag == DW_TAG_partial_unit) { - symbol_context_scope = sc.comp_unit; - } else if (sc.function != NULL && sc_parent_die) { - symbol_context_scope = - sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID()); - if (symbol_context_scope == NULL) - symbol_context_scope = sc.function; + if (attrs.abstract_origin.IsValid()) { + DWARFDIE abs_die = attrs.abstract_origin.Reference(); + + if (dwarf->ResolveType(abs_die)) { + function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>( + GetCachedClangDeclContextForDIE(abs_die)); + + if (function_decl) { + LinkDeclContextToDIE(function_decl, die); + } + } } - if (symbol_context_scope != NULL) { - type_sp->SetSymbolContextScope(symbol_context_scope); + if (!function_decl) { + // We just have a function that isn't part of a class + function_decl = m_ast.CreateFunctionDeclaration( + ignore_containing_context ? m_ast.GetTranslationUnitDecl() + : containing_decl_ctx, + attrs.name.GetCString(), clang_type, attrs.storage, + attrs.is_inline); + + if (has_template_params) { + ClangASTContext::TemplateParameterInfos template_param_infos; + ParseTemplateParameterInfos(die, template_param_infos); + template_function_decl = m_ast.CreateFunctionDeclaration( + ignore_containing_context ? m_ast.GetTranslationUnitDecl() + : containing_decl_ctx, + attrs.name.GetCString(), clang_type, attrs.storage, + attrs.is_inline); + clang::FunctionTemplateDecl *func_template_decl = + m_ast.CreateFunctionTemplateDecl( + containing_decl_ctx, template_function_decl, + attrs.name.GetCString(), template_param_infos); + m_ast.CreateFunctionTemplateSpecializationInfo( + function_decl, func_template_decl, template_param_infos); + } + + lldbassert(function_decl); + + if (function_decl) { + LinkDeclContextToDIE(function_decl, die); + + if (!function_param_decls.empty()) { + m_ast.SetFunctionParameters(function_decl, + &function_param_decls.front(), + function_param_decls.size()); + if (template_function_decl) + m_ast.SetFunctionParameters(template_function_decl, + &function_param_decls.front(), + function_param_decls.size()); + } + + ClangASTMetadata metadata; + metadata.SetUserID(die.GetID()); + + if (!object_pointer_name.empty()) { + metadata.SetObjectPtrName(object_pointer_name.c_str()); + if (log) + log->Printf("Setting object pointer name: %s on function " + "object %p.", + object_pointer_name.c_str(), + static_cast<void *>(function_decl)); + } + m_ast.SetMetadata(function_decl, metadata); + } } - - // We are ready to put this type into the uniqued list up at the module - // level - type_list->Insert(type_sp); - - dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); } - } else if (type_ptr != DIE_IS_BEING_PARSED) { - type_sp = type_ptr->shared_from_this(); } + type_sp = std::make_shared<Type>( + die.GetID(), dwarf, attrs.name, llvm::None, nullptr, LLDB_INVALID_UID, + Type::eEncodingIsUID, &attrs.decl, clang_type, Type::eResolveStateFull); + assert(type_sp.get()); + } break; + + case DW_TAG_array_type: { + DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), + DW_TAG_value_to_name(tag), type_name_cstr); + + DWARFDIE type_die = attrs.type.Reference(); + Type *element_type = dwarf->ResolveTypeUID(type_die, true); + + if (element_type) { + auto array_info = ParseChildArrayInfo(die); + if (array_info) { + attrs.byte_stride = array_info->byte_stride; + attrs.bit_stride = array_info->bit_stride; + } + if (attrs.byte_stride == 0 && attrs.bit_stride == 0) + attrs.byte_stride = element_type->GetByteSize().getValueOr(0); + CompilerType array_element_type = element_type->GetForwardCompilerType(); + + if (ClangASTContext::IsCXXClassType(array_element_type) && + !array_element_type.GetCompleteType()) { + ModuleSP module_sp = die.GetModule(); + if (module_sp) { + if (die.GetCU()->GetProducer() == eProducerClang) + module_sp->ReportError( + "DWARF DW_TAG_array_type DIE at 0x%8.8x has a " + "class/union/struct element type DIE 0x%8.8x that is a " + "forward declaration, not a complete definition.\nTry " + "compiling the source file with -fstandalone-debug or " + "disable -gmodules", + die.GetOffset(), type_die.GetOffset()); + else + module_sp->ReportError( + "DWARF DW_TAG_array_type DIE at 0x%8.8x has a " + "class/union/struct element type DIE 0x%8.8x that is a " + "forward declaration, not a complete definition.\nPlease " + "file a bug against the compiler and include the " + "preprocessed output for %s", + die.GetOffset(), type_die.GetOffset(), + GetUnitName(die).c_str()); + } + + // We have no choice other than to pretend that the element class + // type is complete. If we don't do this, clang will crash when + // trying to layout the class. Since we provide layout + // assistance, all ivars in this class and other classes will be + // fine, this is the best we can do short of crashing. + if (ClangASTContext::StartTagDeclarationDefinition( + array_element_type)) { + ClangASTContext::CompleteTagDeclarationDefinition(array_element_type); + } else { + module_sp->ReportError("DWARF DIE at 0x%8.8x was not able to " + "start its definition.\nPlease file a " + "bug and attach the file at the start " + "of this error message", + type_die.GetOffset()); + } + } + + uint64_t array_element_bit_stride = + attrs.byte_stride * 8 + attrs.bit_stride; + if (array_info && array_info->element_orders.size() > 0) { + uint64_t num_elements = 0; + auto end = array_info->element_orders.rend(); + for (auto pos = array_info->element_orders.rbegin(); pos != end; + ++pos) { + num_elements = *pos; + clang_type = m_ast.CreateArrayType(array_element_type, num_elements, + attrs.is_vector); + array_element_type = clang_type; + array_element_bit_stride = + num_elements ? array_element_bit_stride * num_elements + : array_element_bit_stride; + } + } else { + clang_type = m_ast.CreateArrayType(array_element_type, 0, attrs.is_vector); + } + ConstString empty_name; + type_sp = std::make_shared<Type>( + die.GetID(), dwarf, empty_name, array_element_bit_stride / 8, nullptr, + dwarf->GetUID(type_die), Type::eEncodingIsUID, &attrs.decl, + clang_type, Type::eResolveStateFull); + type_sp->SetEncodingType(element_type); + m_ast.SetMetadataAsUserID(clang_type.GetOpaqueQualType(), die.GetID()); + } + } break; + + case DW_TAG_ptr_to_member_type: { + Type *pointee_type = dwarf->ResolveTypeUID(attrs.type.Reference(), true); + Type *class_type = + dwarf->ResolveTypeUID(attrs.containing_type.Reference(), true); + + CompilerType pointee_clang_type = pointee_type->GetForwardCompilerType(); + CompilerType class_clang_type = class_type->GetLayoutCompilerType(); + + clang_type = ClangASTContext::CreateMemberPointerType(class_clang_type, + pointee_clang_type); + + if (llvm::Optional<uint64_t> clang_type_size = + clang_type.GetByteSize(nullptr)) { + type_sp = std::make_shared<Type>( + die.GetID(), dwarf, attrs.name, *clang_type_size, nullptr, + LLDB_INVALID_UID, Type::eEncodingIsUID, nullptr, clang_type, + Type::eResolveStateForward); + } + + break; + } + default: + dwarf->GetObjectFile()->GetModule()->ReportError( + "{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and " + "attach the file at the start of this error message", + die.GetOffset(), tag, DW_TAG_value_to_name(tag)); + break; + } + + if (type_sp.get()) { + DWARFDIE sc_parent_die = SymbolFileDWARF::GetParentSymbolContextDIE(die); + dw_tag_t sc_parent_tag = sc_parent_die.Tag(); + + SymbolContextScope *symbol_context_scope = NULL; + if (sc_parent_tag == DW_TAG_compile_unit || + sc_parent_tag == DW_TAG_partial_unit) { + symbol_context_scope = sc.comp_unit; + } else if (sc.function != NULL && sc_parent_die) { + symbol_context_scope = + sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID()); + if (symbol_context_scope == NULL) + symbol_context_scope = sc.function; + } else + symbol_context_scope = sc.module_sp.get(); + + if (symbol_context_scope != NULL) { + type_sp->SetSymbolContextScope(symbol_context_scope); + } + + // We are ready to put this type into the uniqued list up at the module + // level + type_list->Insert(type_sp); + + dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); } return type_sp; } @@ -1920,9 +1697,9 @@ m_property_setter_name(property_setter_name), m_property_getter_name(property_getter_name), m_property_attributes(property_attributes) { - if (metadata != NULL) { - m_metadata_ap.reset(new ClangASTMetadata()); - *m_metadata_ap = *metadata; + if (metadata != nullptr) { + m_metadata_up.reset(new ClangASTMetadata()); + *m_metadata_up = *metadata; } } @@ -1940,9 +1717,9 @@ m_property_getter_name = rhs.m_property_getter_name; m_property_attributes = rhs.m_property_attributes; - if (rhs.m_metadata_ap.get()) { - m_metadata_ap.reset(new ClangASTMetadata()); - *m_metadata_ap = *rhs.m_metadata_ap; + if (rhs.m_metadata_up) { + m_metadata_up.reset(new ClangASTMetadata()); + *m_metadata_up = *rhs.m_metadata_up; } return *this; } @@ -1951,7 +1728,7 @@ return ClangASTContext::AddObjCClassProperty( m_class_opaque_type, m_property_name, m_property_opaque_type, m_ivar_decl, m_property_setter_name, m_property_getter_name, - m_property_attributes, m_metadata_ap.get()); + m_property_attributes, m_metadata_up.get()); } private: @@ -1962,7 +1739,7 @@ const char *m_property_setter_name; const char *m_property_getter_name; uint32_t m_property_attributes; - std::unique_ptr<ClangASTMetadata> m_metadata_ap; + std::unique_ptr<ClangASTMetadata> m_metadata_up; }; bool DWARFASTParserClang::ParseTemplateDIE( @@ -2015,7 +1792,7 @@ case DW_AT_type: if (attributes.ExtractFormValueAtIndex(i, form_value)) { - Type *lldb_type = die.ResolveTypeUID(DIERef(form_value)); + Type *lldb_type = die.ResolveTypeUID(form_value.Reference()); if (lldb_type) clang_type = lldb_type->GetForwardCompilerType(); } @@ -2118,7 +1895,6 @@ return false; #if defined LLDB_CONFIGURATION_DEBUG - //---------------------------------------------------------------------- // For debugging purposes, the LLDB_DWARF_DONT_COMPLETE_TYPENAMES environment // variable can be set with one or more typenames separated by ';' // characters. This will cause this function to not complete any types whose @@ -2128,7 +1904,6 @@ // // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo;Bar;Baz - //---------------------------------------------------------------------- const char *dont_complete_typenames_cstr = getenv("LLDB_DWARF_DONT_COMPLETE_TYPENAMES"); if (dont_complete_typenames_cstr && dont_complete_typenames_cstr[0]) { @@ -2191,26 +1966,21 @@ default_accessibility = eAccessPrivate; } - SymbolContext sc(die.GetLLDBCompileUnit()); std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases; std::vector<int> member_accessibilities; bool is_a_class = false; // Parse members and base classes first - DWARFDIECollection member_function_dies; + std::vector<DWARFDIE> member_function_dies; DelayedPropertyList delayed_properties; - ParseChildMembers(sc, die, clang_type, class_language, bases, + ParseChildMembers(die, clang_type, class_language, bases, member_accessibilities, member_function_dies, delayed_properties, default_accessibility, is_a_class, layout_info); // Now parse any methods if there were any... - size_t num_functions = member_function_dies.Size(); - if (num_functions > 0) { - for (size_t i = 0; i < num_functions; ++i) { - dwarf->ResolveType(member_function_dies.GetDIEAtIndex(i)); - } - } + for (const DWARFDIE &die : member_function_dies) + dwarf->ResolveType(die); if (class_language == eLanguageTypeObjC) { ConstString class_name(clang_type.GetTypeName()); @@ -2313,7 +2083,7 @@ !layout_info.base_offsets.empty() || !layout_info.vbase_offsets.empty()) { if (type) - layout_info.bit_size = type->GetByteSize() * 8; + layout_info.bit_size = type->GetByteSize().getValueOr(0) * 8; if (layout_info.bit_size == 0) layout_info.bit_size = die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8; @@ -2394,11 +2164,10 @@ case DW_TAG_enumeration_type: if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) { if (die.HasChildren()) { - SymbolContext sc(die.GetLLDBCompileUnit()); bool is_signed = false; clang_type.IsIntegerType(is_signed); - ParseChildEnumerators(sc, clang_type, is_signed, type->GetByteSize(), - die); + ParseChildEnumerators(clang_type, is_signed, + type->GetByteSize().getValueOr(0), die); } ClangASTContext::CompleteTagDeclarationDefinition(clang_type); } @@ -2447,8 +2216,8 @@ } size_t DWARFASTParserClang::ParseChildEnumerators( - const SymbolContext &sc, lldb_private::CompilerType &clang_type, - bool is_signed, uint32_t enumerator_byte_size, const DWARFDIE &parent_die) { + lldb_private::CompilerType &clang_type, bool is_signed, + uint32_t enumerator_byte_size, const DWARFDIE &parent_die) { if (!parent_die) return 0; @@ -2461,7 +2230,7 @@ DWARFAttributes attributes; const size_t num_child_attributes = die.GetAttributes(attributes); if (num_child_attributes > 0) { - const char *name = NULL; + const char *name = nullptr; bool got_value = false; int64_t enum_value = 0; Declaration decl; @@ -2487,8 +2256,7 @@ case DW_AT_description: default: case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); + decl.SetFile(die.GetCU()->GetFile(form_value.Unsigned())); break; case DW_AT_decl_line: decl.SetLine(form_value.Unsigned()); @@ -2564,20 +2332,20 @@ Function *DWARFASTParserClang::ParseFunctionFromDWARF(CompileUnit &comp_unit, const DWARFDIE &die) { DWARFRangeList func_ranges; - const char *name = NULL; - const char *mangled = NULL; + const char *name = nullptr; + const char *mangled = nullptr; int decl_file = 0; int decl_line = 0; int decl_column = 0; int call_file = 0; int call_line = 0; int call_column = 0; - DWARFExpression frame_base(die.GetCU()); + DWARFExpression frame_base; const dw_tag_t tag = die.Tag(); if (tag != DW_TAG_subprogram) - return NULL; + return nullptr; if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line, decl_column, call_file, call_line, call_column, @@ -2603,7 +2371,8 @@ func_name.SetValue(ConstString(mangled), true); else if ((die.GetParent().Tag() == DW_TAG_compile_unit || die.GetParent().Tag() == DW_TAG_partial_unit) && - Language::LanguageIsCPlusPlus(die.GetLanguage()) && name && + Language::LanguageIsCPlusPlus(die.GetLanguage()) && + !Language::LanguageIsObjC(die.GetLanguage()) && name && strcmp(name, "main") != 0) { // If the mangled name is not present in the DWARF, generate the // demangled name using the decl context. We skip if the function is @@ -2622,9 +2391,9 @@ clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE(die, nullptr); - ParseChildParameters(comp_unit, containing_decl_ctx, die, true, - is_static, is_variadic, has_template_params, - param_types, param_decls, type_quals); + ParseChildParameters(containing_decl_ctx, die, true, is_static, + is_variadic, has_template_params, param_types, + param_decls, type_quals); sstr << "("; for (size_t i = 0; i < param_types.size(); i++) { if (i > 0) @@ -2642,26 +2411,26 @@ func_name.SetValue(ConstString(name), false); FunctionSP func_sp; - std::unique_ptr<Declaration> decl_ap; + std::unique_ptr<Declaration> decl_up; if (decl_file != 0 || decl_line != 0 || decl_column != 0) - decl_ap.reset(new Declaration( - comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file), - decl_line, decl_column)); + decl_up.reset(new Declaration(die.GetCU()->GetFile(decl_file), + decl_line, decl_column)); SymbolFileDWARF *dwarf = die.GetDWARF(); // Supply the type _only_ if it has already been parsed Type *func_type = dwarf->GetDIEToType().lookup(die.GetDIE()); - assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED); + assert(func_type == nullptr || func_type != DIE_IS_BEING_PARSED); if (dwarf->FixupAddress(func_range.GetBaseAddress())) { const user_id_t func_user_id = die.GetID(); - func_sp.reset(new Function(&comp_unit, + func_sp = + std::make_shared<Function>(&comp_unit, func_user_id, // UserID is the DIE offset func_user_id, func_name, func_type, - func_range)); // first address range + func_range); // first address range - if (func_sp.get() != NULL) { + if (func_sp.get() != nullptr) { if (frame_base.IsValid()) func_sp->GetFrameBaseExpression() = frame_base; comp_unit.AddFunction(func_sp); @@ -2670,19 +2439,19 @@ } } } - return NULL; + return nullptr; } bool DWARFASTParserClang::ParseChildMembers( - const SymbolContext &sc, const DWARFDIE &parent_die, - CompilerType &class_clang_type, const LanguageType class_language, + const DWARFDIE &parent_die, CompilerType &class_clang_type, + const LanguageType class_language, std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes, std::vector<int> &member_accessibilities, - DWARFDIECollection &member_function_dies, + std::vector<DWARFDIE> &member_function_dies, DelayedPropertyList &delayed_properties, AccessType &default_accessibility, bool &is_a_class, ClangASTImporter::LayoutInfo &layout_info) { if (!parent_die) - return 0; + return false; // Get the parent byte size so we can verify any members will fit const uint64_t parent_byte_size = @@ -2697,7 +2466,7 @@ ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(class_clang_type.GetTypeSystem()); if (ast == nullptr) - return 0; + return false; for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid(); die = die.GetSibling()) { @@ -2709,12 +2478,10 @@ DWARFAttributes attributes; const size_t num_attributes = die.GetAttributes(attributes); if (num_attributes > 0) { - Declaration decl; - // DWARFExpression location; - const char *name = NULL; - const char *prop_name = NULL; - const char *prop_getter_name = NULL; - const char *prop_setter_name = NULL; + const char *name = nullptr; + const char *prop_name = nullptr; + const char *prop_getter_name = nullptr; + const char *prop_setter_name = nullptr; uint32_t prop_attributes = 0; bool is_artificial = false; @@ -2722,7 +2489,7 @@ AccessType accessibility = eAccessNone; uint32_t member_byte_offset = (parent_die.Tag() == DW_TAG_union_type) ? 0 : UINT32_MAX; - size_t byte_size = 0; + llvm::Optional<uint64_t> byte_size; int64_t bit_offset = 0; uint64_t data_bit_offset = UINT64_MAX; size_t bit_size = 0; @@ -2734,16 +2501,6 @@ DWARFFormValue form_value; if (attributes.ExtractFormValueAtIndex(i, form_value)) { switch (attr) { - case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; case DW_AT_name: name = form_value.AsCString(); break; @@ -2776,7 +2533,8 @@ module_sp, debug_info_data, die.GetCU(), block_offset, block_length, eRegisterKindDWARF, &initialValue, nullptr, memberOffset, nullptr)) { - member_byte_offset = memberOffset.ResolveValue(NULL).UInt(); + member_byte_offset = + memberOffset.ResolveValue(nullptr).UInt(); } } else { // With DWARF 3 and later, if the value is an integer constant, @@ -2865,7 +2623,7 @@ // with a crash if we try to use this type in an expression when clang // becomes unhappy with its recycled debug info. - if (byte_size == 0 && bit_offset < 0) { + if (byte_size.getValueOr(0) == 0 && bit_offset < 0) { bit_size = 0; bit_offset = 0; } @@ -2877,7 +2635,7 @@ // Handle static members if (is_external && member_byte_offset == UINT32_MAX) { - Type *var_type = die.ResolveTypeUID(DIERef(encoding_form)); + Type *var_type = die.ResolveTypeUID(encoding_form.Reference()); if (var_type) { if (accessibility == eAccessNone) @@ -2890,9 +2648,9 @@ } if (!is_artificial) { - Type *member_type = die.ResolveTypeUID(DIERef(encoding_form)); + Type *member_type = die.ResolveTypeUID(encoding_form.Reference()); - clang::FieldDecl *field_decl = NULL; + clang::FieldDecl *field_decl = nullptr; if (tag == DW_TAG_member) { if (member_type) { if (accessibility == eAccessNone) @@ -2927,12 +2685,12 @@ if (data_bit_offset != UINT64_MAX) { this_field_info.bit_offset = data_bit_offset; } else { - if (byte_size == 0) + if (!byte_size) byte_size = member_type->GetByteSize(); ObjectFile *objfile = die.GetDWARF()->GetObjectFile(); if (objfile->GetByteOrder() == eByteOrderLittle) { - this_field_info.bit_offset += byte_size * 8; + this_field_info.bit_offset += byte_size.getValueOr(0) * 8; this_field_info.bit_offset -= (bit_offset + bit_size); } else { this_field_info.bit_offset += bit_offset; @@ -2945,13 +2703,12 @@ ObjectFile *objfile = die.GetDWARF()->GetObjectFile(); objfile->GetModule()->ReportWarning( "0x%8.8" PRIx64 ": %s bitfield named \"%s\" has invalid " - "bit offset (0x%8.8" PRIx64 + "bit offset (0x%8.8" PRIx64 ") member will be ignored. Please file a bug against the " "compiler and include the preprocessed output for %s\n", die.GetID(), DW_TAG_value_to_name(tag), name, this_field_info.bit_offset, - sc.comp_unit ? sc.comp_unit->GetPath().c_str() - : "the source file"); + GetUnitName(parent_die).c_str()); this_field_info.Clear(); continue; } @@ -3074,9 +2831,10 @@ member_byte_offset > parent_byte_size)) { module_sp->ReportError( "0x%8.8" PRIx64 - ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64 + ": DW_TAG_member '%s' refers to type 0x%8.8x" " which extends beyond the bounds of 0x%8.8" PRIx64, - die.GetID(), name, encoding_form.Reference(), + die.GetID(), name, + encoding_form.Reference().GetOffset(), parent_die.GetID()); } @@ -3103,9 +2861,7 @@ "complete definition.\nPlease file a bug against the " "compiler and include the preprocessed output for %s", parent_die.GetOffset(), parent_die.GetName(), - die.GetOffset(), name, - sc.comp_unit ? sc.comp_unit->GetPath().c_str() - : "the source file"); + die.GetOffset(), name, GetUnitName(parent_die).c_str()); // We have no choice other than to pretend that the member // class is complete. If we don't do this, clang will crash // when trying to layout the class. Since we provide layout @@ -3139,24 +2895,23 @@ if (name) module_sp->ReportError( "0x%8.8" PRIx64 - ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64 + ": DW_TAG_member '%s' refers to type 0x%8.8x" " which was unable to be parsed", - die.GetID(), name, encoding_form.Reference()); + die.GetID(), name, encoding_form.Reference().GetOffset()); else module_sp->ReportError( - "0x%8.8" PRIx64 - ": DW_TAG_member refers to type 0x%8.8" PRIx64 + "0x%8.8" PRIx64 ": DW_TAG_member refers to type 0x%8.8x" " which was unable to be parsed", - die.GetID(), encoding_form.Reference()); + die.GetID(), encoding_form.Reference().GetOffset()); } } - if (prop_name != NULL && member_type) { - clang::ObjCIvarDecl *ivar_decl = NULL; + if (prop_name != nullptr && member_type) { + clang::ObjCIvarDecl *ivar_decl = nullptr; if (field_decl) { ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl); - assert(ivar_decl != NULL); + assert(ivar_decl != nullptr); } ClangASTMetadata metadata; @@ -3177,7 +2932,7 @@ case DW_TAG_subprogram: // Let the type parsing code handle this one for us. - member_function_dies.Append(die); + member_function_dies.push_back(die); break; case DW_TAG_inheritance: { @@ -3188,8 +2943,6 @@ DWARFAttributes attributes; const size_t num_attributes = die.GetAttributes(attributes); if (num_attributes > 0) { - Declaration decl; - DWARFExpression location(die.GetCU()); DWARFFormValue encoding_form; AccessType accessibility = default_accessibility; bool is_virtual = false; @@ -3201,16 +2954,6 @@ DWARFFormValue form_value; if (attributes.ExtractFormValueAtIndex(i, form_value)) { switch (attr) { - case DW_AT_decl_file: - decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; case DW_AT_type: encoding_form = form_value; break; @@ -3227,7 +2970,8 @@ block_offset, block_length, eRegisterKindDWARF, &initialValue, nullptr, memberOffset, nullptr)) { - member_byte_offset = memberOffset.ResolveValue(NULL).UInt(); + member_byte_offset = + memberOffset.ResolveValue(nullptr).UInt(); } } else { // With DWARF 3 and later, if the value is an integer constant, @@ -3254,14 +2998,15 @@ } } - Type *base_class_type = die.ResolveTypeUID(DIERef(encoding_form)); - if (base_class_type == NULL) { + Type *base_class_type = die.ResolveTypeUID(encoding_form.Reference()); + if (base_class_type == nullptr) { module_sp->ReportError("0x%8.8x: DW_TAG_inheritance failed to " - "resolve the base class at 0x%8.8" PRIx64 + "resolve the base class at 0x%8.8x" " from enclosing type 0x%8.8x. \nPlease file " "a bug and attach the file at the start of " "this error message", - die.GetOffset(), encoding_form.Reference(), + die.GetOffset(), + encoding_form.Reference().GetOffset(), parent_die.GetOffset()); break; } @@ -3313,10 +3058,9 @@ } size_t DWARFASTParserClang::ParseChildParameters( - CompileUnit &comp_unit, clang::DeclContext *containing_decl_ctx, - const DWARFDIE &parent_die, bool skip_artificial, bool &is_static, - bool &is_variadic, bool &has_template_params, - std::vector<CompilerType> &function_param_types, + clang::DeclContext *containing_decl_ctx, const DWARFDIE &parent_die, + bool skip_artificial, bool &is_static, bool &is_variadic, + bool &has_template_params, std::vector<CompilerType> &function_param_types, std::vector<clang::ParmVarDecl *> &function_param_decls, unsigned &type_quals) { if (!parent_die) @@ -3331,8 +3075,7 @@ DWARFAttributes attributes; const size_t num_attributes = die.GetAttributes(attributes); if (num_attributes > 0) { - const char *name = NULL; - Declaration decl; + const char *name = nullptr; DWARFFormValue param_type_die_form; bool is_artificial = false; // one of None, Auto, Register, Extern, Static, PrivateExtern @@ -3344,16 +3087,6 @@ DWARFFormValue form_value; if (attributes.ExtractFormValueAtIndex(i, form_value)) { switch (attr) { - case DW_AT_decl_file: - decl.SetFile(comp_unit.GetSupportFiles().GetFileSpecAtIndex( - form_value.Unsigned())); - break; - case DW_AT_decl_line: - decl.SetLine(form_value.Unsigned()); - break; - case DW_AT_decl_column: - decl.SetColumn(form_value.Unsigned()); - break; case DW_AT_name: name = form_value.AsCString(); break; @@ -3388,8 +3121,9 @@ // Often times compilers omit the "this" name for the // specification DIEs, so we can't rely upon the name being in // the formal parameter DIE... - (name == NULL || ::strcmp(name, "this") == 0)) { - Type *this_type = die.ResolveTypeUID(DIERef(param_type_die_form)); + (name == nullptr || ::strcmp(name, "this") == 0)) { + Type *this_type = + die.ResolveTypeUID(param_type_die_form.Reference()); if (this_type) { uint32_t encoding_mask = this_type->GetEncodingMask(); if (encoding_mask & Type::eEncodingIsPointerUID) { @@ -3406,7 +3140,7 @@ } if (!skip) { - Type *type = die.ResolveTypeUID(DIERef(param_type_die_form)); + Type *type = die.ResolveTypeUID(param_type_die_form.Reference()); if (type) { function_param_types.push_back(type->GetForwardCompilerType()); @@ -3554,7 +3288,7 @@ if (attr == DW_AT_type && attributes.ExtractFormValueAtIndex(i, form_value)) - return dwarf->ResolveTypeUID(dwarf->GetDIE(DIERef(form_value)), true); + return dwarf->ResolveTypeUID(form_value.Reference(), true); } } } @@ -3799,8 +3533,11 @@ const char *namespace_name = die.GetName(); clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE(die, nullptr); - namespace_decl = m_ast.GetUniqueNamespaceDeclaration(namespace_name, - containing_decl_ctx); + bool is_inline = + die.GetAttributeValueAsUnsigned(DW_AT_export_symbols, 0) != 0; + + namespace_decl = m_ast.GetUniqueNamespaceDeclaration( + namespace_name, containing_decl_ctx, is_inline); Log *log = nullptr; // (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO)); if (log) { @@ -3870,7 +3607,7 @@ bool DWARFASTParserClang::CopyUniqueClassMethodTypes( const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die, - lldb_private::Type *class_type, DWARFDIECollection &failures) { + lldb_private::Type *class_type, std::vector<DWARFDIE> &failures) { if (!class_type || !src_class_die || !dst_class_die) return false; if (src_class_die.Tag() != dst_class_die.Tag()) @@ -4075,7 +3812,7 @@ log->Printf("warning: couldn't find a match for 0x%8.8x", dst_die.GetOffset()); - failures.Append(dst_die); + failures.push_back(dst_die); } } } @@ -4140,9 +3877,9 @@ "method '%s'", dst_die.GetOffset(), dst_name_artificial.GetCString()); - failures.Append(dst_die); + failures.push_back(dst_die); } } - return (failures.Size() != 0); + return !failures.empty(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.h index 63e058d..5b5d83d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.h
@@ -1,9 +1,8 @@ //===-- DWARFASTParserClang.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,11 +21,12 @@ #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/ClangASTImporter.h" +#include <vector> + namespace lldb_private { class CompileUnit; } class DWARFDebugInfoEntry; -class DWARFDIECollection; class SymbolFileDWARF; class DWARFASTParserClang : public DWARFASTParser { @@ -81,19 +81,17 @@ &template_param_infos); bool ParseChildMembers( - const lldb_private::SymbolContext &sc, const DWARFDIE &die, - lldb_private::CompilerType &class_compiler_type, + const DWARFDIE &die, lldb_private::CompilerType &class_compiler_type, const lldb::LanguageType class_language, std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes, std::vector<int> &member_accessibilities, - DWARFDIECollection &member_function_dies, + std::vector<DWARFDIE> &member_function_dies, DelayedPropertyList &delayed_properties, lldb::AccessType &default_accessibility, bool &is_a_class, lldb_private::ClangASTImporter::LayoutInfo &layout_info); size_t - ParseChildParameters(lldb_private::CompileUnit &comp_unit, - clang::DeclContext *containing_decl_ctx, + ParseChildParameters(clang::DeclContext *containing_decl_ctx, const DWARFDIE &parent_die, bool skip_artificial, bool &is_static, bool &is_variadic, bool &has_template_params, @@ -101,8 +99,7 @@ std::vector<clang::ParmVarDecl *> &function_param_decls, unsigned &type_quals); - size_t ParseChildEnumerators(const lldb_private::SymbolContext &sc, - lldb_private::CompilerType &compiler_type, + size_t ParseChildEnumerators(lldb_private::CompilerType &compiler_type, bool is_signed, uint32_t enumerator_byte_size, const DWARFDIE &parent_die); @@ -118,7 +115,7 @@ bool CopyUniqueClassMethodTypes(const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die, lldb_private::Type *class_type, - DWARFDIECollection &failures); + std::vector<DWARFDIE> &failures); clang::DeclContext *GetCachedClangDeclContextForDIE(const DWARFDIE &die); @@ -128,10 +125,8 @@ lldb::TypeSP ParseTypeFromDWO(const DWARFDIE &die, lldb_private::Log *log); - //---------------------------------------------------------------------- // Return true if this type is a declaration to a type in an external // module. - //---------------------------------------------------------------------- lldb::ModuleSP GetModuleForType(const DWARFDIE &die); typedef llvm::SmallPtrSet<const DWARFDebugInfoEntry *, 4> DIEPointerSet; @@ -150,7 +145,7 @@ DeclToDIEMap m_decl_to_die; DIEToDeclContextMap m_die_to_decl_ctx; DeclContextToDIEMap m_decl_ctx_to_die; - std::unique_ptr<lldb_private::ClangASTImporter> m_clang_ast_importer_ap; + std::unique_ptr<lldb_private::ClangASTImporter> m_clang_ast_importer_up; }; #endif // SymbolFileDWARF_DWARFASTParserClang_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserRust.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserRust.cpp deleted file mode 100644 index 9eaaf74..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserRust.cpp +++ /dev/null
@@ -1,1210 +0,0 @@ -//===-- DWARFASTParserRust.cpp ---------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "DWARFASTParserRust.h" - -#include "DWARFASTParserRust.h" -#include "DWARFCompileUnit.h" -#include "DWARFDIE.h" -#include "DWARFDIECollection.h" -#include "DWARFDebugInfo.h" -#include "DWARFDeclContext.h" -#include "DWARFDefines.h" -#include "SymbolFileDWARF.h" -#include "SymbolFileDWARFDebugMap.h" -#include "UniqueDWARFASTType.h" - -#include "clang/Basic/Specifiers.h" - -#include "lldb/Core/Module.h" -#include "lldb/Core/Value.h" -#include "lldb/Symbol/CompileUnit.h" -#include "lldb/Symbol/Function.h" -#include "lldb/Symbol/ObjectFile.h" -#include "lldb/Symbol/TypeList.h" - -using namespace lldb; -using namespace lldb_private; - -#define INVALID_ATTR dw_attr_t(-1) - -// A way to iterate over DIE attrs. -class IterableDIEAttrs -{ -public: - IterableDIEAttrs(const DWARFDIE &die) - { - m_size = die.GetAttributes(m_attrs); - } - - IterableDIEAttrs(const IterableDIEAttrs &) = delete; - IterableDIEAttrs &operator=(const IterableDIEAttrs &) = delete; - - class iterator - { - public: - - iterator(const IterableDIEAttrs *die, size_t offset) - : m_die(die) - , m_offset(offset) - { - } - - iterator(const iterator &other) - : m_die(other.m_die) - , m_offset(other.m_offset) - { - } - - iterator &operator=(const iterator &other) - { - m_die = other.m_die; - m_offset = other.m_offset; - return *this; - } - - iterator &operator++() - { - ++m_offset; - return *this; - } - - bool operator!=(const iterator &other) const - { - return m_die != other.m_die || m_offset != other.m_offset; - } - - std::pair<dw_attr_t, DWARFFormValue> operator*() const - { - dw_attr_t attr = m_die->m_attrs.AttributeAtIndex(m_offset); - DWARFFormValue value; - if (!m_die->m_attrs.ExtractFormValueAtIndex(m_offset, value)) - attr = INVALID_ATTR; - return std::make_pair(attr, value); - } - - private: - - const IterableDIEAttrs *m_die; - size_t m_offset; - }; - - iterator begin() const - { - return iterator(this, 0); - } - - iterator end() const - { - return iterator(this, m_size); - } - -private: - - size_t m_size; - DWARFAttributes m_attrs; -}; - -// A way to iterate over a DIE's direct children. -class IterableDIEChildren -{ -public: - IterableDIEChildren(const DWARFDIE &die) - : m_die(die) - { - } - - IterableDIEChildren(const IterableDIEChildren &) = delete; - IterableDIEChildren &operator=(const IterableDIEChildren &) = delete; - - class iterator - { - public: - - iterator(const DWARFDIE &die) - : m_die(die) - { - } - - ~iterator() - { - } - - iterator(const iterator &other) - : m_die(other.m_die) - { - } - - iterator &operator=(const iterator &other) - { - m_die = other.m_die; - return *this; - } - - iterator &operator++() - { - m_die = m_die.GetSibling(); - return *this; - } - - bool operator!=(const iterator &other) const - { - return m_die != other.m_die; - } - - DWARFDIE operator*() const - { - return m_die; - } - - private: - - DWARFDIE m_die; - }; - - iterator begin() const - { - return iterator(m_die.GetFirstChild()); - } - - iterator end() const - { - return iterator(DWARFDIE(m_die.GetCU(), (DWARFDebugInfoEntry*) nullptr)); - } - -private: - - DWARFDIE m_die; -}; - -ConstString DWARFASTParserRust::FullyQualify(const ConstString &name, const DWARFDIE &die) { - SymbolFileDWARF *dwarf = die.GetDWARF(); - lldb::user_id_t id = die.GetID(); - CompilerDeclContext ctx = dwarf->GetDeclContextContainingUID(id); - ConstString ctx_name = ctx.GetScopeQualifiedName(); - if (!ctx_name) { - return name; - } - std::string qual_name = std::string(ctx_name.AsCString()) + "::" + name.AsCString(); - return ConstString(qual_name.c_str()); -} - -TypeSP DWARFASTParserRust::ParseSimpleType(lldb_private::Log *log, const DWARFDIE &die) { - lldb::user_id_t encoding_uid = LLDB_INVALID_UID; - const char *type_name_cstr = NULL; - ConstString type_name_const_str; - uint64_t byte_size = 0; - uint64_t encoding = 0; - - for (auto &&value : IterableDIEAttrs(die)) { - switch (value.first) { - case DW_AT_name: - type_name_cstr = value.second.AsCString(); - if (type_name_cstr) - type_name_const_str.SetCString(type_name_cstr); - break; - case DW_AT_byte_size: - byte_size = value.second.Unsigned(); - break; - case DW_AT_encoding: - encoding = value.second.Unsigned(); - break; - case DW_AT_type: - encoding_uid = value.second.Reference(); - break; - } - } - - SymbolFileDWARF *dwarf = die.GetDWARF(); - Type::ResolveState resolve_state = Type::eResolveStateUnresolved; - CompilerType compiler_type; - Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID; - switch (die.Tag()) { - case DW_TAG_unspecified_type: - resolve_state = Type::eResolveStateFull; - compiler_type = m_ast.CreateVoidType(); - break; - - case DW_TAG_base_type: - resolve_state = Type::eResolveStateFull; - if (encoding == DW_ATE_boolean) - compiler_type = m_ast.CreateBoolType(type_name_const_str); - else if (encoding == DW_ATE_float) - compiler_type = m_ast.CreateFloatType(type_name_const_str, byte_size); - else if (byte_size == 0 && type_name_const_str && - strcmp(type_name_const_str.AsCString(), "()") == 0) - compiler_type = m_ast.CreateTupleType(type_name_const_str, byte_size, false); - else if (encoding == DW_ATE_signed || encoding == DW_ATE_unsigned || - // DW_ATE_UCS seems to be less used (perhaps - // Fortran-specific?) and since I'm not planning to have - // rustc emit it, we ignore it here. - encoding == DW_ATE_unsigned_char || encoding == DW_ATE_UTF) - compiler_type = m_ast.CreateIntegralType(type_name_const_str, - encoding == DW_ATE_signed, - byte_size, - (encoding == DW_ATE_unsigned_char || - encoding == DW_ATE_UTF)); - else - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "DWARFASTParserRust::ParseSimpleType (die = 0x%8.8x) %s " - "unrecognized encoding '%d')", - die.GetOffset(), DW_TAG_value_to_name(die.Tag()), int(encoding)); - break; - - // Note that, currently, rustc does not emit DW_TAG_reference_type - // - references are distinguished by name; and also we don't want - // to treat Rust references as CompilerType references. - case DW_TAG_typedef: - type_name_const_str = FullyQualify(type_name_const_str, die); - // Fall through. - case DW_TAG_pointer_type: - case DW_TAG_template_type_parameter: { - Type *type = dwarf->ResolveTypeUID(encoding_uid); - if (type) { - CompilerType impl = type->GetForwardCompilerType(); - if (die.Tag() == DW_TAG_pointer_type) { - int byte_size = die.GetCU()->GetAddressByteSize(); - m_ast.SetAddressByteSize(byte_size); - compiler_type = m_ast.CreatePointerType(type_name_const_str, impl, byte_size); - encoding_data_type = Type::eEncodingIsPointerUID; - } else { - compiler_type = m_ast.CreateTypedefType(type_name_const_str, impl); - encoding_data_type = Type::eEncodingIsTypedefUID; - } - } - break; - } - - default: - // Should have been filtered by the caller. - assert(0); - } - - return TypeSP(new Type(die.GetID(), dwarf, type_name_const_str, - byte_size, NULL, encoding_uid, - encoding_data_type, Declaration(), compiler_type, - resolve_state)); -} - -TypeSP DWARFASTParserRust::ParseArrayType(const DWARFDIE &die) { - lldb::user_id_t type_die_offset = DW_INVALID_OFFSET; - - for (auto &&value : IterableDIEAttrs(die)) { - switch (value.first) { - case DW_AT_type: - type_die_offset = value.second.Reference(); - break; - } - } - - SymbolFileDWARF *dwarf = die.GetDWARF(); - Type *element_type = dwarf->ResolveTypeUID(type_die_offset); - if (!element_type) - return TypeSP(nullptr); - - CompilerType compiler_type; - uint64_t count = 0; - - for (auto &&child_die : IterableDIEChildren(die)) { - if (child_die.Tag() == DW_TAG_subrange_type) { - for (auto &&value : IterableDIEAttrs(child_die)) { - if (value.first == DW_AT_count) { - count = value.second.Unsigned(); - break; - } - } - break; - } - } - - CompilerType array_element_type = element_type->GetForwardCompilerType(); - compiler_type = m_ast.CreateArrayType(array_element_type, count); - - ConstString type_name_const_str = compiler_type.GetTypeName(); - TypeSP type_sp(new Type(die.GetID(), dwarf, type_name_const_str, - element_type->GetByteSize(), NULL, type_die_offset, - Type::eEncodingIsUID, Declaration(), compiler_type, - Type::eResolveStateFull)); - type_sp->SetEncodingType(element_type); - return type_sp; -} - -TypeSP DWARFASTParserRust::ParseFunctionType(const DWARFDIE &die) { - clang::StorageClass storage = clang::SC_None; //, Extern, Static, PrivateExtern - const char *type_name_cstr = NULL; - ConstString type_name_const_str; - Declaration decl; - - CompilerType return_type; - for (auto &&attr : IterableDIEAttrs(die)) { - switch (attr.first) { - case DW_AT_name: - type_name_cstr = attr.second.AsCString(); - type_name_const_str.SetCString(type_name_cstr); - break; - - case DW_AT_external: - if (attr.second.Unsigned()) { - if (storage == clang::SC_None) - storage = clang::SC_Extern; - else - storage = clang::SC_PrivateExtern; - } - break; - - case DW_AT_type: { - Type *type = die.ResolveTypeUID(DIERef(attr.second)); - if (type) { - return_type = type->GetForwardCompilerType(); - } - break; - } - } - } - - if (!return_type) { - return_type = m_ast.CreateVoidType(); - } - - SymbolFileDWARF *dwarf = die.GetDWARF(); - std::vector<CompilerType> function_param_types; - std::vector<CompilerType> template_params; - for (auto &&child_die : IterableDIEChildren(die)) { - if (child_die.Tag() == DW_TAG_formal_parameter) { - for (auto &&attr : IterableDIEAttrs(child_die)) { - if (attr.first == DW_AT_type) { - Type *type = die.ResolveTypeUID(DIERef(attr.second)); - if (type) { - function_param_types.push_back(type->GetForwardCompilerType()); - } - break; - } - } - } else if (child_die.Tag() == DW_TAG_template_type_parameter) { - Type *param_type = dwarf->ResolveTypeUID(child_die, true); - if (param_type) { - template_params.push_back(param_type->GetForwardCompilerType()); - } - } - } - - CompilerType compiler_type = m_ast.CreateFunctionType(type_name_const_str, return_type, - std::move(function_param_types), - std::move(template_params)); - - TypeSP type_sp(new Type(die.GetID(), dwarf, type_name_const_str, 0, NULL, - LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, - compiler_type, Type::eResolveStateFull)); - - return type_sp; -} - -static bool starts_with(const char *str, const char *prefix) { - return strncmp(str, prefix, strlen(prefix)) == 0; -} - -#define RUST_ENCODED_PREFIX "RUST$ENCODED$ENUM$" - -std::vector<size_t> DWARFASTParserRust::ParseDiscriminantPath(const char **in_str) { - std::vector<size_t> result; - const char *str = *in_str; - - assert(starts_with(str, RUST_ENCODED_PREFIX)); - str += strlen(RUST_ENCODED_PREFIX); - - // We're going to push a synthetic unit struct field as the enum - // type's first member, so the resulting discriminant path always - // starts with 1. - result.push_back(1); - - while (*str >= '0' && *str <= '9') { - char *next; - unsigned long value = strtoul(str, &next, 10); - result.push_back(value); - str = next; - if (*str != '$') { - // Report an error? - *in_str = nullptr; - result.clear(); - return result; - } - ++str; - } - - // At this point, STR points to the name of the elided member type. - *in_str = str; - return result; -} - -void DWARFASTParserRust::FindDiscriminantLocation(CompilerType type, - std::vector<size_t> &&path, - uint64_t &offset, - uint64_t &byte_size) { - offset = 0; - - for (size_t index : path) { - std::string ignore_name; - uint32_t bitsize_ignore, bitoffset_ignore; - bool isbase_ignore, isderef_ignore; - uint64_t lang_flags_ignore; - - uint32_t this_size; - int32_t this_offset; - - type = m_ast.GetChildCompilerTypeAtIndex(type.GetOpaqueQualType(), nullptr, index, - false, false, true, - ignore_name, - this_size, this_offset, - bitsize_ignore, bitoffset_ignore, - isbase_ignore, isderef_ignore, - nullptr, lang_flags_ignore); - offset += this_offset; - // The last time this is done, it will hold the size of the final - // field, which is what we want. - byte_size = this_size; - } -} - -bool DWARFASTParserRust::IsPossibleEnumVariant(const DWARFDIE &die) { - if (die.Tag() != DW_TAG_structure_type) { - // Only structures can be enum variants. - return false; - } - - for (auto &&child_die : IterableDIEChildren(die)) { - if (child_die.Tag() == DW_TAG_member) { - for (auto &&attr : IterableDIEAttrs(child_die)) { - if (attr.first == DW_AT_name) { - return strcmp(attr.second.AsCString(), "RUST$ENUM$DISR") == 0; - } - } - // No name, so whatever it is, it isn't an enum variant. - return false; - } - } - - // We didn't see a member, and an empty structure might well be an - // enum variant. - return true; -} - -std::vector<DWARFASTParserRust::Field> -DWARFASTParserRust::ParseFields(const DWARFDIE &die, std::vector<size_t> &discriminant_path, - bool &is_tuple, - uint64_t &discr_offset, uint64_t &discr_byte_size, - bool &saw_discr, std::vector<CompilerType> &template_params) { - SymbolFileDWARF *dwarf = die.GetDWARF(); - - // We construct a list of fields and then apply them later so that - // we can analyze the fields to see what sort of structure this - // really is. - std::vector<Field> fields; - unsigned field_index = 0; - bool numeric_names = true; - - // We might have recursed in here with a variant part. If so, we - // want to handle the discriminant and variants specially. - bool is_variant = die.Tag() == DW_TAG_variant_part; - DWARFDIE discriminant_die; - if (is_variant) { - discriminant_die = die.GetReferencedDIE(DW_AT_discr); - } - - // For old-style ("RUST$ENUM$DISR"-using) enums that don't have the - // NonZero optimization applied, variants are listed in order of - // discriminant. We track that value here. - uint64_t naive_discriminant = 0; - - bool could_be_enum = die.Tag() == DW_TAG_union_type; - bool encoded_enum = false; - - ModuleSP module_sp = die.GetModule(); - for (auto &&child_die : IterableDIEChildren(die)) { - Field new_field; - - // If this isn't correct for this particular enum, that's ok, - // because the correct value will be computed below. - new_field.discriminant = naive_discriminant++; - - if (is_variant && child_die.Tag() == DW_TAG_variant) { - // Find the discriminant, if it exists. - for (auto &&attr : IterableDIEAttrs(child_die)) { - if (attr.first == DW_AT_discr_value) { - new_field.discriminant = attr.second.Unsigned(); - break; - } - } - - // Use the child that is a member. - bool found = false; - for (auto &&variant_child_die : IterableDIEChildren(child_die)) { - if (variant_child_die.Tag() == DW_TAG_member) { - found = true; - child_die = variant_child_die; - break; - } - } - if (!found) { - // Just ignore this variant. - continue; - } - - // Fall through and process the variant's child as if it were a - // child of the structure. - } - - if (child_die.Tag() == DW_TAG_member) { - for (auto &&attr : IterableDIEAttrs(child_die)) { - switch (attr.first) { - case DW_AT_name: - new_field.name = attr.second.AsCString(); - if (fields.size() == 0) { - if (strcmp(new_field.name, "RUST$ENUM$DISR") == 0) - new_field.is_discriminant = true; - else if (starts_with(new_field.name, RUST_ENCODED_PREFIX)) { - // The "non-zero" optimization has been applied. - // In this case, we'll see a single field like: - // RUST$ENCODED$ENUM$n0$n1...$Name - // Here n0, n1, ... are integers that describe the path - // to the discriminant. When the discriminant (and - // integer) is 0, the enum has the value Name, a - // unit-like struct. However when it is non-zero, the - // enum has the value of this field's type. - - // Here we're going to push an initial field for the - // unit-like struct. Note that the constructor sets the - // discriminant to the correct value -- zero. - Field unit_field; - unit_field.name = new_field.name; - discriminant_path = ParseDiscriminantPath(&unit_field.name); - unit_field.is_elided = true; - fields.push_back(unit_field); - - // The actual field is the default variant. - new_field.is_default = true; - new_field.name = nullptr; - encoded_enum = true; - } - } - break; - case DW_AT_type: - new_field.type = attr.second; - if (could_be_enum && !encoded_enum) { - could_be_enum = IsPossibleEnumVariant(dwarf->GetDIE(DIERef(new_field.type))); - } - break; - case DW_AT_data_member_location: - if (attr.second.BlockData()) { - Value initialValue(0); - Value memberOffset(0); - const DWARFDataExtractor &debug_info_data = - child_die.GetDWARF()->get_debug_info_data(); - uint32_t block_length = attr.second.Unsigned(); - uint32_t block_offset = attr.second.BlockData() - debug_info_data.GetDataStart(); - if (DWARFExpression::Evaluate( - NULL, // ExecutionContext * - NULL, // RegisterContext * - module_sp, debug_info_data, die.GetCU(), block_offset, - block_length, eRegisterKindDWARF, &initialValue, NULL, - memberOffset, NULL)) { - new_field.byte_offset = memberOffset.ResolveValue(NULL).UInt(); - } - } else { - new_field.byte_offset = attr.second.Unsigned(); - } - break; - } - } - } - - if (child_die == discriminant_die) { - // This field is the discriminant, so don't push it, but instead - // record this for the caller. - saw_discr = true; - discr_offset = new_field.byte_offset; - - Type *type = die.ResolveTypeUID(DIERef(new_field.type)); - if (type) { - lldb_private::CompilerType ctype = type->GetFullCompilerType(); - discr_byte_size = m_ast.GetBitSize(ctype.GetOpaqueQualType(), nullptr) / 8; - } - } else if (child_die.Tag() == DW_TAG_variant_part) { - // New-style enum representation -- nothing useful is in the - // enclosing struct, so we can just recurse here. - return ParseFields(child_die, discriminant_path, is_tuple, - discr_offset, discr_byte_size, saw_discr, template_params); - } else if (child_die.Tag() == DW_TAG_member) { - if (new_field.is_discriminant) { - // Don't check this field name, and don't increment field_index. - // When we see a tuple with fields like - // RUST$ENUM$DISR - // __0 - // __1 - // etc - // ... it means the tuple is a member type of an enum. - } else if (numeric_names) { - char buf[32]; - snprintf (buf, sizeof (buf), "__%u", field_index); - if (!new_field.name || strcmp(new_field.name, buf) != 0) - numeric_names = false; - ++field_index; - } - - fields.push_back(new_field); - } else if (child_die.Tag() == DW_TAG_template_type_parameter) { - Type *param_type = dwarf->ResolveTypeUID(child_die, true); - if (param_type) { - template_params.push_back(param_type->GetForwardCompilerType()); - } - } - } - - if (!numeric_names) { - // If the field name checking failed, maybe we don't have a tuple - // after all, somehow. - is_tuple = false; - } else if (!is_tuple) { - // If we saw numeric names in sequence, we have a tuple struct; - // but if there were no fields, then we can't tell and so we - // arbitrarily choose an empty struct. - is_tuple = field_index > 0; - } - - // If we saw a Rust enum, correctly arrange the scope of the various - // sub-types. This is needed to work around the way that the Rust - // compiler emits the types: it emits each enum variant's type as a - // sibling of the enum type, whereas logically it ought to be a - // child. - if (could_be_enum) { - for (auto &&field : fields) { - m_reparent_map[dwarf->GetDIE(DIERef(field.type)).GetDIE()] = die; - } - } - - return fields; -} - -TypeSP DWARFASTParserRust::ParseStructureType(const DWARFDIE &die) { - const bool is_union = die.Tag() == DW_TAG_union_type; - - bool byte_size_valid = false; - uint64_t byte_size = 0; - const char *type_name_cstr = NULL; - ConstString type_name_const_str; - SymbolFileDWARF *dwarf = die.GetDWARF(); - Declaration decl; - - for (auto &&attr : IterableDIEAttrs(die)) { - switch (attr.first) { - case DW_AT_name: - type_name_cstr = attr.second.AsCString(); - type_name_const_str.SetCString(type_name_cstr); - break; - - case DW_AT_byte_size: - byte_size = attr.second.Unsigned(); - byte_size_valid = true; - break; - } - } - - UniqueDWARFASTType ast_entry; - TypeSP type_sp; - - // Only try and unique the type if it has a name. - if (type_name_const_str && - dwarf->GetUniqueDWARFASTTypeMap().Find(type_name_const_str, die, &decl, - byte_size_valid ? byte_size : -1, ast_entry)) { - // We have already parsed this type. - type_sp = ast_entry.m_type_sp; - if (type_sp) { - dwarf->m_die_to_type[die.GetDIE()] = type_sp.get(); - return type_sp; - } - } - - // Currently, rustc emits tuples with a name starting with "("; but - // there's no way to distinguish a zero-length struct from a - // zero-length tuple struct. This decision might be changed by - // ParseFields. - bool is_tuple = type_name_cstr && type_name_cstr[0] == '('; - // We might see a tuple struct, and we want to differentiate the two - // when qualifying names. - bool is_anon_tuple = is_tuple; - bool saw_discr = false; - uint64_t discr_offset, discr_byte_size; - std::vector<size_t> discriminant_path; - std::vector<CompilerType> template_params; - std::vector<Field> fields = ParseFields(die, discriminant_path, is_tuple, - discr_offset, discr_byte_size, saw_discr, - template_params); - - // This is true if this is a union, there are multiple fields and - // each field's type has a discriminant. - bool all_have_discriminants = is_union && fields.size() > 0; - // This is true if the current type has a discriminant. - // all_have_discriminants records whether the outer type is a Rust - // enum; this records whether the current type is one variant type - // of the enum. - bool has_discriminant = fields.size() > 0 && fields[0].is_discriminant; - - // See the comment by m_discriminant to understand this. - DIERef save_discr = m_discriminant; - if (has_discriminant) - m_discriminant = DIERef(fields[0].type); - - // Have to resolve the field types before creating the outer type, - // so that we can see whether or not this is an enum. - for (auto &&field : fields) { - if (field.is_elided) { - // A unit-like struct with the given name. The byte size - // probably doesn't matter. - ConstString name = FullyQualify(type_name_const_str, die); - name = ConstString((std::string(name.AsCString()) + "::" + field.name).c_str()); - field.compiler_type = m_ast.CreateStructType(name, 1, false); - } else { - Type *type = die.ResolveTypeUID(DIERef(field.type)); - if (type) { - field.compiler_type = type->GetFullCompilerType(); - if (all_have_discriminants) - all_have_discriminants = m_ast.TypeHasDiscriminant(field.compiler_type); - } - } - - // Fix up the field's name by taking it from the type if necessary. - if (field.name == nullptr) { - field.name = field.compiler_type.GetTypeName().AsCString(); - } - } - - m_discriminant = save_discr; - - bool compiler_type_was_created = false; - CompilerType compiler_type(&m_ast, - dwarf->m_forward_decl_die_to_clang_type.lookup(die.GetDIE())); - if (!compiler_type) { - compiler_type_was_created = true; - - if (!is_anon_tuple) { - type_name_const_str = FullyQualify(type_name_const_str, die); - } - - if (saw_discr) { - compiler_type = m_ast.CreateEnumType(type_name_const_str, byte_size, - discr_offset, discr_byte_size); - } else if (all_have_discriminants) { - // In this case, the discriminant is easily computed as the 0th - // field of the 0th field. - discriminant_path = std::vector<size_t> { 0 }; - - FindDiscriminantLocation(fields[0].compiler_type, std::move(discriminant_path), - discr_offset, discr_byte_size); - - compiler_type = m_ast.CreateEnumType(type_name_const_str, byte_size, - discr_offset, discr_byte_size); - } else if (!discriminant_path.empty()) { - CompilerType start_type = fields[discriminant_path[0]].compiler_type; - discriminant_path.erase(discriminant_path.begin()); - - FindDiscriminantLocation(start_type, std::move(discriminant_path), - discr_offset, discr_byte_size); - - compiler_type = m_ast.CreateEnumType(type_name_const_str, byte_size, - discr_offset, discr_byte_size); - } else if (is_union) - compiler_type = m_ast.CreateUnionType(type_name_const_str, byte_size); - else if (is_tuple) - compiler_type = m_ast.CreateTupleType(type_name_const_str, byte_size, has_discriminant); - else - compiler_type = m_ast.CreateStructType(type_name_const_str, byte_size, has_discriminant); - } - - type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str, - byte_size, NULL, LLDB_INVALID_UID, - Type::eEncodingIsUID, &decl, compiler_type, - Type::eResolveStateForward)); - - // Now add the fields. - int fieldno = 0; - for (auto &&field : fields) { - if (field.compiler_type) { - ConstString name; - if (is_tuple) { - char buf[32]; - snprintf (buf, sizeof (buf), "%u", fieldno); - ++fieldno; - name = ConstString(buf); - } else { - name = ConstString(field.name); - } - m_ast.AddFieldToStruct(compiler_type, name, field.compiler_type, field.byte_offset, - field.is_default, field.discriminant); - } - } - - for (const CompilerType ¶m_type : template_params) - m_ast.AddTemplateParameter(compiler_type, param_type); - - m_ast.FinishAggregateInitialization(compiler_type); - - // Add our type to the unique type map so we don't - // end up creating many copies of the same type over - // and over in the ASTContext for our module - ast_entry.m_type_sp = type_sp; - ast_entry.m_die = die; - ast_entry.m_declaration = decl; - ast_entry.m_byte_size = byte_size; - dwarf->GetUniqueDWARFASTTypeMap().Insert(type_name_const_str, ast_entry); - - if (compiler_type_was_created) { - // Leave this as a forward declaration until we need - // to know the details of the type. lldb_private::Type - // will automatically call the SymbolFile virtual function - // "SymbolFileDWARF::CompleteType(Type *)" - // When the definition needs to be defined. - dwarf->m_forward_decl_die_to_clang_type[die.GetDIE()] = - compiler_type.GetOpaqueQualType(); - dwarf->m_forward_decl_clang_type_to_die[compiler_type.GetOpaqueQualType()] = - die.GetDIERef(); - } - - return type_sp; -} - -TypeSP DWARFASTParserRust::ParseCLikeEnum(lldb_private::Log *log, const DWARFDIE &die) { - const char *type_name_cstr = NULL; - ConstString type_name_const_str; - SymbolFileDWARF *dwarf = die.GetDWARF(); - CompilerType underlying_type; - - for (auto &&attr : IterableDIEAttrs(die)) { - switch (attr.first) { - case DW_AT_name: - type_name_cstr = attr.second.AsCString(); - type_name_const_str.SetCString(type_name_cstr); - break; - - case DW_AT_type: - if (Type *type = die.ResolveTypeUID(DIERef(attr.second))) { - underlying_type = type->GetFullCompilerType(); - } - break; - } - } - - // See the comment by m_discriminant to understand this; but this - // allows registering two types of the same name when reading a Rust - // enum. - if (die.GetDIERef() == m_discriminant) { - type_name_const_str.Clear(); - } else { - type_name_const_str = FullyQualify(type_name_const_str, die); - } - - std::map<uint64_t, std::string> values; - for (auto &&child_die : IterableDIEChildren(die)) { - if (child_die.Tag() != DW_TAG_enumerator) { - continue; - } - - bool saw_value = false; - uint64_t value; - std::string name; - for (auto &&attr : IterableDIEAttrs(child_die)) { - switch (attr.first) { - case DW_AT_name: - name = attr.second.AsCString(); - break; - case DW_AT_const_value: - saw_value = true; - value = attr.second.Unsigned(); - break; - } - - if (saw_value && !name.empty()) { - values[value] = name; - } else { - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "DWARFASTParserRust::ParseCLikeEnum (die = 0x%8.8x) %s " - "is invalid)", - child_die.GetOffset(), DW_TAG_value_to_name(die.Tag())); - } - } - } - - Declaration decl; - CompilerType compiler_type = m_ast.CreateCLikeEnumType(type_name_const_str, - underlying_type, - std::move(values)); - TypeSP type_sp(new Type(die.GetID(), dwarf, type_name_const_str, 0, NULL, - LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, - compiler_type, Type::eResolveStateFull)); - - return type_sp; -} - -TypeSP DWARFASTParserRust::ParseTypeFromDWARF( - const lldb_private::SymbolContext &sc, const DWARFDIE &die, - lldb_private::Log *log, bool *type_is_new_ptr) { - TypeSP type_sp; - - if (type_is_new_ptr) - *type_is_new_ptr = false; - - if (die) { - SymbolFileDWARF *dwarf = die.GetDWARF(); - if (log) { - dwarf->GetObjectFile()->GetModule()->LogMessage( - log, "DWARFASTParserRust::ParseTypeFromDWARF (die = 0x%8.8x) %s name = " - "'%s')", - die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.GetName()); - } - - Type *type_ptr = dwarf->m_die_to_type.lookup(die.GetDIE()); - TypeList *type_list = dwarf->GetTypeList(); - if (type_ptr == NULL) { - if (type_is_new_ptr) - *type_is_new_ptr = true; - - const dw_tag_t tag = die.Tag(); - - // Set a bit that lets us know that we are currently parsing this - dwarf->m_die_to_type[die.GetDIE()] = DIE_IS_BEING_PARSED; - - switch (tag) { - case DW_TAG_base_type: - case DW_TAG_pointer_type: - case DW_TAG_typedef: - case DW_TAG_template_type_parameter: - case DW_TAG_unspecified_type: - type_sp = ParseSimpleType(log, die); - break; - - case DW_TAG_union_type: - case DW_TAG_structure_type: - type_sp = ParseStructureType(die); - break; - - case DW_TAG_subprogram: - case DW_TAG_subroutine_type: - type_sp = ParseFunctionType(die); - break; - - case DW_TAG_array_type: - type_sp = ParseArrayType(die); - break; - - case DW_TAG_enumeration_type: - type_sp = ParseCLikeEnum(log, die); - break; - - default: - dwarf->GetObjectFile()->GetModule()->ReportError( - "{0x%8.8x}: unhandled type tag 0x%4.4x (%s), " - "please file a bug and attach the file at the " - "start of this error message", - die.GetOffset(), tag, DW_TAG_value_to_name(tag)); - break; - } - - if (type_sp.get()) { - DWARFDIE sc_parent_die = - SymbolFileDWARF::GetParentSymbolContextDIE(die); - dw_tag_t sc_parent_tag = sc_parent_die.Tag(); - - SymbolContextScope *symbol_context_scope = NULL; - if (sc_parent_tag == DW_TAG_compile_unit) { - symbol_context_scope = sc.comp_unit; - } else if (sc.function != NULL && sc_parent_die) { - symbol_context_scope = - sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID()); - if (symbol_context_scope == NULL) - symbol_context_scope = sc.function; - } - - if (symbol_context_scope != NULL) { - type_sp->SetSymbolContextScope(symbol_context_scope); - } - - // We are ready to put this type into the uniqued list up at the module - // level - type_list->Insert(type_sp); - } - dwarf->m_die_to_type[die.GetDIE()] = type_sp.get(); - } else if (type_ptr != DIE_IS_BEING_PARSED) { - type_sp = type_ptr->shared_from_this(); - } - } - return type_sp; -} - -bool DWARFASTParserRust::CompleteTypeFromDWARF(const DWARFDIE &die, - lldb_private::Type *type, - CompilerType &compiler_type) { - // We don't currently use type completion for Rust. - return bool(die); -} - -Function *DWARFASTParserRust::ParseFunctionFromDWARF(CompileUnit &comp_unit, - const DWARFDIE &die) { - DWARFRangeList func_ranges; - const char *name = NULL; - const char *mangled = NULL; - int decl_file = 0; - int decl_line = 0; - int decl_column = 0; - int call_file = 0; - int call_line = 0; - int call_column = 0; - DWARFExpression frame_base(die.GetCU()); - - assert(die.Tag() == DW_TAG_subprogram); - - if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line, - decl_column, call_file, call_line, call_column, - &frame_base)) { - // Union of all ranges in the function DIE (if the function is - // discontiguous) - AddressRange func_range; - lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0); - lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0); - if (lowest_func_addr != LLDB_INVALID_ADDRESS && - lowest_func_addr <= highest_func_addr) { - ModuleSP module_sp(die.GetModule()); - func_range.GetBaseAddress().ResolveAddressUsingFileSections( - lowest_func_addr, module_sp->GetSectionList()); - if (func_range.GetBaseAddress().IsValid()) - func_range.SetByteSize(highest_func_addr - lowest_func_addr); - } - - if (func_range.GetBaseAddress().IsValid()) { - Mangled func_name; - func_name.SetValue(ConstString(name), false); - - FunctionSP func_sp; - std::unique_ptr<Declaration> decl_ap; - if (decl_file != 0 || decl_line != 0 || decl_column != 0) - decl_ap.reset(new Declaration( - comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file), - decl_line, decl_column)); - - SymbolFileDWARF *dwarf = die.GetDWARF(); - // Supply the type _only_ if it has already been parsed - Type *func_type = dwarf->m_die_to_type.lookup(die.GetDIE()); - - assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED); - - if (dwarf->FixupAddress(func_range.GetBaseAddress())) { - const user_id_t func_user_id = die.GetID(); - func_sp.reset(new Function(&comp_unit, - func_user_id, // UserID is the DIE offset - func_user_id, func_name, func_type, - func_range)); // first address range - - if (func_sp.get() != NULL) { - if (frame_base.IsValid()) - func_sp->GetFrameBaseExpression() = frame_base; - comp_unit.AddFunction(func_sp); - return func_sp.get(); - } - } - } - } - return NULL; -} - -lldb_private::CompilerDeclContext -DWARFASTParserRust::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) { - auto iter = m_decl_contexts.find(die.GetDIE()); - if (iter != m_decl_contexts.end()) { - return iter->second; - } - - CompilerDeclContext result; - switch (die.Tag()) { - case DW_TAG_compile_unit: - result = m_ast.GetTranslationUnitDecl(); - break; - - case DW_TAG_union_type: - case DW_TAG_structure_type: - case DW_TAG_namespace: { - const char *name = die.GetName(); - if (name) { - CompilerDeclContext parent = GetDeclContextContainingUIDFromDWARF(die); - result = m_ast.GetNamespaceDecl(parent, ConstString(name)); - } - break; - } - - case DW_TAG_lexical_block: - case DW_TAG_subprogram: - result = GetDeclContextContainingUIDFromDWARF(die); - break; - - default: - break; - } - - if (result) { - m_decl_contexts[die.GetDIE()] = result; - m_decl_contexts_to_die.emplace(result, die); - } - - return result; -} - -lldb_private::CompilerDeclContext -DWARFASTParserRust::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) { - DWARFDIE decl_ctx_die; - - DWARFDebugInfoEntry *ptr = die.GetDIE(); - auto iter = m_reparent_map.find(ptr); - if (iter != m_reparent_map.end()) { - decl_ctx_die = iter->second; - } else { - SymbolFileDWARF *dwarf = die.GetDWARF(); - decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die); - } - return GetDeclContextForUIDFromDWARF(decl_ctx_die); -} - -lldb_private::CompilerDecl -DWARFASTParserRust::GetDeclForUIDFromDWARF(const DWARFDIE &die) { - auto iter = m_decls.find(die.GetDIE()); - if (iter != m_decls.end()) { - return iter->second; - } - - CompilerDecl result; - if (die.Tag() == DW_TAG_variable || die.Tag() == DW_TAG_constant) { - const char *name = die.GetName(); - if (name) { - const char *mangled = die.GetMangledName(); - CompilerDeclContext parent = GetDeclContextContainingUIDFromDWARF(die); - result = m_ast.GetDecl(parent, ConstString(name), ConstString(mangled)); - - if (result) { - m_decls[die.GetDIE()] = result; - } - } - } - - return result; -} - -std::vector<DWARFDIE> -DWARFASTParserRust::GetDIEForDeclContext(lldb_private::CompilerDeclContext decl_context) { - std::vector<DWARFDIE> result; - for (auto it = m_decl_contexts_to_die.find(decl_context); - it != m_decl_contexts_to_die.end(); - ++it) - result.push_back(it->second); - return result; -}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserRust.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserRust.h deleted file mode 100644 index 68c8ad2..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserRust.h +++ /dev/null
@@ -1,135 +0,0 @@ -//===-- DWARFASTParserRust.h --------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef SymbolFileDWARF_DWARFASTParserRust_h_ -#define SymbolFileDWARF_DWARFASTParserRust_h_ - -// C Includes -// C++ Includes -// Other libraries and framework includes -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallVector.h" -#include "lldb/Utility/ConstString.h" - -// Project includes -#include "DWARFASTParser.h" -#include "DWARFDIE.h" -#include "DWARFDebugInfoEntry.h" -#include "DWARFDefines.h" -#include "DIERef.h" -#include "lldb/Core/PluginInterface.h" -#include "lldb/Symbol/RustASTContext.h" -#include "DWARFFormValue.h" - -class DWARFDebugInfoEntry; -class DWARFDIECollection; - -class DWARFASTParserRust : public DWARFASTParser { -public: - DWARFASTParserRust(lldb_private::RustASTContext &ast) - : m_ast(ast) - { - } - - lldb::TypeSP ParseTypeFromDWARF(const lldb_private::SymbolContext &sc, - const DWARFDIE &die, lldb_private::Log *log, - bool *type_is_new_ptr) override; - - lldb_private::Function * - ParseFunctionFromDWARF(lldb_private::CompileUnit &comp_unit, - const DWARFDIE &die) override; - - bool CompleteTypeFromDWARF(const DWARFDIE &die, lldb_private::Type *type, - lldb_private::CompilerType &rust_type) override; - - lldb_private::CompilerDeclContext - GetDeclContextForUIDFromDWARF(const DWARFDIE &die) override; - - lldb_private::CompilerDeclContext - GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) override; - - lldb_private::CompilerDecl GetDeclForUIDFromDWARF(const DWARFDIE &die) override; - - std::vector<DWARFDIE> GetDIEForDeclContext(lldb_private::CompilerDeclContext decl_context) - override; - -private: - lldb::TypeSP ParseSimpleType(lldb_private::Log *log, const DWARFDIE &die); - lldb::TypeSP ParseArrayType(const DWARFDIE &die); - lldb::TypeSP ParseFunctionType(const DWARFDIE &die); - lldb::TypeSP ParseStructureType(const DWARFDIE &die); - lldb::TypeSP ParseCLikeEnum(lldb_private::Log *log, const DWARFDIE &die); - lldb_private::ConstString FullyQualify(const lldb_private::ConstString &name, - const DWARFDIE &die); - - std::vector<size_t> ParseDiscriminantPath(const char **in_str); - void FindDiscriminantLocation(lldb_private::CompilerType type, - std::vector<size_t> &&path, - uint64_t &offset, uint64_t &byte_size); - bool IsPossibleEnumVariant(const DWARFDIE &die); - - struct Field { - Field() - : is_discriminant(false), - is_elided(false), - name(nullptr), - byte_offset(-1), - is_default(false), - discriminant(0) - { - } - - bool is_discriminant; - // True if this field is the field that was elided by the non-zero - // optimization. - bool is_elided; - const char *name; - DWARFFormValue type; - lldb_private::CompilerType compiler_type; - uint32_t byte_offset; - - // These are used if this is a member of an enum type. - bool is_default; - uint64_t discriminant; - }; - - std::vector<Field> ParseFields(const DWARFDIE &die, - std::vector<size_t> &discriminant_path, - bool &is_tuple, - uint64_t &discr_offset, uint64_t &discr_byte_size, - bool &saw_discr, - std::vector<lldb_private::CompilerType> &template_params); - - lldb_private::RustASTContext &m_ast; - - // The Rust compiler will emit a DW_TAG_enumeration_type for the - // type of an enum discriminant. However, this type will have the - // same name as the enum type itself. So, when we expect to read - // the enumeration type, we set this member, and ParseCLikeEnum - // avoids giving the name to the enumeration type. - DIERef m_discriminant; - - // When reading a Rust enum, we set this temporarily when reading - // the field types, so that they can get the correct scoping. - DWARFDIE m_rust_enum_die; - - // The Rust compiler emits the variants of an enum type as siblings - // to the DW_TAG_union_type that (currently) represents the enum. - // However, conceptually these ought to be nested. This map tracks - // DIEs involved in this situation so that the enum variants can be - // given correctly-scoped names. - llvm::DenseMap<const DWARFDebugInfoEntry *, DWARFDIE> m_reparent_map; - - llvm::DenseMap<const DWARFDebugInfoEntry *, lldb_private::CompilerDeclContext> m_decl_contexts; - llvm::DenseMap<const DWARFDebugInfoEntry *, lldb_private::CompilerDecl> m_decls; - std::multimap<lldb_private::CompilerDeclContext, const DWARFDIE> m_decl_contexts_to_die; -}; - -#endif // SymbolFileDWARF_DWARFASTParserRust_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.cpp index d78b9ab..6128163 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.cpp
@@ -1,9 +1,8 @@ //===-- DWARFAbbreviationDeclaration.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,6 +11,8 @@ #include "lldb/Core/dwarf.h" #include "lldb/Utility/Stream.h" +#include "llvm/Object/Error.h" + #include "DWARFFormValue.h" using namespace lldb_private; @@ -24,57 +25,46 @@ : m_code(InvalidCode), m_tag(tag), m_has_children(has_children), m_attributes() {} -bool DWARFAbbreviationDeclaration::Extract(const DWARFDataExtractor &data, - lldb::offset_t *offset_ptr) { - return Extract(data, offset_ptr, data.GetULEB128(offset_ptr)); -} +llvm::Expected<DWARFEnumState> +DWARFAbbreviationDeclaration::extract(const DWARFDataExtractor &data, + lldb::offset_t *offset_ptr) { + m_code = data.GetULEB128(offset_ptr); + if (m_code == 0) + return DWARFEnumState::Complete; -bool DWARFAbbreviationDeclaration::Extract(const DWARFDataExtractor &data, - lldb::offset_t *offset_ptr, - dw_uleb128_t code) { - m_code = code; m_attributes.clear(); - if (m_code) { - m_tag = data.GetULEB128(offset_ptr); - m_has_children = data.GetU8(offset_ptr); + m_tag = data.GetULEB128(offset_ptr); + if (m_tag == DW_TAG_null) + return llvm::make_error<llvm::object::GenericBinaryError>( + "abbrev decl requires non-null tag."); - while (data.ValidOffset(*offset_ptr)) { - dw_attr_t attr = data.GetULEB128(offset_ptr); - dw_form_t form = data.GetULEB128(offset_ptr); - DWARFFormValue::ValueType val; + m_has_children = data.GetU8(offset_ptr); - if (form == DW_FORM_implicit_const) - val.value.sval = data.GetULEB128(offset_ptr); + while (data.ValidOffset(*offset_ptr)) { + dw_attr_t attr = data.GetULEB128(offset_ptr); + dw_form_t form = data.GetULEB128(offset_ptr); - if (attr && form) - m_attributes.push_back(DWARFAttribute(attr, form, val)); - else - break; - } + // This is the last attribute for this abbrev decl, but there may still be + // more abbrev decls, so return MoreItems to indicate to the caller that + // they should call this function again. + if (!attr && !form) + return DWARFEnumState::MoreItems; - return m_tag != 0; - } else { - m_tag = 0; - m_has_children = 0; + if (!attr || !form) + return llvm::make_error<llvm::object::GenericBinaryError>( + "malformed abbreviation declaration attribute"); + + DWARFFormValue::ValueType val; + + if (form == DW_FORM_implicit_const) + val.value.sval = data.GetULEB128(offset_ptr); + + m_attributes.push_back(DWARFAttribute(attr, form, val)); } - return false; -} - -void DWARFAbbreviationDeclaration::Dump(Stream *s) const { - s->Printf("Debug Abbreviation Declaration: code = 0x%4.4x, tag = %s, " - "has_children = %s\n", - m_code, DW_TAG_value_to_name(m_tag), - DW_CHILDREN_value_to_name(m_has_children)); - - DWARFAttribute::const_iterator pos; - - for (pos = m_attributes.begin(); pos != m_attributes.end(); ++pos) - s->Printf(" attr = %s, form = %s\n", - DW_AT_value_to_name(pos->get_attr()), - DW_FORM_value_to_name(pos->get_form())); - - s->Printf("\n"); + return llvm::make_error<llvm::object::GenericBinaryError>( + "abbreviation declaration attribute list not terminated with a null " + "entry"); } bool DWARFAbbreviationDeclaration::IsValid() { @@ -95,5 +85,5 @@ bool DWARFAbbreviationDeclaration:: operator==(const DWARFAbbreviationDeclaration &rhs) const { return Tag() == rhs.Tag() && HasChildren() == rhs.HasChildren() && - Attributes() == rhs.Attributes(); + m_attributes == rhs.m_attributes; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.h index afce525..c0cf882 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAbbreviationDeclaration.h
@@ -1,9 +1,8 @@ //===-- DWARFAbbreviationDeclaration.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,7 +10,9 @@ #define liblldb_DWARFAbbreviationDeclaration_h_ #include "DWARFAttribute.h" +#include "DWARFDefines.h" #include "SymbolFileDWARF.h" +#include "llvm/Support/Error.h" class DWARFAbbreviationDeclaration { public: @@ -20,18 +21,12 @@ // For hand crafting an abbreviation declaration DWARFAbbreviationDeclaration(dw_tag_t tag, uint8_t has_children); - void AddAttribute(const DWARFAttribute &attr) { - m_attributes.push_back(attr); - } dw_uleb128_t Code() const { return m_code; } void SetCode(dw_uleb128_t code) { m_code = code; } dw_tag_t Tag() const { return m_tag; } bool HasChildren() const { return m_has_children; } size_t NumAttributes() const { return m_attributes.size(); } - dw_attr_t GetAttrByIndex(uint32_t idx) const { - return m_attributes.size() > idx ? m_attributes[idx].get_attr() : 0; - } dw_form_t GetFormByIndex(uint32_t idx) const { return m_attributes.size() > idx ? m_attributes[idx].get_form() : 0; } @@ -45,14 +40,20 @@ return m_attributes[idx].get_form(); } uint32_t FindAttributeIndex(dw_attr_t attr) const; - bool Extract(const lldb_private::DWARFDataExtractor &data, - lldb::offset_t *offset_ptr); - bool Extract(const lldb_private::DWARFDataExtractor &data, - lldb::offset_t *offset_ptr, dw_uleb128_t code); + + /// Extract one abbreviation declaration and all of its associated attributes. + /// Possible return values: + /// DWARFEnumState::Complete - the extraction completed successfully. This + /// was the last abbrev decl in a sequence, and the user should not call + /// this function again. + /// DWARFEnumState::MoreItems - the extraction completed successfully. The + /// user should call this function again to retrieve the next decl. + /// llvm::Error - A parsing error occurred. The debug info is malformed. + llvm::Expected<lldb_private::DWARFEnumState> + extract(const lldb_private::DWARFDataExtractor &data, + lldb::offset_t *offset_ptr); bool IsValid(); - void Dump(lldb_private::Stream *s) const; bool operator==(const DWARFAbbreviationDeclaration &rhs) const; - const DWARFAttribute::collection &Attributes() const { return m_attributes; } protected: dw_uleb128_t m_code;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.cpp index dd830eb..b3594a4 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.cpp
@@ -1,9 +1,8 @@ //===-- DWARFAttribute.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,41 +32,27 @@ m_infos.push_back(attr_value); } -bool DWARFAttributes::ContainsAttribute(dw_attr_t attr) const { - return FindAttributeIndex(attr) != UINT32_MAX; -} - -bool DWARFAttributes::RemoveAttribute(dw_attr_t attr) { - uint32_t attr_index = FindAttributeIndex(attr); - if (attr_index != UINT32_MAX) { - m_infos.erase(m_infos.begin() + attr_index); - return true; - } - return false; -} - bool DWARFAttributes::ExtractFormValueAtIndex( uint32_t i, DWARFFormValue &form_value) const { const DWARFUnit *cu = CompileUnitAtIndex(i); - form_value.SetCompileUnit(cu); + form_value.SetUnit(cu); form_value.SetForm(FormAtIndex(i)); lldb::offset_t offset = DIEOffsetAtIndex(i); return form_value.ExtractValue(cu->GetData(), &offset); } -uint64_t DWARFAttributes::FormValueAsUnsigned(dw_attr_t attr, - uint64_t fail_value) const { +DWARFDIE +DWARFAttributes::FormValueAsReference(dw_attr_t attr) const { const uint32_t attr_idx = FindAttributeIndex(attr); if (attr_idx != UINT32_MAX) - return FormValueAsUnsignedAtIndex(attr_idx, fail_value); - return fail_value; + return FormValueAsReferenceAtIndex(attr_idx); + return {}; } -uint64_t -DWARFAttributes::FormValueAsUnsignedAtIndex(uint32_t i, - uint64_t fail_value) const { +DWARFDIE +DWARFAttributes::FormValueAsReferenceAtIndex(uint32_t i) const { DWARFFormValue form_value; if (ExtractFormValueAtIndex(i, form_value)) return form_value.Reference(); - return fail_value; + return {}; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.h index 2399861..58427b1 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFAttribute.h
@@ -1,9 +1,8 @@ //===-- DWARFAttribute.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -27,8 +26,6 @@ m_attr = attr; m_form = form; } - void set_attr(dw_attr_t attr) { m_attr = attr; } - void set_form(dw_form_t form) { m_form = form; } dw_attr_t get_attr() const { return m_attr; } dw_form_t get_form() const { return m_form; } void get(dw_attr_t &attr, dw_form_t &form, @@ -68,11 +65,9 @@ } dw_attr_t FormAtIndex(uint32_t i) const { return m_infos[i].attr.get_form(); } bool ExtractFormValueAtIndex(uint32_t i, DWARFFormValue &form_value) const; - uint64_t FormValueAsUnsignedAtIndex(uint32_t i, uint64_t fail_value) const; - uint64_t FormValueAsUnsigned(dw_attr_t attr, uint64_t fail_value) const; + DWARFDIE FormValueAsReferenceAtIndex(uint32_t i) const; + DWARFDIE FormValueAsReference(dw_attr_t attr) const; uint32_t FindAttributeIndex(dw_attr_t attr) const; - bool ContainsAttribute(dw_attr_t attr) const; - bool RemoveAttribute(dw_attr_t attr); void Clear() { m_infos.clear(); } size_t Size() const { return m_infos.size(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.cpp index 077de96..96adb72 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.cpp
@@ -1,9 +1,8 @@ //===-- DWARFBaseDIE.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,14 +17,12 @@ using namespace lldb_private; -DIERef DWARFBaseDIE::GetDIERef() const { +llvm::Optional<DIERef> DWARFBaseDIE::GetDIERef() const { if (!IsValid()) - return DIERef(); + return llvm::None; - dw_offset_t cu_offset = m_cu->GetOffset(); - if (m_cu->GetBaseObjOffset() != DW_INVALID_OFFSET) - cu_offset = m_cu->GetBaseObjOffset(); - return DIERef(cu_offset, m_die->GetOffset()); + return DIERef(m_cu->GetSymbolFileDWARF().GetDwoNum(), m_cu->GetDebugSection(), + m_die->GetOffset()); } dw_tag_t DWARFBaseDIE::Tag() const { @@ -42,8 +39,7 @@ const char *DWARFBaseDIE::GetAttributeValueAsString(const dw_attr_t attr, const char *fail_value) const { if (IsValid()) - return m_die->GetAttributeValueAsString(GetDWARF(), GetCU(), attr, - fail_value); + return m_die->GetAttributeValueAsString(GetCU(), attr, fail_value); else return fail_value; } @@ -51,26 +47,7 @@ uint64_t DWARFBaseDIE::GetAttributeValueAsUnsigned(const dw_attr_t attr, uint64_t fail_value) const { if (IsValid()) - return m_die->GetAttributeValueAsUnsigned(GetDWARF(), GetCU(), attr, - fail_value); - else - return fail_value; -} - -int64_t DWARFBaseDIE::GetAttributeValueAsSigned(const dw_attr_t attr, - int64_t fail_value) const { - if (IsValid()) - return m_die->GetAttributeValueAsSigned(GetDWARF(), GetCU(), attr, - fail_value); - else - return fail_value; -} - -uint64_t DWARFBaseDIE::GetAttributeValueAsReference(const dw_attr_t attr, - uint64_t fail_value) const { - if (IsValid()) - return m_die->GetAttributeValueAsReference(GetDWARF(), GetCU(), attr, - fail_value); + return m_die->GetAttributeValueAsUnsigned(GetCU(), attr, fail_value); else return fail_value; } @@ -78,19 +55,20 @@ uint64_t DWARFBaseDIE::GetAttributeValueAsAddress(const dw_attr_t attr, uint64_t fail_value) const { if (IsValid()) - return m_die->GetAttributeValueAsAddress(GetDWARF(), GetCU(), attr, - fail_value); + return m_die->GetAttributeValueAsAddress(GetCU(), attr, fail_value); else return fail_value; } lldb::user_id_t DWARFBaseDIE::GetID() const { - return GetDIERef().GetUID(GetDWARF()); + if (IsValid()) + return GetDWARF()->GetUID(*this); + return LLDB_INVALID_UID; } const char *DWARFBaseDIE::GetName() const { if (IsValid()) - return m_die->GetName(GetDWARF(), m_cu); + return m_die->GetName(m_cu); else return nullptr; } @@ -110,13 +88,6 @@ return lldb::ModuleSP(); } -lldb_private::CompileUnit *DWARFBaseDIE::GetLLDBCompileUnit() const { - if (IsValid()) - return GetDWARF()->GetCompUnitForDWARFCompUnit(GetCU()); - else - return nullptr; -} - dw_offset_t DWARFBaseDIE::GetOffset() const { if (IsValid()) return m_die->GetOffset(); @@ -124,16 +95,9 @@ return DW_INVALID_OFFSET; } -dw_offset_t DWARFBaseDIE::GetCompileUnitRelativeOffset() const { - if (IsValid()) - return m_die->GetOffset() - m_cu->GetOffset(); - else - return DW_INVALID_OFFSET; -} - SymbolFileDWARF *DWARFBaseDIE::GetDWARF() const { if (m_cu) - return m_cu->GetSymbolFileDWARF(); + return &m_cu->GetSymbolFileDWARF(); else return nullptr; } @@ -163,21 +127,13 @@ size_t DWARFBaseDIE::GetAttributes(DWARFAttributes &attributes, uint32_t depth) const { - if (IsValid()) { - return m_die->GetAttributes(m_cu, m_cu->GetFixedFormSizes(), attributes, - depth); - } + if (IsValid()) + return m_die->GetAttributes(m_cu, attributes, depth); if (depth == 0) attributes.Clear(); return 0; } -void DWARFBaseDIE::Dump(lldb_private::Stream *s, - const uint32_t recurse_depth) const { - if (s && IsValid()) - m_die->Dump(GetDWARF(), GetCU(), *s, recurse_depth); -} - bool operator==(const DWARFBaseDIE &lhs, const DWARFBaseDIE &rhs) { return lhs.GetDIE() == rhs.GetDIE() && lhs.GetCU() == rhs.GetCU(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.h index 2163a02..0058043 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFBaseDIE.h
@@ -1,9 +1,8 @@ //===-- DWARFBaseDIE.h -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,13 +12,12 @@ #include "lldb/Core/dwarf.h" #include "lldb/lldb-types.h" -struct DIERef; +class DIERef; class DWARFASTParser; class DWARFAttributes; class DWARFUnit; class DWARFDebugInfoEntry; class DWARFDeclContext; -class DWARFDIECollection; class SymbolFileDWARF; class DWARFBaseDIE { @@ -39,9 +37,7 @@ : m_cu(const_cast<DWARFUnit *>(cu)), m_die(const_cast<DWARFDebugInfoEntry *>(die)) {} - //---------------------------------------------------------------------- // Tests - //---------------------------------------------------------------------- explicit operator bool() const { return IsValid(); } bool IsValid() const { return m_cu && m_die; } @@ -50,16 +46,14 @@ bool Supports_DW_AT_APPLE_objc_complete_type() const; - //---------------------------------------------------------------------- // Accessors - //---------------------------------------------------------------------- SymbolFileDWARF *GetDWARF() const; DWARFUnit *GetCU() const { return m_cu; } DWARFDebugInfoEntry *GetDIE() const { return m_die; } - DIERef GetDIERef() const; + llvm::Optional<DIERef> GetDIERef() const; lldb_private::TypeSystem *GetTypeSystem() const; @@ -79,33 +73,25 @@ m_die = nullptr; } - //---------------------------------------------------------------------- // Get the data that contains the attribute values for this DIE. Support // for .debug_types means that any DIE can have its data either in the // .debug_info or the .debug_types section; this method will return the // correct section data. // // Clients must validate that this object is valid before calling this. - //---------------------------------------------------------------------- const lldb_private::DWARFDataExtractor &GetData() const; - //---------------------------------------------------------------------- // Accessing information about a DIE - //---------------------------------------------------------------------- dw_tag_t Tag() const; const char *GetTagAsCString() const; dw_offset_t GetOffset() const; - dw_offset_t GetCompileUnitRelativeOffset() const; - - //---------------------------------------------------------------------- // Get the LLDB user ID for this DIE. This is often just the DIE offset, // but it might have a SymbolFileDWARF::GetID() in the high 32 bits if // we are doing Darwin DWARF in .o file, or DWARF stand alone debug // info. - //---------------------------------------------------------------------- lldb::user_id_t GetID() const; const char *GetName() const; @@ -114,38 +100,22 @@ lldb::ModuleSP GetModule() const; - lldb_private::CompileUnit *GetLLDBCompileUnit() const; - - //---------------------------------------------------------------------- // Getting attribute values from the DIE. // // GetAttributeValueAsXXX() functions should only be used if you are // looking for one or two attributes on a DIE. If you are trying to // parse all attributes, use GetAttributes (...) instead - //---------------------------------------------------------------------- const char *GetAttributeValueAsString(const dw_attr_t attr, const char *fail_value) const; uint64_t GetAttributeValueAsUnsigned(const dw_attr_t attr, uint64_t fail_value) const; - int64_t GetAttributeValueAsSigned(const dw_attr_t attr, - int64_t fail_value) const; - - uint64_t GetAttributeValueAsReference(const dw_attr_t attr, - uint64_t fail_value) const; - uint64_t GetAttributeValueAsAddress(const dw_attr_t attr, uint64_t fail_value) const; size_t GetAttributes(DWARFAttributes &attributes, uint32_t depth = 0) const; - //---------------------------------------------------------------------- - // Pretty printing - //---------------------------------------------------------------------- - - void Dump(lldb_private::Stream *s, const uint32_t recurse_depth) const; - protected: DWARFUnit *m_cu; DWARFDebugInfoEntry *m_die;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp index b9a7231..718f053 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp
@@ -1,98 +1,115 @@ //===-- DWARFCompileUnit.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DWARFCompileUnit.h" +#include "DWARFDebugAranges.h" +#include "SymbolFileDWARFDebugMap.h" -#include "SymbolFileDWARF.h" +#include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/LineTable.h" #include "lldb/Utility/Stream.h" using namespace lldb; using namespace lldb_private; -extern int g_verbose; - -DWARFCompileUnit::DWARFCompileUnit(SymbolFileDWARF *dwarf2Data) - : DWARFUnit(dwarf2Data) {} - -DWARFUnitSP DWARFCompileUnit::Extract(SymbolFileDWARF *dwarf2Data, - const DWARFDataExtractor &debug_info, - lldb::offset_t *offset_ptr) { - // std::make_shared would require the ctor to be public. - std::shared_ptr<DWARFCompileUnit> cu_sp(new DWARFCompileUnit(dwarf2Data)); - - cu_sp->m_offset = *offset_ptr; - - if (debug_info.ValidOffset(*offset_ptr)) { - dw_offset_t abbr_offset; - const DWARFDebugAbbrev *abbr = dwarf2Data->DebugAbbrev(); - cu_sp->m_length = debug_info.GetDWARFInitialLength(offset_ptr); - cu_sp->m_is_dwarf64 = debug_info.IsDWARF64(); - cu_sp->m_version = debug_info.GetU16(offset_ptr); - - if (cu_sp->m_version == 5) { - cu_sp->m_unit_type = debug_info.GetU8(offset_ptr); - cu_sp->m_addr_size = debug_info.GetU8(offset_ptr); - abbr_offset = debug_info.GetDWARFOffset(offset_ptr); - - if (cu_sp->m_unit_type == llvm::dwarf::DW_UT_skeleton) - cu_sp->m_dwo_id = debug_info.GetU64(offset_ptr); - } else { - abbr_offset = debug_info.GetDWARFOffset(offset_ptr); - cu_sp->m_addr_size = debug_info.GetU8(offset_ptr); - } - - bool length_OK = - debug_info.ValidOffset(cu_sp->GetNextCompileUnitOffset() - 1); - bool version_OK = SymbolFileDWARF::SupportedVersion(cu_sp->m_version); - bool abbr_offset_OK = - dwarf2Data->get_debug_abbrev_data().ValidOffset(abbr_offset); - bool addr_size_OK = (cu_sp->m_addr_size == 4) || (cu_sp->m_addr_size == 8); - - if (length_OK && version_OK && addr_size_OK && abbr_offset_OK && - abbr != NULL) { - cu_sp->m_abbrevs = abbr->GetAbbreviationDeclarationSet(abbr_offset); - return cu_sp; - } - - // reset the offset to where we tried to parse from if anything went wrong - *offset_ptr = cu_sp->m_offset; - } - - return nullptr; -} - void DWARFCompileUnit::Dump(Stream *s) const { s->Printf("0x%8.8x: Compile Unit: length = 0x%8.8x, version = 0x%4.4x, " "abbr_offset = 0x%8.8x, addr_size = 0x%2.2x (next CU at " "{0x%8.8x})\n", - m_offset, m_length, m_version, GetAbbrevOffset(), m_addr_size, - GetNextCompileUnitOffset()); + GetOffset(), GetLength(), GetVersion(), GetAbbrevOffset(), + GetAddressByteSize(), GetNextUnitOffset()); } -uint32_t DWARFCompileUnit::GetHeaderByteSize() const { - if (m_version < 5) - return m_is_dwarf64 ? 23 : 11; +void DWARFCompileUnit::BuildAddressRangeTable( + DWARFDebugAranges *debug_aranges) { + // This function is usually called if there in no .debug_aranges section in + // order to produce a compile unit level set of address ranges that is + // accurate. - switch (m_unit_type) { - case llvm::dwarf::DW_UT_compile: - case llvm::dwarf::DW_UT_partial: - return 12; - case llvm::dwarf::DW_UT_skeleton: - case llvm::dwarf::DW_UT_split_compile: - return 20; - case llvm::dwarf::DW_UT_type: - case llvm::dwarf::DW_UT_split_type: - return 24; + size_t num_debug_aranges = debug_aranges->GetNumRanges(); + + // First get the compile unit DIE only and check if it has a DW_AT_ranges + const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly(); + + const dw_offset_t cu_offset = GetOffset(); + if (die) { + DWARFRangeList ranges; + const size_t num_ranges = + die->GetAttributeAddressRanges(this, ranges, false); + if (num_ranges > 0) { + // This compile unit has DW_AT_ranges, assume this is correct if it is + // present since clang no longer makes .debug_aranges by default and it + // emits DW_AT_ranges for DW_TAG_compile_units. GCC also does this with + // recent GCC builds. + for (size_t i = 0; i < num_ranges; ++i) { + const DWARFRangeList::Entry &range = ranges.GetEntryRef(i); + debug_aranges->AppendRange(cu_offset, range.GetRangeBase(), + range.GetRangeEnd()); + } + + return; // We got all of our ranges from the DW_AT_ranges attribute + } } - llvm_unreachable("invalid UnitType."); -} + // We don't have a DW_AT_ranges attribute, so we need to parse the DWARF -const lldb_private::DWARFDataExtractor &DWARFCompileUnit::GetData() const { - return m_dwarf->get_debug_info_data(); + // If the DIEs weren't parsed, then we don't want all dies for all compile + // units to stay loaded when they weren't needed. So we can end up parsing + // the DWARF and then throwing them all away to keep memory usage down. + ScopedExtractDIEs clear_dies(ExtractDIEsScoped()); + + die = DIEPtr(); + if (die) + die->BuildAddressRangeTable(this, debug_aranges); + + if (debug_aranges->GetNumRanges() == num_debug_aranges) { + // We got nothing from the functions, maybe we have a line tables only + // situation. Check the line tables and build the arange table from this. + SymbolContext sc; + sc.comp_unit = m_dwarf.GetCompUnitForDWARFCompUnit(*this); + if (sc.comp_unit) { + SymbolFileDWARFDebugMap *debug_map_sym_file = + m_dwarf.GetDebugMapSymfile(); + if (debug_map_sym_file == nullptr) { + if (LineTable *line_table = sc.comp_unit->GetLineTable()) { + LineTable::FileAddressRanges file_ranges; + const bool append = true; + const size_t num_ranges = + line_table->GetContiguousFileAddressRanges(file_ranges, append); + for (uint32_t idx = 0; idx < num_ranges; ++idx) { + const LineTable::FileAddressRanges::Entry &range = + file_ranges.GetEntryRef(idx); + debug_aranges->AppendRange(cu_offset, range.GetRangeBase(), + range.GetRangeEnd()); + } + } + } else + debug_map_sym_file->AddOSOARanges(&m_dwarf, debug_aranges); + } + } + + if (debug_aranges->GetNumRanges() == num_debug_aranges) { + // We got nothing from the functions, maybe we have a line tables only + // situation. Check the line tables and build the arange table from this. + SymbolContext sc; + sc.comp_unit = m_dwarf.GetCompUnitForDWARFCompUnit(*this); + if (sc.comp_unit) { + if (LineTable *line_table = sc.comp_unit->GetLineTable()) { + LineTable::FileAddressRanges file_ranges; + const bool append = true; + const size_t num_ranges = + line_table->GetContiguousFileAddressRanges(file_ranges, append); + for (uint32_t idx = 0; idx < num_ranges; ++idx) { + const LineTable::FileAddressRanges::Entry &range = + file_ranges.GetEntryRef(idx); + debug_aranges->AppendRange(GetOffset(), range.GetRangeBase(), + range.GetRangeEnd()); + } + } + } + } }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h index b92a155..75647db 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h
@@ -1,9 +1,8 @@ //===-- DWARFCompileUnit.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,35 +10,26 @@ #define SymbolFileDWARF_DWARFCompileUnit_h_ #include "DWARFUnit.h" +#include "llvm/Support/Error.h" class DWARFCompileUnit : public DWARFUnit { public: - static DWARFUnitSP Extract(SymbolFileDWARF *dwarf2Data, - const lldb_private::DWARFDataExtractor &debug_info, - lldb::offset_t *offset_ptr); + void BuildAddressRangeTable(DWARFDebugAranges *debug_aranges) override; + void Dump(lldb_private::Stream *s) const override; - //------------------------------------------------------------------ - /// Get the data that contains the DIE information for this unit. - /// - /// @return - /// The correct data (.debug_types for DWARF 4 and earlier, and - /// .debug_info for DWARF 5 and later) for the DIE information in - /// this unit. - //------------------------------------------------------------------ - const lldb_private::DWARFDataExtractor &GetData() const override; - - //------------------------------------------------------------------ - /// Get the size in bytes of the header. - /// - /// @return - /// Byte size of the compile unit header - //------------------------------------------------------------------ - uint32_t GetHeaderByteSize() const override; + static bool classof(const DWARFUnit *unit) { return !unit->IsTypeUnit(); } private: - DWARFCompileUnit(SymbolFileDWARF *dwarf2Data); + DWARFCompileUnit(SymbolFileDWARF &dwarf, lldb::user_id_t uid, + const DWARFUnitHeader &header, + const DWARFAbbreviationDeclarationSet &abbrevs, + DIERef::Section section) + : DWARFUnit(dwarf, uid, header, abbrevs, section) {} + DISALLOW_COPY_AND_ASSIGN(DWARFCompileUnit); + + friend class DWARFUnit; }; #endif // SymbolFileDWARF_DWARFCompileUnit_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFContext.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFContext.cpp new file mode 100644 index 0000000..eb307ce --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFContext.cpp
@@ -0,0 +1,138 @@ +//===-- DWARFContext.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 "DWARFContext.h" + +#include "lldb/Core/Section.h" + +using namespace lldb; +using namespace lldb_private; + +static DWARFDataExtractor LoadSection(SectionList *section_list, + SectionType section_type) { + if (!section_list) + return DWARFDataExtractor(); + + auto section_sp = section_list->FindSectionByType(section_type, true); + if (!section_sp) + return DWARFDataExtractor(); + + DWARFDataExtractor data; + section_sp->GetSectionData(data); + return data; +} + +const DWARFDataExtractor & +DWARFContext::LoadOrGetSection(SectionType main_section_type, + llvm::Optional<SectionType> dwo_section_type, + SectionData &data) { + llvm::call_once(data.flag, [&] { + if (dwo_section_type && isDwo()) + data.data = LoadSection(m_dwo_section_list, *dwo_section_type); + else + data.data = LoadSection(m_main_section_list, main_section_type); + }); + return data.data; +} + +const DWARFDataExtractor &DWARFContext::getOrLoadAbbrevData() { + return LoadOrGetSection(eSectionTypeDWARFDebugAbbrev, + eSectionTypeDWARFDebugAbbrevDwo, m_data_debug_abbrev); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadArangesData() { + return LoadOrGetSection(eSectionTypeDWARFDebugAranges, llvm::None, + m_data_debug_aranges); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadAddrData() { + return LoadOrGetSection(eSectionTypeDWARFDebugAddr, llvm::None, + m_data_debug_addr); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadDebugInfoData() { + return LoadOrGetSection(eSectionTypeDWARFDebugInfo, + eSectionTypeDWARFDebugInfoDwo, m_data_debug_info); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadLineData() { + return LoadOrGetSection(eSectionTypeDWARFDebugLine, llvm::None, + m_data_debug_line); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadLineStrData() { + return LoadOrGetSection(eSectionTypeDWARFDebugLineStr, llvm::None, + m_data_debug_line_str); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadMacroData() { + return LoadOrGetSection(eSectionTypeDWARFDebugMacro, llvm::None, + m_data_debug_macro); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadRangesData() { + return LoadOrGetSection(eSectionTypeDWARFDebugRanges, llvm::None, + m_data_debug_ranges); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadRngListsData() { + return LoadOrGetSection(eSectionTypeDWARFDebugRngLists, llvm::None, + m_data_debug_rnglists); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadStrData() { + return LoadOrGetSection(eSectionTypeDWARFDebugStr, + eSectionTypeDWARFDebugStrDwo, m_data_debug_str); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadStrOffsetsData() { + return LoadOrGetSection(eSectionTypeDWARFDebugStrOffsets, + eSectionTypeDWARFDebugStrOffsetsDwo, + m_data_debug_str_offsets); +} + +const DWARFDataExtractor &DWARFContext::getOrLoadDebugTypesData() { + return LoadOrGetSection(eSectionTypeDWARFDebugTypes, + eSectionTypeDWARFDebugTypesDwo, m_data_debug_types); +} + +llvm::DWARFContext &DWARFContext::GetAsLLVM() { + if (!m_llvm_context) { + llvm::StringMap<std::unique_ptr<llvm::MemoryBuffer>> section_map; + uint8_t addr_size = 0; + + auto AddSection = [&](Section §ion) { + DataExtractor section_data; + section.GetSectionData(section_data); + + // Set the address size the first time we see it. + if (addr_size == 0) + addr_size = section_data.GetByteSize(); + + llvm::StringRef data = llvm::toStringRef(section_data.GetData()); + llvm::StringRef name = section.GetName().GetStringRef(); + if (name.startswith(".")) + name = name.drop_front(); + section_map.try_emplace( + name, llvm::MemoryBuffer::getMemBuffer(data, name, false)); + }; + + if (m_main_section_list) { + for (auto §ion : *m_main_section_list) + AddSection(*section); + } + + if (m_dwo_section_list) { + for (auto §ion : *m_dwo_section_list) + AddSection(*section); + } + + m_llvm_context = llvm::DWARFContext::create(section_map, addr_size); + } + return *m_llvm_context; +}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFContext.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFContext.h new file mode 100644 index 0000000..add0423 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFContext.h
@@ -0,0 +1,74 @@ +//===-- DWARFContext.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_PLUGINS_SYMBOLFILE_DWARF_DWARFCONTEXT_H +#define LLDB_PLUGINS_SYMBOLFILE_DWARF_DWARFCONTEXT_H + +#include "DWARFDataExtractor.h" +#include "lldb/Core/Section.h" +#include "llvm/ADT/Optional.h" +#include "llvm/DebugInfo/DWARF/DWARFContext.h" +#include "llvm/Support/Threading.h" +#include <memory> + +namespace lldb_private { +class DWARFContext { +private: + SectionList *m_main_section_list; + SectionList *m_dwo_section_list; + mutable std::unique_ptr<llvm::DWARFContext> m_llvm_context; + + struct SectionData { + llvm::once_flag flag; + DWARFDataExtractor data; + }; + + SectionData m_data_debug_abbrev; + SectionData m_data_debug_addr; + SectionData m_data_debug_aranges; + SectionData m_data_debug_info; + SectionData m_data_debug_line; + SectionData m_data_debug_line_str; + SectionData m_data_debug_macro; + SectionData m_data_debug_ranges; + SectionData m_data_debug_rnglists; + SectionData m_data_debug_str; + SectionData m_data_debug_str_offsets; + SectionData m_data_debug_types; + + bool isDwo() { return m_dwo_section_list != nullptr; } + + const DWARFDataExtractor & + LoadOrGetSection(lldb::SectionType main_section_type, + llvm::Optional<lldb::SectionType> dwo_section_type, + SectionData &data); + +public: + explicit DWARFContext(SectionList *main_section_list, + SectionList *dwo_section_list) + : m_main_section_list(main_section_list), + m_dwo_section_list(dwo_section_list) {} + + const DWARFDataExtractor &getOrLoadAbbrevData(); + const DWARFDataExtractor &getOrLoadAddrData(); + const DWARFDataExtractor &getOrLoadArangesData(); + const DWARFDataExtractor &getOrLoadDebugInfoData(); + const DWARFDataExtractor &getOrLoadLineData(); + const DWARFDataExtractor &getOrLoadLineStrData(); + const DWARFDataExtractor &getOrLoadMacroData(); + const DWARFDataExtractor &getOrLoadRangesData(); + const DWARFDataExtractor &getOrLoadRngListsData(); + const DWARFDataExtractor &getOrLoadStrData(); + const DWARFDataExtractor &getOrLoadStrOffsetsData(); + const DWARFDataExtractor &getOrLoadDebugTypesData(); + + llvm::DWARFContext &GetAsLLVM(); +}; +} // namespace lldb_private + +#endif
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.cpp index 22b70b2..9d97ca1 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.cpp
@@ -1,16 +1,14 @@ //===-- DWARFDIE.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DWARFDIE.h" #include "DWARFASTParser.h" -#include "DWARFDIECollection.h" #include "DWARFDebugInfo.h" #include "DWARFDebugInfoEntry.h" #include "DWARFDeclContext.h" @@ -18,20 +16,75 @@ using namespace lldb_private; -void DWARFDIE::ElaboratingDIEIterator::Next() { - assert(!m_worklist.empty() && "Incrementing end iterator?"); +namespace { - // Pop the current item from the list. - DWARFDIE die = m_worklist.back(); - m_worklist.pop_back(); +/// Iterate through all DIEs elaborating (i.e. reachable by a chain of +/// DW_AT_specification and DW_AT_abstract_origin attributes) a given DIE. For +/// convenience, the starting die is included in the sequence as the first +/// item. +class ElaboratingDIEIterator + : public std::iterator<std::input_iterator_tag, DWARFDIE> { - // And add back any items that elaborate it. - for (dw_attr_t attr : {DW_AT_specification, DW_AT_abstract_origin}) { - if (DWARFDIE d = die.GetReferencedDIE(attr)) - if (m_seen.insert(die.GetID()).second) - m_worklist.push_back(d); + // The operating invariant is: top of m_worklist contains the "current" item + // and the rest of the list are items yet to be visited. An empty worklist + // means we've reached the end. + // Infinite recursion is prevented by maintaining a list of seen DIEs. + // Container sizes are optimized for the case of following DW_AT_specification + // and DW_AT_abstract_origin just once. + llvm::SmallVector<DWARFDIE, 2> m_worklist; + llvm::SmallSet<lldb::user_id_t, 3> m_seen; + + void Next() { + assert(!m_worklist.empty() && "Incrementing end iterator?"); + + // Pop the current item from the list. + DWARFDIE die = m_worklist.back(); + m_worklist.pop_back(); + + // And add back any items that elaborate it. + for (dw_attr_t attr : {DW_AT_specification, DW_AT_abstract_origin}) { + if (DWARFDIE d = die.GetReferencedDIE(attr)) + if (m_seen.insert(die.GetID()).second) + m_worklist.push_back(d); + } } + +public: + /// An iterator starting at die d. + explicit ElaboratingDIEIterator(DWARFDIE d) : m_worklist(1, d) {} + + /// End marker + ElaboratingDIEIterator() {} + + const DWARFDIE &operator*() const { return m_worklist.back(); } + ElaboratingDIEIterator &operator++() { + Next(); + return *this; + } + ElaboratingDIEIterator operator++(int) { + ElaboratingDIEIterator I = *this; + Next(); + return I; + } + + friend bool operator==(const ElaboratingDIEIterator &a, + const ElaboratingDIEIterator &b) { + if (a.m_worklist.empty() || b.m_worklist.empty()) + return a.m_worklist.empty() == b.m_worklist.empty(); + return a.m_worklist.back() == b.m_worklist.back(); + } + friend bool operator!=(const ElaboratingDIEIterator &a, + const ElaboratingDIEIterator &b) { + return !(a == b); + } +}; + +llvm::iterator_range<ElaboratingDIEIterator> +elaborating_dies(const DWARFDIE &die) { + return llvm::make_range(ElaboratingDIEIterator(die), + ElaboratingDIEIterator()); } +} // namespace DWARFDIE DWARFDIE::GetParent() const { @@ -59,12 +112,10 @@ DWARFDIE DWARFDIE::GetReferencedDIE(const dw_attr_t attr) const { - const dw_offset_t die_offset = - GetAttributeValueAsReference(attr, DW_INVALID_OFFSET); - if (die_offset != DW_INVALID_OFFSET) - return GetDIE(die_offset); + if (IsValid()) + return m_die->GetAttributeValueAsReference(GetCU(), attr); else - return DWARFDIE(); + return {}; } DWARFDIE @@ -79,12 +130,11 @@ DWARFDIE::GetAttributeValueAsReferenceDIE(const dw_attr_t attr) const { if (IsValid()) { DWARFUnit *cu = GetCU(); - SymbolFileDWARF *dwarf = cu->GetSymbolFileDWARF(); const bool check_specification_or_abstract_origin = true; DWARFFormValue form_value; - if (m_die->GetAttributeValue(dwarf, cu, attr, form_value, nullptr, + if (m_die->GetAttributeValue(cu, attr, form_value, nullptr, check_specification_or_abstract_origin)) - return dwarf->GetDIE(DIERef(form_value)); + return form_value.Reference(); } return DWARFDIE(); } @@ -96,13 +146,14 @@ DWARFUnit *cu = GetCU(); DWARFDebugInfoEntry *function_die = nullptr; DWARFDebugInfoEntry *block_die = nullptr; - if (m_die->LookupAddress(file_addr, dwarf, cu, &function_die, &block_die)) { + if (m_die->LookupAddress(file_addr, cu, &function_die, &block_die)) { if (block_die && block_die != function_die) { if (cu->ContainsDIEOffset(block_die->GetOffset())) return DWARFDIE(cu, block_die); else - return DWARFDIE(dwarf->DebugInfo()->GetCompileUnit( - DIERef(cu->GetOffset(), block_die->GetOffset())), + return DWARFDIE(dwarf->DebugInfo()->GetUnit(DIERef( + cu->GetSymbolFileDWARF().GetDwoNum(), + cu->GetDebugSection(), block_die->GetOffset())), block_die); } } @@ -112,25 +163,149 @@ const char *DWARFDIE::GetMangledName() const { if (IsValid()) - return m_die->GetMangledName(GetDWARF(), m_cu); + return m_die->GetMangledName(m_cu); else return nullptr; } const char *DWARFDIE::GetPubname() const { if (IsValid()) - return m_die->GetPubname(GetDWARF(), m_cu); + return m_die->GetPubname(m_cu); else return nullptr; } const char *DWARFDIE::GetQualifiedName(std::string &storage) const { if (IsValid()) - return m_die->GetQualifiedName(GetDWARF(), m_cu, storage); + return m_die->GetQualifiedName(m_cu, storage); else return nullptr; } +// GetName +// +// Get value of the DW_AT_name attribute and place that value into the supplied +// stream object. If the DIE is a NULL object "NULL" is placed into the stream, +// and if no DW_AT_name attribute exists for the DIE then nothing is printed. +void DWARFDIE::GetName(Stream &s) const { + if (!IsValid()) + return; + if (GetDIE()->IsNULL()) { + s.PutCString("NULL"); + return; + } + const char *name = GetDIE()->GetAttributeValueAsString(GetCU(), DW_AT_name, nullptr, true); + if (!name) + return; + s.PutCString(name); +} + +// AppendTypeName +// +// Follows the type name definition down through all needed tags to end up with +// a fully qualified type name and dump the results to the supplied stream. +// This is used to show the name of types given a type identifier. +void DWARFDIE::AppendTypeName(Stream &s) const { + if (!IsValid()) + return; + if (GetDIE()->IsNULL()) { + s.PutCString("NULL"); + return; + } + if (const char *name = GetPubname()) { + s.PutCString(name); + return; + } + switch (Tag()) { + case DW_TAG_array_type: + break; // print out a "[]" after printing the full type of the element + // below + case DW_TAG_base_type: + s.PutCString("base "); + break; + case DW_TAG_class_type: + s.PutCString("class "); + break; + case DW_TAG_const_type: + s.PutCString("const "); + break; + case DW_TAG_enumeration_type: + s.PutCString("enum "); + break; + case DW_TAG_file_type: + s.PutCString("file "); + break; + case DW_TAG_interface_type: + s.PutCString("interface "); + break; + case DW_TAG_packed_type: + s.PutCString("packed "); + break; + case DW_TAG_pointer_type: + break; // print out a '*' after printing the full type below + case DW_TAG_ptr_to_member_type: + break; // print out a '*' after printing the full type below + case DW_TAG_reference_type: + break; // print out a '&' after printing the full type below + case DW_TAG_restrict_type: + s.PutCString("restrict "); + break; + case DW_TAG_set_type: + s.PutCString("set "); + break; + case DW_TAG_shared_type: + s.PutCString("shared "); + break; + case DW_TAG_string_type: + s.PutCString("string "); + break; + case DW_TAG_structure_type: + s.PutCString("struct "); + break; + case DW_TAG_subrange_type: + s.PutCString("subrange "); + break; + case DW_TAG_subroutine_type: + s.PutCString("function "); + break; + case DW_TAG_thrown_type: + s.PutCString("thrown "); + break; + case DW_TAG_union_type: + s.PutCString("union "); + break; + case DW_TAG_unspecified_type: + s.PutCString("unspecified "); + break; + case DW_TAG_volatile_type: + s.PutCString("volatile "); + break; + default: + return; + } + + // Follow the DW_AT_type if possible + if (DWARFDIE next_die = GetAttributeValueAsReferenceDIE(DW_AT_type)) + next_die.AppendTypeName(s); + + switch (Tag()) { + case DW_TAG_array_type: + s.PutCString("[]"); + break; + case DW_TAG_pointer_type: + s.PutChar('*'); + break; + case DW_TAG_ptr_to_member_type: + s.PutChar('*'); + break; + case DW_TAG_reference_type: + s.PutChar('&'); + break; + default: + break; + } +} + lldb_private::Type *DWARFDIE::ResolveType() const { if (IsValid()) return GetDWARF()->ResolveType(*this, true); @@ -138,29 +313,30 @@ return nullptr; } -lldb_private::Type *DWARFDIE::ResolveTypeUID(const DIERef &die_ref) const { - SymbolFileDWARF *dwarf = GetDWARF(); - if (dwarf) - return dwarf->ResolveTypeUID(dwarf->GetDIE(die_ref), true); - else - return nullptr; +lldb_private::Type *DWARFDIE::ResolveTypeUID(const DWARFDIE &die) const { + if (SymbolFileDWARF *dwarf = GetDWARF()) + return dwarf->ResolveTypeUID(die, true); + return nullptr; } -void DWARFDIE::GetDeclContextDIEs(DWARFDIECollection &decl_context_dies) const { - if (IsValid()) { - DWARFDIE parent_decl_ctx_die = - m_die->GetParentDeclContextDIE(GetDWARF(), GetCU()); - if (parent_decl_ctx_die && parent_decl_ctx_die.GetDIE() != GetDIE()) { - decl_context_dies.Append(parent_decl_ctx_die); - parent_decl_ctx_die.GetDeclContextDIEs(decl_context_dies); - } +std::vector<DWARFDIE> DWARFDIE::GetDeclContextDIEs() const { + if (!IsValid()) + return {}; + + std::vector<DWARFDIE> result; + DWARFDIE parent = GetParentDeclContextDIE(); + while (parent.IsValid() && parent.GetDIE() != GetDIE()) { + result.push_back(std::move(parent)); + parent = parent.GetParentDeclContextDIE(); } + + return result; } void DWARFDIE::GetDWARFDeclContext(DWARFDeclContext &dwarf_decl_ctx) const { if (IsValid()) { dwarf_decl_ctx.SetLanguage(GetLanguage()); - m_die->GetDWARFDeclContext(GetDWARF(), GetCU(), dwarf_decl_ctx); + m_die->GetDWARFDeclContext(GetCU(), dwarf_decl_ctx); } else { dwarf_decl_ctx.Clear(); } @@ -218,7 +394,7 @@ DWARFDIE DWARFDIE::GetParentDeclContextDIE() const { if (IsValid()) - return m_die->GetParentDeclContextDIE(GetDWARF(), m_cu); + return m_die->GetParentDeclContextDIE(m_cu); else return DWARFDIE(); } @@ -230,7 +406,7 @@ } bool DWARFDIE::IsMethod() const { - for (DWARFDIE d: elaborating_dies()) + for (DWARFDIE d : elaborating_dies(*this)) if (d.GetParent().IsStructUnionOrClass()) return true; return false; @@ -276,8 +452,8 @@ lldb_private::DWARFExpression *frame_base) const { if (IsValid()) { return m_die->GetDIENamesAndRanges( - GetDWARF(), GetCU(), name, mangled, ranges, decl_file, decl_line, - decl_column, call_file, call_line, call_column, frame_base); + GetCU(), name, mangled, ranges, decl_file, decl_line, decl_column, + call_file, call_line, call_column, frame_base); } else return false; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h index b0d06a8..7753ec9 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h
@@ -1,9 +1,8 @@ //===-- DWARFDIE.h ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,46 +14,37 @@ class DWARFDIE : public DWARFBaseDIE { public: - class ElaboratingDIEIterator; - using DWARFBaseDIE::DWARFBaseDIE; - //---------------------------------------------------------------------- // Tests - //---------------------------------------------------------------------- bool IsStructUnionOrClass() const; bool IsMethod() const; - //---------------------------------------------------------------------- // Accessors - //---------------------------------------------------------------------- lldb::ModuleSP GetContainingDWOModule() const; DWARFDIE GetContainingDWOModuleDIE() const; - inline llvm::iterator_range<ElaboratingDIEIterator> elaborating_dies() const; - - //---------------------------------------------------------------------- // Accessing information about a DIE - //---------------------------------------------------------------------- const char *GetMangledName() const; const char *GetPubname() const; const char *GetQualifiedName(std::string &storage) const; + using DWARFBaseDIE::GetName; + void GetName(lldb_private::Stream &s) const; + + void AppendTypeName(lldb_private::Stream &s) const; + lldb_private::Type *ResolveType() const; - //---------------------------------------------------------------------- // Resolve a type by UID using this DIE's DWARF file - //---------------------------------------------------------------------- - lldb_private::Type *ResolveTypeUID(const DIERef &die_ref) const; + lldb_private::Type *ResolveTypeUID(const DWARFDIE &die) const; - //---------------------------------------------------------------------- // Functions for obtaining DIE relations and references - //---------------------------------------------------------------------- DWARFDIE GetParent() const; @@ -68,11 +58,9 @@ DWARFDIE GetReferencedDIE(const dw_attr_t attr) const; - //---------------------------------------------------------------------- // Get a another DIE from the same DWARF file as this DIE. This will // check the current DIE's compile unit first to see if "die_offset" is // in the same compile unit, and fall back to checking the DWARF file. - //---------------------------------------------------------------------- DWARFDIE GetDIE(dw_offset_t die_offset) const; using DWARFBaseDIE::GetDIE; @@ -83,10 +71,8 @@ DWARFDIE GetParentDeclContextDIE() const; - //---------------------------------------------------------------------- // DeclContext related functions - //---------------------------------------------------------------------- - void GetDeclContextDIEs(DWARFDIECollection &decl_context_dies) const; + std::vector<DWARFDIE> GetDeclContextDIEs() const; void GetDWARFDeclContext(DWARFDeclContext &dwarf_decl_ctx) const; @@ -95,13 +81,11 @@ void GetDeclContext(std::vector<lldb_private::CompilerContext> &context) const; - //---------------------------------------------------------------------- // Getting attribute values from the DIE. // // GetAttributeValueAsXXX() functions should only be used if you are // looking for one or two attributes on a DIE. If you are trying to // parse all attributes, use GetAttributes (...) instead - //---------------------------------------------------------------------- DWARFDIE GetAttributeValueAsReferenceDIE(const dw_attr_t attr) const; @@ -111,9 +95,7 @@ int &call_line, int &call_column, lldb_private::DWARFExpression *frame_base) const; - //---------------------------------------------------------------------- // CompilerDecl related functions - //---------------------------------------------------------------------- lldb_private::CompilerDecl GetDecl() const; @@ -122,58 +104,4 @@ lldb_private::CompilerDeclContext GetContainingDeclContext() const; }; -/// Iterate through all DIEs elaborating (i.e. reachable by a chain of -/// DW_AT_specification and DW_AT_abstract_origin attributes) a given DIE. For -/// convenience, the starting die is included in the sequence as the first -/// item. -class DWARFDIE::ElaboratingDIEIterator - : public std::iterator<std::input_iterator_tag, DWARFDIE> { - - // The operating invariant is: top of m_worklist contains the "current" item - // and the rest of the list are items yet to be visited. An empty worklist - // means we've reached the end. - // Infinite recursion is prevented by maintaining a list of seen DIEs. - // Container sizes are optimized for the case of following DW_AT_specification - // and DW_AT_abstract_origin just once. - llvm::SmallVector<DWARFDIE, 2> m_worklist; - llvm::SmallSet<lldb::user_id_t, 3> m_seen; - - void Next(); - -public: - /// An iterator starting at die d. - explicit ElaboratingDIEIterator(DWARFDIE d) : m_worklist(1, d) {} - - /// End marker - ElaboratingDIEIterator() {} - - const DWARFDIE &operator*() const { return m_worklist.back(); } - ElaboratingDIEIterator &operator++() { - Next(); - return *this; - } - ElaboratingDIEIterator operator++(int) { - ElaboratingDIEIterator I = *this; - Next(); - return I; - } - - friend bool operator==(const ElaboratingDIEIterator &a, - const ElaboratingDIEIterator &b) { - if (a.m_worklist.empty() || b.m_worklist.empty()) - return a.m_worklist.empty() == b.m_worklist.empty(); - return a.m_worklist.back() == b.m_worklist.back(); - } - friend bool operator!=(const ElaboratingDIEIterator &a, - const ElaboratingDIEIterator &b) { - return !(a == b); - } -}; - -llvm::iterator_range<DWARFDIE::ElaboratingDIEIterator> -DWARFDIE::elaborating_dies() const { - return llvm::make_range(ElaboratingDIEIterator(*this), - ElaboratingDIEIterator()); -} - #endif // SymbolFileDWARF_DWARFDIE_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIECollection.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIECollection.cpp deleted file mode 100644 index 1e5bf61..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIECollection.cpp +++ /dev/null
@@ -1,35 +0,0 @@ -//===-- DWARFDIECollection.cpp ----------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "DWARFDIECollection.h" - -#include <algorithm> - -#include "lldb/Utility/Stream.h" - -using namespace lldb_private; -using namespace std; - -void DWARFDIECollection::Append(const DWARFDIE &die) { m_dies.push_back(die); } - -DWARFDIE -DWARFDIECollection::GetDIEAtIndex(uint32_t idx) const { - if (idx < m_dies.size()) - return m_dies[idx]; - return DWARFDIE(); -} - -size_t DWARFDIECollection::Size() const { return m_dies.size(); } - -void DWARFDIECollection::Dump(Stream *s, const char *title) const { - if (title && title[0] != '\0') - s->Printf("%s\n", title); - for (const auto &die : m_dies) - s->Printf("0x%8.8x\n", die.GetOffset()); -}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIECollection.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIECollection.h deleted file mode 100644 index e1e73e7..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDIECollection.h +++ /dev/null
@@ -1,38 +0,0 @@ -//===-- DWARFDIECollection.h ------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef SymbolFileDWARF_DWARFDIECollection_h_ -#define SymbolFileDWARF_DWARFDIECollection_h_ - -#include "DWARFDIE.h" -#include <vector> - -class DWARFDIECollection { -public: - DWARFDIECollection() : m_dies() {} - ~DWARFDIECollection() {} - - void Append(const DWARFDIE &die); - - void Dump(lldb_private::Stream *s, const char *title) const; - - DWARFDIE - GetDIEAtIndex(uint32_t idx) const; - - size_t Size() const; - -protected: - typedef std::vector<DWARFDIE> collection; - typedef collection::iterator iterator; - typedef collection::const_iterator const_iterator; - - collection m_dies; // Ordered list of die offsets -}; - -#endif // SymbolFileDWARF_DWARFDIECollection_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.cpp index 2fcdd34..1678b22 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.cpp
@@ -1,27 +1,30 @@ //===-- DWARFDataExtractor.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DWARFDataExtractor.h" +#include "llvm/ADT/StringRef.h" namespace lldb_private { uint64_t DWARFDataExtractor::GetDWARFInitialLength(lldb::offset_t *offset_ptr) const { - uint64_t length = GetU32(offset_ptr); - m_is_dwarf64 = (length == UINT32_MAX); - if (m_is_dwarf64) - length = GetU64(offset_ptr); - return length; + return GetU32(offset_ptr); } dw_offset_t DWARFDataExtractor::GetDWARFOffset(lldb::offset_t *offset_ptr) const { return GetMaxU64(offset_ptr, GetDWARFSizeOfOffset()); } + +llvm::DWARFDataExtractor DWARFDataExtractor::GetAsLLVM() const { + return llvm::DWARFDataExtractor( + llvm::StringRef(reinterpret_cast<const char *>(GetDataStart()), + GetByteSize()), + GetByteOrder() == lldb::eByteOrderLittle, GetAddressByteSize()); } +} // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.h index 1f34203..22db5e8 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDataExtractor.h
@@ -1,9 +1,8 @@ //===-- DWARFDataExtractor.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,27 +11,26 @@ #include "lldb/Core/dwarf.h" #include "lldb/Utility/DataExtractor.h" +#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" namespace lldb_private { class DWARFDataExtractor : public DataExtractor { public: - DWARFDataExtractor() : DataExtractor(), m_is_dwarf64(false) {} + DWARFDataExtractor() = default; DWARFDataExtractor(const DWARFDataExtractor &data, lldb::offset_t offset, lldb::offset_t length) - : DataExtractor(data, offset, length), m_is_dwarf64(false) {} + : DataExtractor(data, offset, length) {} uint64_t GetDWARFInitialLength(lldb::offset_t *offset_ptr) const; dw_offset_t GetDWARFOffset(lldb::offset_t *offset_ptr) const; - size_t GetDWARFSizeofInitialLength() const { return m_is_dwarf64 ? 12 : 4; } - size_t GetDWARFSizeOfOffset() const { return m_is_dwarf64 ? 8 : 4; } - bool IsDWARF64() const { return m_is_dwarf64; } + size_t GetDWARFSizeofInitialLength() const { return 4; } + size_t GetDWARFSizeOfOffset() const { return 4; } -protected: - mutable bool m_is_dwarf64; + llvm::DWARFDataExtractor GetAsLLVM() const; }; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp index affe4b8..2630156 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp
@@ -1,9 +1,8 @@ //===-- DWARFDebugAbbrev.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,50 +14,41 @@ using namespace lldb_private; using namespace std; -//---------------------------------------------------------------------- // DWARFAbbreviationDeclarationSet::Clear() -//---------------------------------------------------------------------- void DWARFAbbreviationDeclarationSet::Clear() { m_idx_offset = 0; m_decls.clear(); } -//---------------------------------------------------------------------- // DWARFAbbreviationDeclarationSet::Extract() -//---------------------------------------------------------------------- -bool DWARFAbbreviationDeclarationSet::Extract(const DWARFDataExtractor &data, - lldb::offset_t *offset_ptr) { +llvm::Error +DWARFAbbreviationDeclarationSet::extract(const DWARFDataExtractor &data, + lldb::offset_t *offset_ptr) { const lldb::offset_t begin_offset = *offset_ptr; m_offset = begin_offset; Clear(); DWARFAbbreviationDeclaration abbrevDeclaration; dw_uleb128_t prev_abbr_code = 0; - while (abbrevDeclaration.Extract(data, offset_ptr)) { + while (true) { + llvm::Expected<DWARFEnumState> es = + abbrevDeclaration.extract(data, offset_ptr); + if (!es) + return es.takeError(); + if (*es == DWARFEnumState::Complete) + break; m_decls.push_back(abbrevDeclaration); if (m_idx_offset == 0) m_idx_offset = abbrevDeclaration.Code(); - else { - if (prev_abbr_code + 1 != abbrevDeclaration.Code()) - m_idx_offset = - UINT32_MAX; // Out of order indexes, we can't do O(1) lookups... + else if (prev_abbr_code + 1 != abbrevDeclaration.Code()) { + // Out of order indexes, we can't do O(1) lookups... + m_idx_offset = UINT32_MAX; } prev_abbr_code = abbrevDeclaration.Code(); } - return begin_offset != *offset_ptr; + return llvm::ErrorSuccess(); } -//---------------------------------------------------------------------- -// DWARFAbbreviationDeclarationSet::Dump() -//---------------------------------------------------------------------- -void DWARFAbbreviationDeclarationSet::Dump(Stream *s) const { - std::for_each( - m_decls.begin(), m_decls.end(), - bind2nd(std::mem_fun_ref(&DWARFAbbreviationDeclaration::Dump), s)); -} - -//---------------------------------------------------------------------- // DWARFAbbreviationDeclarationSet::GetAbbreviationDeclaration() -//---------------------------------------------------------------------- const DWARFAbbreviationDeclaration * DWARFAbbreviationDeclarationSet::GetAbbreviationDeclaration( dw_uleb128_t abbrCode) const { @@ -74,32 +64,11 @@ if (idx < m_decls.size()) return &m_decls[idx]; } - return NULL; + return nullptr; } -//---------------------------------------------------------------------- -// DWARFAbbreviationDeclarationSet::AppendAbbrevDeclSequential() -// -// Append an abbreviation declaration with a sequential code for O(n) lookups. -// Handy when creating an DWARFAbbreviationDeclarationSet. -//---------------------------------------------------------------------- -dw_uleb128_t DWARFAbbreviationDeclarationSet::AppendAbbrevDeclSequential( - const DWARFAbbreviationDeclaration &abbrevDecl) { - // Get the next abbreviation code based on our current array size - dw_uleb128_t code = m_decls.size() + 1; - // Push the new declaration on the back - m_decls.push_back(abbrevDecl); - - // Update the code for this new declaration - m_decls.back().SetCode(code); - - return code; // return the new abbreviation code! -} - -//---------------------------------------------------------------------- // DWARFAbbreviationDeclarationSet::GetUnsupportedForms() -//---------------------------------------------------------------------- void DWARFAbbreviationDeclarationSet::GetUnsupportedForms( std::set<dw_form_t> &invalid_forms) const { for (const auto &abbr_decl : m_decls) { @@ -112,13 +81,11 @@ } } -//---------------------------------------------------------------------- // Encode // // Encode the abbreviation table onto the end of the buffer provided into a // byte representation as would be found in a ".debug_abbrev" debug information // section. -//---------------------------------------------------------------------- // void // DWARFAbbreviationDeclarationSet::Encode(BinaryStreamBuf& debug_abbrev_buf) // const @@ -130,49 +97,29 @@ // debug_abbrev_buf.Append8(0); //} -//---------------------------------------------------------------------- // DWARFDebugAbbrev constructor -//---------------------------------------------------------------------- DWARFDebugAbbrev::DWARFDebugAbbrev() : m_abbrevCollMap(), m_prev_abbr_offset_pos(m_abbrevCollMap.end()) {} -//---------------------------------------------------------------------- // DWARFDebugAbbrev::Parse() -//---------------------------------------------------------------------- -void DWARFDebugAbbrev::Parse(const DWARFDataExtractor &data) { +llvm::Error DWARFDebugAbbrev::parse(const DWARFDataExtractor &data) { lldb::offset_t offset = 0; while (data.ValidOffset(offset)) { uint32_t initial_cu_offset = offset; DWARFAbbreviationDeclarationSet abbrevDeclSet; - if (abbrevDeclSet.Extract(data, &offset)) - m_abbrevCollMap[initial_cu_offset] = abbrevDeclSet; - else - break; + llvm::Error error = abbrevDeclSet.extract(data, &offset); + if (error) + return error; + + m_abbrevCollMap[initial_cu_offset] = abbrevDeclSet; } m_prev_abbr_offset_pos = m_abbrevCollMap.end(); + return llvm::ErrorSuccess(); } -//---------------------------------------------------------------------- -// DWARFDebugAbbrev::Dump() -//---------------------------------------------------------------------- -void DWARFDebugAbbrev::Dump(Stream *s) const { - if (m_abbrevCollMap.empty()) { - s->PutCString("< EMPTY >\n"); - return; - } - - DWARFAbbreviationDeclarationCollMapConstIter pos; - for (pos = m_abbrevCollMap.begin(); pos != m_abbrevCollMap.end(); ++pos) { - s->Printf("Abbrev table for offset: 0x%8.8x\n", pos->first); - pos->second.Dump(s); - } -} - -//---------------------------------------------------------------------- // DWARFDebugAbbrev::GetAbbreviationDeclarationSet() -//---------------------------------------------------------------------- const DWARFAbbreviationDeclarationSet * DWARFDebugAbbrev::GetAbbreviationDeclarationSet( dw_offset_t cu_abbr_offset) const { @@ -188,12 +135,10 @@ if (pos != m_abbrevCollMap.end()) return &(pos->second); - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // DWARFDebugAbbrev::GetUnsupportedForms() -//---------------------------------------------------------------------- void DWARFDebugAbbrev::GetUnsupportedForms( std::set<dw_form_t> &invalid_forms) const { for (const auto &pair : m_abbrevCollMap)
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.h index 2bacb63..9c47293 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.h
@@ -1,9 +1,8 @@ //===-- DWARFDebugAbbrev.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,17 +34,21 @@ void Clear(); dw_offset_t GetOffset() const { return m_offset; } - void Dump(lldb_private::Stream *s) const; - bool Extract(const lldb_private::DWARFDataExtractor &data, - lldb::offset_t *offset_ptr); + + /// Extract all abbrev decls in a set. Returns llvm::ErrorSuccess() on + /// success, and an appropriate llvm::Error object otherwise. + llvm::Error extract(const lldb_private::DWARFDataExtractor &data, + lldb::offset_t *offset_ptr); // void Encode(BinaryStreamBuf& debug_abbrev_buf) const; - dw_uleb128_t - AppendAbbrevDeclSequential(const DWARFAbbreviationDeclaration &abbrevDecl); void GetUnsupportedForms(std::set<dw_form_t> &invalid_forms) const; const DWARFAbbreviationDeclaration * GetAbbreviationDeclaration(dw_uleb128_t abbrCode) const; + /// Unit test accessor functions. + /// @{ + uint32_t GetIndexOffset() const { return m_idx_offset; } + /// @} private: dw_offset_t m_offset; uint32_t m_idx_offset; @@ -64,8 +67,10 @@ DWARFDebugAbbrev(); const DWARFAbbreviationDeclarationSet * GetAbbreviationDeclarationSet(dw_offset_t cu_abbr_offset) const; - void Dump(lldb_private::Stream *s) const; - void Parse(const lldb_private::DWARFDataExtractor &data); + /// Extract all abbreviations for a particular compile unit. Returns + /// llvm::ErrorSuccess() on success, and an appropriate llvm::Error object + /// otherwise. + llvm::Error parse(const lldb_private::DWARFDataExtractor &data); void GetUnsupportedForms(std::set<dw_form_t> &invalid_forms) const; protected:
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.cpp index 0026536..86ce3b3 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.cpp
@@ -1,17 +1,15 @@ //===-- DWARFDebugArangeSet.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DWARFDebugArangeSet.h" - -#include "SymbolFileDWARF.h" -#include "lldb/Utility/Stream.h" -#include <assert.h> +#include "DWARFDataExtractor.h" +#include "llvm/Object/Error.h" +#include <cassert> using namespace lldb_private; @@ -34,213 +32,88 @@ m_arange_descriptors.clear(); } -void DWARFDebugArangeSet::SetHeader(uint16_t version, uint32_t cu_offset, - uint8_t addr_size, uint8_t seg_size) { - m_header.version = version; - m_header.cu_offset = cu_offset; - m_header.addr_size = addr_size; - m_header.seg_size = seg_size; -} +llvm::Error DWARFDebugArangeSet::extract(const DWARFDataExtractor &data, + lldb::offset_t *offset_ptr) { + assert(data.ValidOffset(*offset_ptr)); -void DWARFDebugArangeSet::Compact() { - if (m_arange_descriptors.empty()) - return; + m_arange_descriptors.clear(); + m_offset = *offset_ptr; - // Iterate through all arange descriptors and combine any ranges that overlap - // or have matching boundaries. The m_arange_descriptors are assumed to be in - // ascending order after being built by adding descriptors using the - // AddDescriptor method. - uint32_t i = 0; - while (i + 1 < m_arange_descriptors.size()) { - if (m_arange_descriptors[i].end_address() >= - m_arange_descriptors[i + 1].address) { - // The current range ends at or exceeds the start of the next address - // range. Compute the max end address between the two and use that to - // make the new length. - const dw_addr_t max_end_addr = - std::max(m_arange_descriptors[i].end_address(), - m_arange_descriptors[i + 1].end_address()); - m_arange_descriptors[i].length = - max_end_addr - m_arange_descriptors[i].address; - // Now remove the next entry as it was just combined with the previous - // one. - m_arange_descriptors.erase(m_arange_descriptors.begin() + i + 1); - } else { - // Discontiguous address range, just proceed to the next one. - ++i; - } - } -} -//---------------------------------------------------------------------- -// Compare function DWARFDebugArangeSet::Descriptor structures -//---------------------------------------------------------------------- -static bool DescriptorLessThan(const DWARFDebugArangeSet::Descriptor &range1, - const DWARFDebugArangeSet::Descriptor &range2) { - return range1.address < range2.address; -} + // 7.20 Address Range Table + // + // Each set of entries in the table of address ranges contained in the + // .debug_aranges section begins with a header consisting of: a 4-byte + // length containing the length of the set of entries for this compilation + // unit, not including the length field itself; a 2-byte version identifier + // containing the value 2 for DWARF Version 2; a 4-byte offset into + // the.debug_infosection; a 1-byte unsigned integer containing the size in + // bytes of an address (or the offset portion of an address for segmented + // addressing) on the target system; and a 1-byte unsigned integer + // containing the size in bytes of a segment descriptor on the target + // system. This header is followed by a series of tuples. Each tuple + // consists of an address and a length, each in the size appropriate for an + // address on the target architecture. + m_header.length = data.GetDWARFInitialLength(offset_ptr); + m_header.version = data.GetU16(offset_ptr); + m_header.cu_offset = data.GetDWARFOffset(offset_ptr); + m_header.addr_size = data.GetU8(offset_ptr); + m_header.seg_size = data.GetU8(offset_ptr); -//---------------------------------------------------------------------- -// Add a range descriptor and keep things sorted so we can easily compact the -// ranges before being saved or used. -//---------------------------------------------------------------------- -void DWARFDebugArangeSet::AddDescriptor( - const DWARFDebugArangeSet::Descriptor &range) { - if (m_arange_descriptors.empty()) { - m_arange_descriptors.push_back(range); - return; + // Try to avoid reading invalid arange sets by making sure: + // 1 - the version looks good + // 2 - the address byte size looks plausible + // 3 - the length seems to make sense + // size looks plausible + if (m_header.version < 2 || m_header.version > 5) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Invalid arange header version"); + + if (m_header.addr_size != 4 && m_header.addr_size != 8) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Invalid arange header address size"); + + if (m_header.length == 0) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Invalid arange header length"); + + if (!data.ValidOffset(m_offset + sizeof(m_header.length) + m_header.length - + 1)) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Invalid arange header length"); + + // The first tuple following the header in each set begins at an offset + // that is a multiple of the size of a single tuple (that is, twice the + // size of an address). The header is padded, if necessary, to the + // appropriate boundary. + const uint32_t header_size = *offset_ptr - m_offset; + const uint32_t tuple_size = m_header.addr_size << 1; + uint32_t first_tuple_offset = 0; + while (first_tuple_offset < header_size) + first_tuple_offset += tuple_size; + + *offset_ptr = m_offset + first_tuple_offset; + + Descriptor arangeDescriptor; + + static_assert(sizeof(arangeDescriptor.address) == + sizeof(arangeDescriptor.length), + "DWARFDebugArangeSet::Descriptor.address and " + "DWARFDebugArangeSet::Descriptor.length must have same size"); + + while (data.ValidOffset(*offset_ptr)) { + arangeDescriptor.address = data.GetMaxU64(offset_ptr, m_header.addr_size); + arangeDescriptor.length = data.GetMaxU64(offset_ptr, m_header.addr_size); + + // Each set of tuples is terminated by a 0 for the address and 0 for + // the length. + if (!arangeDescriptor.address && !arangeDescriptor.length) + return llvm::ErrorSuccess(); + + m_arange_descriptors.push_back(arangeDescriptor); } - DescriptorIter end = m_arange_descriptors.end(); - DescriptorIter pos = - lower_bound(m_arange_descriptors.begin(), end, range, DescriptorLessThan); - const dw_addr_t range_end_addr = range.end_address(); - if (pos != end) { - const dw_addr_t found_end_addr = pos->end_address(); - if (range.address < pos->address) { - if (range_end_addr < pos->address) { - // Non-contiguous entries, add this one before the found entry - m_arange_descriptors.insert(pos, range); - } else if (range_end_addr == pos->address) { - // The top end of 'range' is the lower end of the entry pointed to by - // 'pos'. We can combine range with the entry we found by setting the - // starting address and increasing the length since they don't overlap. - pos->address = range.address; - pos->length += range.length; - } else { - // We can combine these two and make sure the largest end address is - // used to make end address. - pos->address = range.address; - pos->length = std::max(found_end_addr, range_end_addr) - pos->address; - } - } else if (range.address == pos->address) { - pos->length = std::max(pos->length, range.length); - } - } else { - // NOTE: 'pos' points to entry past the end which is ok for insert, - // don't use otherwise!!! - const dw_addr_t max_addr = m_arange_descriptors.back().end_address(); - if (max_addr < range.address) { - // Non-contiguous entries, add this one before the found entry - m_arange_descriptors.insert(pos, range); - } else if (max_addr == range.address) { - m_arange_descriptors.back().length += range.length; - } else { - m_arange_descriptors.back().length = std::max(max_addr, range_end_addr) - - m_arange_descriptors.back().address; - } - } -} - -bool DWARFDebugArangeSet::Extract(const DWARFDataExtractor &data, - lldb::offset_t *offset_ptr) { - if (data.ValidOffset(*offset_ptr)) { - m_arange_descriptors.clear(); - m_offset = *offset_ptr; - - // 7.20 Address Range Table - // - // Each set of entries in the table of address ranges contained in the - // .debug_aranges section begins with a header consisting of: a 4-byte - // length containing the length of the set of entries for this compilation - // unit, not including the length field itself; a 2-byte version identifier - // containing the value 2 for DWARF Version 2; a 4-byte offset into - // the.debug_infosection; a 1-byte unsigned integer containing the size in - // bytes of an address (or the offset portion of an address for segmented - // addressing) on the target system; and a 1-byte unsigned integer - // containing the size in bytes of a segment descriptor on the target - // system. This header is followed by a series of tuples. Each tuple - // consists of an address and a length, each in the size appropriate for an - // address on the target architecture. - m_header.length = data.GetDWARFInitialLength(offset_ptr); - m_header.version = data.GetU16(offset_ptr); - m_header.cu_offset = data.GetDWARFOffset(offset_ptr); - m_header.addr_size = data.GetU8(offset_ptr); - m_header.seg_size = data.GetU8(offset_ptr); - - // Try to avoid reading invalid arange sets by making sure: - // 1 - the version looks good - // 2 - the address byte size looks plausible - // 3 - the length seems to make sense - // size looks plausible - if ((m_header.version >= 2 && m_header.version <= 5) && - (m_header.addr_size == 4 || m_header.addr_size == 8) && - (m_header.length > 0)) { - if (data.ValidOffset(m_offset + sizeof(m_header.length) + - m_header.length - 1)) { - // The first tuple following the header in each set begins at an offset - // that is a multiple of the size of a single tuple (that is, twice the - // size of an address). The header is padded, if necessary, to the - // appropriate boundary. - const uint32_t header_size = *offset_ptr - m_offset; - const uint32_t tuple_size = m_header.addr_size << 1; - uint32_t first_tuple_offset = 0; - while (first_tuple_offset < header_size) - first_tuple_offset += tuple_size; - - *offset_ptr = m_offset + first_tuple_offset; - - Descriptor arangeDescriptor; - - static_assert( - sizeof(arangeDescriptor.address) == sizeof(arangeDescriptor.length), - "DWARFDebugArangeSet::Descriptor.address and " - "DWARFDebugArangeSet::Descriptor.length must have same size"); - - while (data.ValidOffset(*offset_ptr)) { - arangeDescriptor.address = - data.GetMaxU64(offset_ptr, m_header.addr_size); - arangeDescriptor.length = - data.GetMaxU64(offset_ptr, m_header.addr_size); - - // Each set of tuples is terminated by a 0 for the address and 0 for - // the length. - if (arangeDescriptor.address || arangeDescriptor.length) - m_arange_descriptors.push_back(arangeDescriptor); - else - break; // We are done if we get a zero address and length - } - } -#if defined(LLDB_CONFIGURATION_DEBUG) - else { - printf("warning: .debug_arange set length is too large arange data at " - "0x%8.8x: length=0x%8.8x, version=0x%4.4x, cu_offset=0x%8.8x, " - "addr_size=%u, seg_size=%u\n", - m_offset, m_header.length, m_header.version, m_header.cu_offset, - m_header.addr_size, m_header.seg_size); - } -#endif - } -#if defined(LLDB_CONFIGURATION_DEBUG) - else { - printf("warning: .debug_arange set has bad header at 0x%8.8x: " - "length=0x%8.8x, version=0x%4.4x, cu_offset=0x%8.8x, " - "addr_size=%u, seg_size=%u\n", - m_offset, m_header.length, m_header.version, m_header.cu_offset, - m_header.addr_size, m_header.seg_size); - } -#endif - - return !m_arange_descriptors.empty(); - } - return false; -} - -dw_offset_t DWARFDebugArangeSet::GetOffsetOfNextEntry() const { - return m_offset + m_header.length + 4; -} - -void DWARFDebugArangeSet::Dump(Stream *s) const { - s->Printf("Address Range Header: length = 0x%8.8x, version = 0x%4.4x, " - "cu_offset = 0x%8.8x, addr_size = 0x%2.2x, seg_size = 0x%2.2x\n", - m_header.length, m_header.version, m_header.cu_offset, - m_header.addr_size, m_header.seg_size); - - const uint32_t hex_width = m_header.addr_size * 2; - DescriptorConstIter pos; - DescriptorConstIter end = m_arange_descriptors.end(); - for (pos = m_arange_descriptors.begin(); pos != end; ++pos) - s->Printf("[0x%*.*" PRIx64 " - 0x%*.*" PRIx64 ")\n", hex_width, hex_width, - pos->address, hex_width, hex_width, pos->end_address()); + return llvm::make_error<llvm::object::GenericBinaryError>( + "arange descriptors not terminated by null entry"); } class DescriptorContainsAddress {
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.h index ae6319a..db0cf22 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.h
@@ -1,20 +1,18 @@ //===-- DWARFDebugArangeSet.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 SymbolFileDWARF_DWARFDebugArangeSet_h_ #define SymbolFileDWARF_DWARFDebugArangeSet_h_ -#include "SymbolFileDWARF.h" +#include "lldb/Core/dwarf.h" +#include <cstdint> #include <vector> -class SymbolFileDWARF; - class DWARFDebugArangeSet { public: struct Header { @@ -41,23 +39,11 @@ DWARFDebugArangeSet(); void Clear(); void SetOffset(uint32_t offset) { m_offset = offset; } - void SetHeader(uint16_t version, uint32_t cu_offset, uint8_t addr_size, - uint8_t seg_size); - void AddDescriptor(const DWARFDebugArangeSet::Descriptor &range); - void Compact(); - bool Extract(const lldb_private::DWARFDataExtractor &data, - lldb::offset_t *offset_ptr); - void Dump(lldb_private::Stream *s) const; - dw_offset_t GetCompileUnitDIEOffset() const { return m_header.cu_offset; } - dw_offset_t GetOffsetOfNextEntry() const; + llvm::Error extract(const lldb_private::DWARFDataExtractor &data, + lldb::offset_t *offset_ptr); dw_offset_t FindAddress(dw_addr_t address) const; size_t NumDescriptors() const { return m_arange_descriptors.size(); } const Header &GetHeader() const { return m_header; } - const Descriptor *GetDescriptor(uint32_t i) const { - if (i < m_arange_descriptors.size()) - return &m_arange_descriptors[i]; - return NULL; - } const Descriptor &GetDescriptorRef(uint32_t i) const { return m_arange_descriptors[i];
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp index 02f528d..ccf33e6 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp
@@ -1,39 +1,24 @@ //===-- DWARFDebugAranges.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DWARFDebugAranges.h" - -#include <assert.h> -#include <stdio.h> - -#include <algorithm> - -#include "lldb/Utility/Log.h" -#include "lldb/Utility/Stream.h" -#include "lldb/Utility/Timer.h" - +#include "DWARFDebugArangeSet.h" #include "DWARFUnit.h" -#include "DWARFDebugInfo.h" -#include "LogChannelDWARF.h" -#include "SymbolFileDWARF.h" +#include "lldb/Utility/Log.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- DWARFDebugAranges::DWARFDebugAranges() : m_aranges() {} -//---------------------------------------------------------------------- // CountArangeDescriptors -//---------------------------------------------------------------------- class CountArangeDescriptors { public: CountArangeDescriptors(uint32_t &count_ref) : count(count_ref) { @@ -45,53 +30,36 @@ uint32_t &count; }; -//---------------------------------------------------------------------- // Extract -//---------------------------------------------------------------------- -bool DWARFDebugAranges::Extract(const DWARFDataExtractor &debug_aranges_data) { - if (debug_aranges_data.ValidOffset(0)) { - lldb::offset_t offset = 0; +llvm::Error +DWARFDebugAranges::extract(const DWARFDataExtractor &debug_aranges_data) { + lldb::offset_t offset = 0; - DWARFDebugArangeSet set; - Range range; - while (set.Extract(debug_aranges_data, &offset)) { - const uint32_t num_descriptors = set.NumDescriptors(); - if (num_descriptors > 0) { - const dw_offset_t cu_offset = set.GetCompileUnitDIEOffset(); + DWARFDebugArangeSet set; + Range range; + while (debug_aranges_data.ValidOffset(offset)) { + llvm::Error error = set.extract(debug_aranges_data, &offset); + if (!error) + return error; - for (uint32_t i = 0; i < num_descriptors; ++i) { - const DWARFDebugArangeSet::Descriptor &descriptor = - set.GetDescriptorRef(i); - m_aranges.Append(RangeToDIE::Entry(descriptor.address, - descriptor.length, cu_offset)); - } + const uint32_t num_descriptors = set.NumDescriptors(); + if (num_descriptors > 0) { + const dw_offset_t cu_offset = set.GetHeader().cu_offset; + + for (uint32_t i = 0; i < num_descriptors; ++i) { + const DWARFDebugArangeSet::Descriptor &descriptor = + set.GetDescriptorRef(i); + m_aranges.Append(RangeToDIE::Entry(descriptor.address, + descriptor.length, cu_offset)); } - set.Clear(); } + set.Clear(); } - return false; -} - -//---------------------------------------------------------------------- -// Generate -//---------------------------------------------------------------------- -bool DWARFDebugAranges::Generate(SymbolFileDWARF *dwarf2Data) { - Clear(); - DWARFDebugInfo *debug_info = dwarf2Data->DebugInfo(); - if (debug_info) { - uint32_t cu_idx = 0; - const uint32_t num_compile_units = dwarf2Data->GetNumCompileUnits(); - for (cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { - DWARFUnit *cu = debug_info->GetCompileUnitAtIndex(cu_idx); - if (cu) - cu->BuildAddressRangeTable(dwarf2Data, this); - } - } - return !IsEmpty(); + return llvm::ErrorSuccess(); } void DWARFDebugAranges::Dump(Log *log) const { - if (log == NULL) + if (log == nullptr) return; const size_t num_entries = m_aranges.GetSize(); @@ -114,35 +82,11 @@ Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); - Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_ARANGES)); - size_t orig_arange_size = 0; - if (log) { - orig_arange_size = m_aranges.GetSize(); - log->Printf("DWARFDebugAranges::Sort(minimize = %u) with %" PRIu64 - " entries", - minimize, (uint64_t)orig_arange_size); - } - m_aranges.Sort(); m_aranges.CombineConsecutiveEntriesWithEqualData(); - - if (log) { - if (minimize) { - const size_t new_arange_size = m_aranges.GetSize(); - const size_t delta = orig_arange_size - new_arange_size; - log->Printf("DWARFDebugAranges::Sort() %" PRIu64 - " entries after minimizing (%" PRIu64 - " entries combined for %" PRIu64 " bytes saved)", - (uint64_t)new_arange_size, (uint64_t)delta, - (uint64_t)delta * sizeof(Range)); - } - Dump(log); - } } -//---------------------------------------------------------------------- // FindAddress -//---------------------------------------------------------------------- dw_offset_t DWARFDebugAranges::FindAddress(dw_addr_t address) const { const RangeToDIE::Entry *entry = m_aranges.FindEntryThatContains(address); if (entry)
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.h index e7a8635..74ba011 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.h
@@ -1,21 +1,17 @@ //===-- DWARFDebugAranges.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 SymbolFileDWARF_DWARFDebugAranges_h_ #define SymbolFileDWARF_DWARFDebugAranges_h_ -#include "DWARFDebugArangeSet.h" -#include <list> - -#include "lldb/Core/RangeMap.h" - -class SymbolFileDWARF; +#include "lldb/Core/dwarf.h" +#include "lldb/Utility/RangeMap.h" +#include "llvm/Support/Error.h" class DWARFDebugAranges { protected: @@ -30,19 +26,14 @@ void Clear() { m_aranges.Clear(); } - bool Extract(const lldb_private::DWARFDataExtractor &debug_aranges_data); - - bool Generate(SymbolFileDWARF *dwarf2Data); + llvm::Error + extract(const lldb_private::DWARFDataExtractor &debug_aranges_data); // Use append range multiple times and then call sort void AppendRange(dw_offset_t cu_offset, dw_addr_t low_pc, dw_addr_t high_pc); void Sort(bool minimize); - const Range *RangeAtIndex(uint32_t idx) const { - return m_aranges.GetEntryAtIndex(idx); - } - void Dump(lldb_private::Log *log) const; dw_offset_t FindAddress(dw_addr_t address) const; @@ -57,8 +48,6 @@ return DW_INVALID_OFFSET; } - static void Dump(SymbolFileDWARF *dwarf2Data, lldb_private::Stream *s); - protected: RangeToDIE m_aranges; };
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp index dadc30d..100f35f 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp
@@ -1,9 +1,8 @@ //===-- DWARFDebugInfo.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,213 +15,183 @@ #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Stream.h" +#include "llvm/Support/Casting.h" #include "DWARFCompileUnit.h" -#include "DWARFDebugAranges.h" +#include "DWARFContext.h" #include "DWARFDebugAranges.h" #include "DWARFDebugInfo.h" #include "DWARFDebugInfoEntry.h" #include "DWARFFormValue.h" -#include "LogChannelDWARF.h" +#include "DWARFTypeUnit.h" using namespace lldb; using namespace lldb_private; using namespace std; -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- -DWARFDebugInfo::DWARFDebugInfo() - : m_dwarf2Data(NULL), m_compile_units(), m_cu_aranges_ap() {} +DWARFDebugInfo::DWARFDebugInfo(SymbolFileDWARF &dwarf, + lldb_private::DWARFContext &context) + : m_dwarf(dwarf), m_context(context), m_units(), m_cu_aranges_up() {} -//---------------------------------------------------------------------- -// SetDwarfData -//---------------------------------------------------------------------- -void DWARFDebugInfo::SetDwarfData(SymbolFileDWARF *dwarf2Data) { - m_dwarf2Data = dwarf2Data; - m_compile_units.clear(); -} +llvm::Expected<DWARFDebugAranges &> DWARFDebugInfo::GetCompileUnitAranges() { + if (m_cu_aranges_up) + return *m_cu_aranges_up; -DWARFDebugAranges &DWARFDebugInfo::GetCompileUnitAranges() { - if (m_cu_aranges_ap.get() == NULL && m_dwarf2Data) { - Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_ARANGES)); + m_cu_aranges_up = llvm::make_unique<DWARFDebugAranges>(); + const DWARFDataExtractor &debug_aranges_data = + m_context.getOrLoadArangesData(); + if (llvm::Error error = m_cu_aranges_up->extract(debug_aranges_data)) + return std::move(error); - m_cu_aranges_ap.reset(new DWARFDebugAranges()); - const DWARFDataExtractor &debug_aranges_data = - m_dwarf2Data->get_debug_aranges_data(); - if (debug_aranges_data.GetByteSize() > 0) { - if (log) - log->Printf( - "DWARFDebugInfo::GetCompileUnitAranges() for \"%s\" from " - ".debug_aranges", - m_dwarf2Data->GetObjectFile()->GetFileSpec().GetPath().c_str()); - m_cu_aranges_ap->Extract(debug_aranges_data); - } - - // Make a list of all CUs represented by the arange data in the file. - std::set<dw_offset_t> cus_with_data; - for (size_t n = 0; n < m_cu_aranges_ap.get()->GetNumRanges(); n++) { - dw_offset_t offset = m_cu_aranges_ap.get()->OffsetAtIndex(n); - if (offset != DW_INVALID_OFFSET) - cus_with_data.insert(offset); - } - - // Manually build arange data for everything that wasn't in the - // .debug_aranges table. - bool printed = false; - const size_t num_compile_units = GetNumCompileUnits(); - for (size_t idx = 0; idx < num_compile_units; ++idx) { - DWARFUnit *cu = GetCompileUnitAtIndex(idx); - - dw_offset_t offset = cu->GetOffset(); - if (cus_with_data.find(offset) == cus_with_data.end()) { - if (log) { - if (!printed) - log->Printf( - "DWARFDebugInfo::GetCompileUnitAranges() for \"%s\" by parsing", - m_dwarf2Data->GetObjectFile()->GetFileSpec().GetPath().c_str()); - printed = true; - } - cu->BuildAddressRangeTable(m_dwarf2Data, m_cu_aranges_ap.get()); - } - } - - const bool minimize = true; - m_cu_aranges_ap->Sort(minimize); + // Make a list of all CUs represented by the arange data in the file. + std::set<dw_offset_t> cus_with_data; + for (size_t n = 0; n < m_cu_aranges_up->GetNumRanges(); n++) { + dw_offset_t offset = m_cu_aranges_up->OffsetAtIndex(n); + if (offset != DW_INVALID_OFFSET) + cus_with_data.insert(offset); } - return *m_cu_aranges_ap.get(); + + // Manually build arange data for everything that wasn't in the + // .debug_aranges table. + const size_t num_units = GetNumUnits(); + for (size_t idx = 0; idx < num_units; ++idx) { + DWARFUnit *cu = GetUnitAtIndex(idx); + + dw_offset_t offset = cu->GetOffset(); + if (cus_with_data.find(offset) == cus_with_data.end()) + cu->BuildAddressRangeTable(m_cu_aranges_up.get()); + } + + const bool minimize = true; + m_cu_aranges_up->Sort(minimize); + return *m_cu_aranges_up; } -void DWARFDebugInfo::ParseCompileUnitHeadersIfNeeded() { - if (m_compile_units.empty()) { - if (m_dwarf2Data != NULL) { - lldb::offset_t offset = 0; - DWARFUnitSP cu_sp; - const auto &debug_info_data = m_dwarf2Data->get_debug_info_data(); - while ((cu_sp = DWARFCompileUnit::Extract(m_dwarf2Data, debug_info_data, - &offset))) { - m_compile_units.push_back(cu_sp); +void DWARFDebugInfo::ParseUnitsFor(DIERef::Section section) { + DWARFDataExtractor data = section == DIERef::Section::DebugTypes + ? m_context.getOrLoadDebugTypesData() + : m_context.getOrLoadDebugInfoData(); + lldb::offset_t offset = 0; + while (data.ValidOffset(offset)) { + llvm::Expected<DWARFUnitSP> unit_sp = + DWARFUnit::extract(m_dwarf, m_units.size(), data, section, &offset); - offset = cu_sp->GetNextCompileUnitOffset(); - } + if (!unit_sp) { + // FIXME: Propagate this error up. + llvm::consumeError(unit_sp.takeError()); + return; + } + + // If it didn't return an error, then it should be returning a valid Unit. + assert(*unit_sp); + m_units.push_back(*unit_sp); + offset = (*unit_sp)->GetNextUnitOffset(); + + if (auto *type_unit = llvm::dyn_cast<DWARFTypeUnit>(unit_sp->get())) { + m_type_hash_to_unit_index.emplace_back(type_unit->GetTypeHash(), + unit_sp.get()->GetID()); } } } -size_t DWARFDebugInfo::GetNumCompileUnits() { - ParseCompileUnitHeadersIfNeeded(); - return m_compile_units.size(); +void DWARFDebugInfo::ParseUnitHeadersIfNeeded() { + if (!m_units.empty()) + return; + + ParseUnitsFor(DIERef::Section::DebugInfo); + ParseUnitsFor(DIERef::Section::DebugTypes); + llvm::sort(m_type_hash_to_unit_index, llvm::less_first()); } -DWARFUnit *DWARFDebugInfo::GetCompileUnitAtIndex(uint32_t idx) { - DWARFUnit *cu = NULL; - if (idx < GetNumCompileUnits()) - cu = m_compile_units[idx].get(); +size_t DWARFDebugInfo::GetNumUnits() { + ParseUnitHeadersIfNeeded(); + return m_units.size(); +} + +DWARFUnit *DWARFDebugInfo::GetUnitAtIndex(user_id_t idx) { + DWARFUnit *cu = nullptr; + if (idx < GetNumUnits()) + cu = m_units[idx].get(); return cu; } -bool DWARFDebugInfo::ContainsCompileUnit(const DWARFUnit *cu) const { - // Not a verify efficient function, but it is handy for use in assertions to - // make sure that a compile unit comes from a debug information file. - CompileUnitColl::const_iterator end_pos = m_compile_units.end(); - CompileUnitColl::const_iterator pos; +uint32_t DWARFDebugInfo::FindUnitIndex(DIERef::Section section, + dw_offset_t offset) { + ParseUnitHeadersIfNeeded(); - for (pos = m_compile_units.begin(); pos != end_pos; ++pos) { - if (pos->get() == cu) - return true; - } - return false; + // llvm::lower_bound is not used as for DIE offsets it would still return + // index +1 and GetOffset() returning index itself would be a special case. + auto pos = llvm::upper_bound( + m_units, std::make_pair(section, offset), + [](const std::pair<DIERef::Section, dw_offset_t> &lhs, + const DWARFUnitSP &rhs) { + return lhs < std::make_pair(rhs->GetDebugSection(), rhs->GetOffset()); + }); + uint32_t idx = std::distance(m_units.begin(), pos); + if (idx == 0) + return DW_INVALID_OFFSET; + return idx - 1; } -bool DWARFDebugInfo::OffsetLessThanCompileUnitOffset( - dw_offset_t offset, const DWARFUnitSP &cu_sp) { - return offset < cu_sp->GetOffset(); -} - -DWARFUnit *DWARFDebugInfo::GetCompileUnit(dw_offset_t cu_offset, - uint32_t *idx_ptr) { - DWARFUnitSP cu_sp; - uint32_t cu_idx = DW_INVALID_INDEX; - if (cu_offset != DW_INVALID_OFFSET) { - ParseCompileUnitHeadersIfNeeded(); - - // Watch out for single compile unit executable as they are pretty common - const size_t num_cus = m_compile_units.size(); - if (num_cus == 1) { - if (m_compile_units[0]->GetOffset() == cu_offset) { - cu_sp = m_compile_units[0]; - cu_idx = 0; - } - } else if (num_cus) { - CompileUnitColl::const_iterator end_pos = m_compile_units.end(); - CompileUnitColl::const_iterator begin_pos = m_compile_units.begin(); - CompileUnitColl::const_iterator pos = std::upper_bound( - begin_pos, end_pos, cu_offset, OffsetLessThanCompileUnitOffset); - if (pos != begin_pos) { - --pos; - if ((*pos)->GetOffset() == cu_offset) { - cu_sp = *pos; - cu_idx = std::distance(begin_pos, pos); - } - } - } +DWARFUnit *DWARFDebugInfo::GetUnitAtOffset(DIERef::Section section, + dw_offset_t cu_offset, + uint32_t *idx_ptr) { + uint32_t idx = FindUnitIndex(section, cu_offset); + DWARFUnit *result = GetUnitAtIndex(idx); + if (result && result->GetOffset() != cu_offset) { + result = nullptr; + idx = DW_INVALID_INDEX; } if (idx_ptr) - *idx_ptr = cu_idx; - return cu_sp.get(); + *idx_ptr = idx; + return result; } -DWARFUnit *DWARFDebugInfo::GetCompileUnit(const DIERef &die_ref) { - if (die_ref.cu_offset == DW_INVALID_OFFSET) - return GetCompileUnitContainingDIEOffset(die_ref.die_offset); - else - return GetCompileUnit(die_ref.cu_offset); +DWARFUnit *DWARFDebugInfo::GetUnit(const DIERef &die_ref) { + return GetUnitContainingDIEOffset(die_ref.section(), die_ref.die_offset()); } DWARFUnit * -DWARFDebugInfo::GetCompileUnitContainingDIEOffset(dw_offset_t die_offset) { - ParseCompileUnitHeadersIfNeeded(); +DWARFDebugInfo::GetUnitContainingDIEOffset(DIERef::Section section, + dw_offset_t die_offset) { + uint32_t idx = FindUnitIndex(section, die_offset); + DWARFUnit *result = GetUnitAtIndex(idx); + if (result && !result->ContainsDIEOffset(die_offset)) + return nullptr; + return result; +} - DWARFUnitSP cu_sp; +DWARFTypeUnit *DWARFDebugInfo::GetTypeUnitForHash(uint64_t hash) { + auto pos = llvm::lower_bound(m_type_hash_to_unit_index, + std::make_pair(hash, 0u), llvm::less_first()); + if (pos == m_type_hash_to_unit_index.end() || pos->first != hash) + return nullptr; + return llvm::cast<DWARFTypeUnit>(GetUnitAtIndex(pos->second)); +} - // Watch out for single compile unit executable as they are pretty common - const size_t num_cus = m_compile_units.size(); - if (num_cus == 1) { - if (m_compile_units[0]->ContainsDIEOffset(die_offset)) - return m_compile_units[0].get(); - } else if (num_cus) { - CompileUnitColl::const_iterator end_pos = m_compile_units.end(); - CompileUnitColl::const_iterator begin_pos = m_compile_units.begin(); - CompileUnitColl::const_iterator pos = std::upper_bound( - begin_pos, end_pos, die_offset, OffsetLessThanCompileUnitOffset); - if (pos != begin_pos) { - --pos; - if ((*pos)->ContainsDIEOffset(die_offset)) - return (*pos).get(); - } - } - - return nullptr; +bool DWARFDebugInfo::ContainsTypeUnits() { + ParseUnitHeadersIfNeeded(); + return !m_type_hash_to_unit_index.empty(); } DWARFDIE -DWARFDebugInfo::GetDIEForDIEOffset(dw_offset_t die_offset) { - DWARFUnit *cu = GetCompileUnitContainingDIEOffset(die_offset); +DWARFDebugInfo::GetDIEForDIEOffset(DIERef::Section section, + dw_offset_t die_offset) { + DWARFUnit *cu = GetUnitContainingDIEOffset(section, die_offset); if (cu) return cu->GetDIE(die_offset); return DWARFDIE(); } -//---------------------------------------------------------------------- // GetDIE() // // Get the DIE (Debug Information Entry) with the specified offset. -//---------------------------------------------------------------------- DWARFDIE DWARFDebugInfo::GetDIE(const DIERef &die_ref) { - DWARFUnit *cu = GetCompileUnit(die_ref); + DWARFUnit *cu = GetUnit(die_ref); if (cu) - return cu->GetDIE(die_ref.die_offset); + return cu->GetDIE(die_ref.die_offset()); return DWARFDIE(); // Not found }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.h index fc6085f..d1b066f 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.h
@@ -1,9 +1,8 @@ //===-- DWARFDebugInfo.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,11 +12,17 @@ #include <map> #include <vector> -#include "DWARFUnit.h" #include "DWARFDIE.h" +#include "DWARFTypeUnit.h" +#include "DWARFUnit.h" #include "SymbolFileDWARF.h" #include "lldb/Core/STLUtils.h" #include "lldb/lldb-private.h" +#include "llvm/Support/Error.h" + +namespace lldb_private { +class DWARFContext; +} typedef std::multimap<const char *, dw_offset_t, CStringCompareFunctionObject> CStringToDIEMap; @@ -32,16 +37,20 @@ const dw_offset_t next_offset, const uint32_t depth, void *userData); - DWARFDebugInfo(); - void SetDwarfData(SymbolFileDWARF *dwarf2Data); + explicit DWARFDebugInfo(SymbolFileDWARF &dwarf, + lldb_private::DWARFContext &context); - size_t GetNumCompileUnits(); - bool ContainsCompileUnit(const DWARFUnit *cu) const; - DWARFUnit *GetCompileUnitAtIndex(uint32_t idx); - DWARFUnit *GetCompileUnit(dw_offset_t cu_offset, uint32_t *idx_ptr = NULL); - DWARFUnit *GetCompileUnitContainingDIEOffset(dw_offset_t die_offset); - DWARFUnit *GetCompileUnit(const DIERef &die_ref); - DWARFDIE GetDIEForDIEOffset(dw_offset_t die_offset); + size_t GetNumUnits(); + DWARFUnit *GetUnitAtIndex(lldb::user_id_t idx); + DWARFUnit *GetUnitAtOffset(DIERef::Section section, dw_offset_t cu_offset, + uint32_t *idx_ptr = nullptr); + DWARFUnit *GetUnitContainingDIEOffset(DIERef::Section section, + dw_offset_t die_offset); + DWARFUnit *GetUnit(const DIERef &die_ref); + DWARFTypeUnit *GetTypeUnitForHash(uint64_t hash); + bool ContainsTypeUnits(); + DWARFDIE GetDIEForDIEOffset(DIERef::Section section, + dw_offset_t die_offset); DWARFDIE GetDIE(const DIERef &die_ref); enum { @@ -51,26 +60,27 @@ (1 << 2) // Show all parent DIEs when dumping single DIEs }; - DWARFDebugAranges &GetCompileUnitAranges(); + llvm::Expected<DWARFDebugAranges &> GetCompileUnitAranges(); protected: - static bool OffsetLessThanCompileUnitOffset(dw_offset_t offset, - const DWARFUnitSP &cu_sp); + typedef std::vector<DWARFUnitSP> UnitColl; - typedef std::vector<DWARFUnitSP> CompileUnitColl; - - //---------------------------------------------------------------------- - // Member variables - //---------------------------------------------------------------------- - SymbolFileDWARF *m_dwarf2Data; - CompileUnitColl m_compile_units; + SymbolFileDWARF &m_dwarf; + lldb_private::DWARFContext &m_context; + UnitColl m_units; std::unique_ptr<DWARFDebugAranges> - m_cu_aranges_ap; // A quick address to compile unit table + m_cu_aranges_up; // A quick address to compile unit table + + std::vector<std::pair<uint64_t, uint32_t>> m_type_hash_to_unit_index; private: // All parsing needs to be done partially any managed by this class as // accessors are called. - void ParseCompileUnitHeadersIfNeeded(); + void ParseUnitHeadersIfNeeded(); + + void ParseUnitsFor(DIERef::Section section); + + uint32_t FindUnitIndex(DIERef::Section section, dw_offset_t offset); DISALLOW_COPY_AND_ASSIGN(DWARFDebugInfo); };
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp index 7531aea..2f55b7d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
@@ -1,9 +1,8 @@ //===-- DWARFDebugInfoEntry.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,19 +12,21 @@ #include <algorithm> +#include "llvm/Support/LEB128.h" + #include "lldb/Core/Module.h" #include "lldb/Expression/DWARFExpression.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/Stream.h" -#include "DWARFUnit.h" -#include "DWARFDIECollection.h" +#include "DWARFCompileUnit.h" #include "DWARFDebugAbbrev.h" #include "DWARFDebugAranges.h" #include "DWARFDebugInfo.h" #include "DWARFDebugRanges.h" #include "DWARFDeclContext.h" #include "DWARFFormValue.h" +#include "DWARFUnit.h" #include "SymbolFileDWARF.h" #include "SymbolFileDWARFDwo.h" @@ -33,14 +34,15 @@ using namespace std; extern int g_verbose; -bool DWARFDebugInfoEntry::FastExtract( - const DWARFDataExtractor &debug_info_data, const DWARFUnit *cu, - const DWARFFormValue::FixedFormSizes &fixed_form_sizes, - lldb::offset_t *offset_ptr) { +// Extract a debug info entry for a given DWARFUnit from the data +// starting at the offset in offset_ptr +bool DWARFDebugInfoEntry::Extract(const DWARFDataExtractor &data, + const DWARFUnit *cu, + lldb::offset_t *offset_ptr) { m_offset = *offset_ptr; m_parent_idx = 0; m_sibling_idx = 0; - const uint64_t abbr_idx = debug_info_data.GetULEB128(offset_ptr); + const uint64_t abbr_idx = data.GetULEB128(offset_ptr); lldbassert(abbr_idx <= UINT16_MAX); m_abbr_idx = abbr_idx; @@ -49,12 +51,9 @@ if (m_abbr_idx) { lldb::offset_t offset = *offset_ptr; - - const DWARFAbbreviationDeclaration *abbrevDecl = - cu->GetAbbreviations()->GetAbbreviationDeclaration(m_abbr_idx); - - if (abbrevDecl == NULL) { - cu->GetSymbolFileDWARF()->GetObjectFile()->GetModule()->ReportError( + const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu); + if (abbrevDecl == nullptr) { + cu->GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError( "{0x%8.8x}: invalid abbreviation code %u, please file a bug and " "attach the file at the start of this error message", m_offset, (unsigned)abbr_idx); @@ -64,16 +63,16 @@ } m_tag = abbrevDecl->Tag(); m_has_children = abbrevDecl->HasChildren(); - // Skip all data in the .debug_info for the attributes + // Skip all data in the .debug_info or .debug_types for the attributes const uint32_t numAttributes = abbrevDecl->NumAttributes(); uint32_t i; dw_form_t form; for (i = 0; i < numAttributes; ++i) { form = abbrevDecl->GetFormByIndexUnchecked(i); - - const uint8_t fixed_skip_size = fixed_form_sizes.GetSize(form); + llvm::Optional<uint8_t> fixed_skip_size = + DWARFFormValue::GetFixedSize(form, cu); if (fixed_skip_size) - offset += fixed_skip_size; + offset += *fixed_skip_size; else { bool form_is_indirect = false; do { @@ -81,24 +80,24 @@ uint32_t form_size = 0; switch (form) { // Blocks if inlined data that have a length field and the data bytes - // inlined in the .debug_info + // inlined in the .debug_info/.debug_types case DW_FORM_exprloc: case DW_FORM_block: - form_size = debug_info_data.GetULEB128(&offset); + form_size = data.GetULEB128(&offset); break; case DW_FORM_block1: - form_size = debug_info_data.GetU8_unchecked(&offset); + form_size = data.GetU8_unchecked(&offset); break; case DW_FORM_block2: - form_size = debug_info_data.GetU16_unchecked(&offset); + form_size = data.GetU16_unchecked(&offset); break; case DW_FORM_block4: - form_size = debug_info_data.GetU32_unchecked(&offset); + form_size = data.GetU32_unchecked(&offset); break; // Inlined NULL terminated C-strings case DW_FORM_string: - debug_info_data.GetCStr(&offset); + data.GetCStr(&offset); break; // Compile unit address sized values @@ -109,7 +108,7 @@ if (cu->GetVersion() <= 2) form_size = cu->GetAddressByteSize(); else - form_size = cu->IsDWARF64() ? 8 : 4; + form_size = 4; break; // 0 sized form @@ -164,20 +163,17 @@ case DW_FORM_GNU_addr_index: case DW_FORM_GNU_str_index: case DW_FORM_strx: - debug_info_data.Skip_LEB128(&offset); + data.Skip_LEB128(&offset); break; case DW_FORM_indirect: form_is_indirect = true; - form = debug_info_data.GetULEB128(&offset); + form = data.GetULEB128(&offset); break; case DW_FORM_strp: case DW_FORM_sec_offset: - if (cu->IsDWARF64()) - debug_info_data.GetU64(&offset); - else - debug_info_data.GetU32(&offset); + data.GetU32(&offset); break; case DW_FORM_implicit_const: @@ -204,233 +200,48 @@ return false; } -//---------------------------------------------------------------------- -// Extract -// -// Extract a debug info entry for a given compile unit from the .debug_info and -// .debug_abbrev data within the SymbolFileDWARF class starting at the given -// offset -//---------------------------------------------------------------------- -bool DWARFDebugInfoEntry::Extract(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, - lldb::offset_t *offset_ptr) { - const DWARFDataExtractor &debug_info_data = cu->GetData(); - // const DWARFDataExtractor& debug_str_data = - // dwarf2Data->get_debug_str_data(); - const uint32_t cu_end_offset = cu->GetNextCompileUnitOffset(); - lldb::offset_t offset = *offset_ptr; - // if (offset >= cu_end_offset) - // Log::Status("DIE at offset 0x%8.8x is beyond the end of the current - // compile unit (0x%8.8x)", m_offset, cu_end_offset); - if ((offset < cu_end_offset) && debug_info_data.ValidOffset(offset)) { - m_offset = offset; - - const uint64_t abbr_idx = debug_info_data.GetULEB128(&offset); - lldbassert(abbr_idx <= UINT16_MAX); - m_abbr_idx = abbr_idx; - if (abbr_idx) { - const DWARFAbbreviationDeclaration *abbrevDecl = - cu->GetAbbreviations()->GetAbbreviationDeclaration(abbr_idx); - - if (abbrevDecl) { - m_tag = abbrevDecl->Tag(); - m_has_children = abbrevDecl->HasChildren(); - - bool isCompileUnitTag = (m_tag == DW_TAG_compile_unit || - m_tag == DW_TAG_partial_unit); - if (cu && isCompileUnitTag) - const_cast<DWARFUnit *>(cu)->SetBaseAddress(0); - - // Skip all data in the .debug_info for the attributes - const uint32_t numAttributes = abbrevDecl->NumAttributes(); - for (uint32_t i = 0; i < numAttributes; ++i) { - DWARFFormValue form_value(cu); - dw_attr_t attr; - abbrevDecl->GetAttrAndFormValueByIndex(i, attr, form_value); - dw_form_t form = form_value.Form(); - - if (isCompileUnitTag && - ((attr == DW_AT_entry_pc) || (attr == DW_AT_low_pc))) { - if (form_value.ExtractValue(debug_info_data, &offset)) { - if (attr == DW_AT_low_pc || attr == DW_AT_entry_pc) - const_cast<DWARFUnit *>(cu)->SetBaseAddress( - form_value.Address()); - } - } else { - bool form_is_indirect = false; - do { - form_is_indirect = false; - uint32_t form_size = 0; - switch (form) { - // Blocks if inlined data that have a length field and the data - // bytes inlined in the .debug_info - case DW_FORM_exprloc: - case DW_FORM_block: - form_size = debug_info_data.GetULEB128(&offset); - break; - case DW_FORM_block1: - form_size = debug_info_data.GetU8(&offset); - break; - case DW_FORM_block2: - form_size = debug_info_data.GetU16(&offset); - break; - case DW_FORM_block4: - form_size = debug_info_data.GetU32(&offset); - break; - - // Inlined NULL terminated C-strings - case DW_FORM_string: - debug_info_data.GetCStr(&offset); - break; - - // Compile unit address sized values - case DW_FORM_addr: - form_size = cu->GetAddressByteSize(); - break; - case DW_FORM_ref_addr: - if (cu->GetVersion() <= 2) - form_size = cu->GetAddressByteSize(); - else - form_size = cu->IsDWARF64() ? 8 : 4; - break; - - // 0 sized form - case DW_FORM_flag_present: - case DW_FORM_implicit_const: - form_size = 0; - break; - - // 1 byte values - case DW_FORM_data1: - case DW_FORM_flag: - case DW_FORM_ref1: - form_size = 1; - break; - - // 2 byte values - case DW_FORM_data2: - case DW_FORM_ref2: - form_size = 2; - break; - - // 4 byte values - case DW_FORM_data4: - case DW_FORM_ref4: - form_size = 4; - break; - - // 8 byte values - case DW_FORM_data8: - case DW_FORM_ref8: - case DW_FORM_ref_sig8: - form_size = 8; - break; - - // signed or unsigned LEB 128 values - case DW_FORM_sdata: - case DW_FORM_udata: - case DW_FORM_ref_udata: - case DW_FORM_GNU_addr_index: - case DW_FORM_GNU_str_index: - debug_info_data.Skip_LEB128(&offset); - break; - - case DW_FORM_indirect: - form = debug_info_data.GetULEB128(&offset); - form_is_indirect = true; - break; - - case DW_FORM_strp: - case DW_FORM_sec_offset: - if (cu->IsDWARF64()) - debug_info_data.GetU64(&offset); - else - debug_info_data.GetU32(&offset); - break; - - default: - *offset_ptr = offset; - return false; - } - - offset += form_size; - } while (form_is_indirect); - } - } - *offset_ptr = offset; - return true; - } - } else { - m_tag = 0; - m_has_children = false; - *offset_ptr = offset; - return true; // NULL debug tag entry - } - } - - return false; +static DWARFRangeList GetRangesOrReportError(const DWARFUnit &unit, + const DWARFDebugInfoEntry &die, + const DWARFFormValue &value) { + llvm::Expected<DWARFRangeList> expected_ranges = + (value.Form() == DW_FORM_rnglistx) + ? unit.FindRnglistFromIndex(value.Unsigned()) + : unit.FindRnglistFromOffset(value.Unsigned()); + if (expected_ranges) + return std::move(*expected_ranges); + unit.GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError( + "{0x%8.8x}: DIE has DW_AT_ranges(0x%" PRIx64 ") attribute, but " + "range extraction failed (%s), please file a bug " + "and attach the file at the start of this error message", + die.GetOffset(), value.Unsigned(), + toString(expected_ranges.takeError()).c_str()); + return DWARFRangeList(); } -//---------------------------------------------------------------------- -// DumpAncestry -// -// Dumps all of a debug information entries parents up until oldest and all of -// it's attributes to the specified stream. -//---------------------------------------------------------------------- -void DWARFDebugInfoEntry::DumpAncestry(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, - const DWARFDebugInfoEntry *oldest, - Stream &s, - uint32_t recurse_depth) const { - const DWARFDebugInfoEntry *parent = GetParent(); - if (parent && parent != oldest) - parent->DumpAncestry(dwarf2Data, cu, oldest, s, 0); - Dump(dwarf2Data, cu, s, recurse_depth); -} - -static dw_offset_t GetRangesOffset(const DWARFDebugRangesBase *debug_ranges, - DWARFFormValue &form_value) { - if (form_value.Form() == DW_FORM_rnglistx) - return debug_ranges->GetOffset(form_value.Unsigned()); - return form_value.Unsigned(); -} - -//---------------------------------------------------------------------- // GetDIENamesAndRanges // // Gets the valid address ranges for a given DIE by looking for a // DW_AT_low_pc/DW_AT_high_pc pair, DW_AT_entry_pc, or DW_AT_ranges attributes. -//---------------------------------------------------------------------- bool DWARFDebugInfoEntry::GetDIENamesAndRanges( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, const char *&name, - const char *&mangled, DWARFRangeList &ranges, int &decl_file, - int &decl_line, int &decl_column, int &call_file, int &call_line, - int &call_column, DWARFExpression *frame_base) const { - if (dwarf2Data == nullptr) - return false; - - SymbolFileDWARFDwo *dwo_symbol_file = cu->GetDwoSymbolFile(); - if (dwo_symbol_file) - return GetDIENamesAndRanges( - dwo_symbol_file, dwo_symbol_file->GetCompileUnit(), name, mangled, - ranges, decl_file, decl_line, decl_column, call_file, call_line, - call_column, frame_base); - + const DWARFUnit *cu, const char *&name, const char *&mangled, + DWARFRangeList &ranges, int &decl_file, int &decl_line, int &decl_column, + int &call_file, int &call_line, int &call_column, + DWARFExpression *frame_base) const { dw_addr_t lo_pc = LLDB_INVALID_ADDRESS; dw_addr_t hi_pc = LLDB_INVALID_ADDRESS; - std::vector<DIERef> die_refs; + std::vector<DWARFDIE> dies; bool set_frame_base_loclist_addr = false; - lldb::offset_t offset; - const DWARFAbbreviationDeclaration *abbrevDecl = - GetAbbreviationDeclarationPtr(dwarf2Data, cu, offset); + const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu); - lldb::ModuleSP module = dwarf2Data->GetObjectFile()->GetModule(); + SymbolFileDWARF &dwarf = cu->GetSymbolFileDWARF(); + lldb::ModuleSP module = dwarf.GetObjectFile()->GetModule(); if (abbrevDecl) { - const DWARFDataExtractor &debug_info_data = cu->GetData(); + const DWARFDataExtractor &data = cu->GetData(); + lldb::offset_t offset = GetFirstAttributeOffset(); - if (!debug_info_data.ValidOffset(offset)) + if (!data.ValidOffset(offset)) return false; const uint32_t numAttributes = abbrevDecl->NumAttributes(); @@ -441,7 +252,7 @@ dw_attr_t attr; abbrevDecl->GetAttrAndFormValueByIndex(i, attr, form_value); - if (form_value.ExtractValue(debug_info_data, &offset)) { + if (form_value.ExtractValue(data, &offset)) { switch (attr) { case DW_AT_low_pc: lo_pc = form_value.Address(); @@ -457,6 +268,7 @@ case DW_AT_high_pc: if (form_value.Form() == DW_FORM_addr || + form_value.Form() == DW_FORM_addrx || form_value.Form() == DW_FORM_GNU_addr_index) { hi_pc = form_value.Address(); } else { @@ -469,35 +281,27 @@ } break; - case DW_AT_ranges: { - const DWARFDebugRangesBase *debug_ranges = dwarf2Data->DebugRanges(); - if (debug_ranges) - debug_ranges->FindRanges(cu, GetRangesOffset(debug_ranges, form_value), ranges); - else - cu->GetSymbolFileDWARF()->GetObjectFile()->GetModule()->ReportError( - "{0x%8.8x}: DIE has DW_AT_ranges(0x%" PRIx64 - ") attribute yet DWARF has no .debug_ranges, please file a bug " - "and attach the file at the start of this error message", - m_offset, form_value.Unsigned()); - } break; + case DW_AT_ranges: + ranges = GetRangesOrReportError(*cu, *this, form_value); + break; case DW_AT_name: - if (name == NULL) + if (name == nullptr) name = form_value.AsCString(); break; case DW_AT_MIPS_linkage_name: case DW_AT_linkage_name: - if (mangled == NULL) + if (mangled == nullptr) mangled = form_value.AsCString(); break; case DW_AT_abstract_origin: - die_refs.emplace_back(form_value); + dies.push_back(form_value.Reference()); break; case DW_AT_specification: - die_refs.emplace_back(form_value); + dies.push_back(form_value.Reference()); break; case DW_AT_decl_file: @@ -534,20 +338,20 @@ if (frame_base) { if (form_value.BlockData()) { uint32_t block_offset = - form_value.BlockData() - debug_info_data.GetDataStart(); + form_value.BlockData() - data.GetDataStart(); uint32_t block_length = form_value.Unsigned(); - frame_base->SetOpcodeData(module, debug_info_data, block_offset, - block_length); + *frame_base = DWARFExpression(module, data, cu, + block_offset, block_length); } else { - const DWARFDataExtractor &debug_loc_data = - dwarf2Data->DebugLocData(); + const DWARFDataExtractor &debug_loc_data = dwarf.DebugLocData(); const dw_offset_t debug_loc_offset = form_value.Unsigned(); size_t loc_list_length = DWARFExpression::LocationListSize( cu, debug_loc_data, debug_loc_offset); if (loc_list_length > 0) { - frame_base->SetOpcodeData(module, debug_loc_data, - debug_loc_offset, loc_list_length); + *frame_base = + DWARFExpression(module, debug_loc_data, cu, + debug_loc_offset, loc_list_length); if (lo_pc != LLDB_INVALID_ADDRESS) { assert(lo_pc >= cu->GetBaseAddress()); frame_base->SetLocationListSlide(lo_pc - @@ -582,56 +386,48 @@ frame_base->SetLocationListSlide(lowest_range_pc - cu->GetBaseAddress()); } - if (ranges.IsEmpty() || name == NULL || mangled == NULL) { - for (const DIERef &die_ref : die_refs) { - if (die_ref.die_offset != DW_INVALID_OFFSET) { - DWARFDIE die = dwarf2Data->GetDIE(die_ref); - if (die) - die.GetDIE()->GetDIENamesAndRanges( - die.GetDWARF(), die.GetCU(), name, mangled, ranges, decl_file, - decl_line, decl_column, call_file, call_line, call_column); + if (ranges.IsEmpty() || name == nullptr || mangled == nullptr) { + for (const DWARFDIE &die : dies) { + if (die) { + die.GetDIE()->GetDIENamesAndRanges(die.GetCU(), name, mangled, ranges, + decl_file, decl_line, decl_column, + call_file, call_line, call_column); } } } return !ranges.IsEmpty(); } -//---------------------------------------------------------------------- // Dump // // Dumps a debug information entry and all of it's attributes to the specified // stream. -//---------------------------------------------------------------------- -void DWARFDebugInfoEntry::Dump(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, Stream &s, +void DWARFDebugInfoEntry::Dump(const DWARFUnit *cu, Stream &s, uint32_t recurse_depth) const { - const DWARFDataExtractor &debug_info_data = cu->GetData(); + const DWARFDataExtractor &data = cu->GetData(); lldb::offset_t offset = m_offset; - if (debug_info_data.ValidOffset(offset)) { - dw_uleb128_t abbrCode = debug_info_data.GetULEB128(&offset); + if (data.ValidOffset(offset)) { + dw_uleb128_t abbrCode = data.GetULEB128(&offset); s.Printf("\n0x%8.8x: ", m_offset); s.Indent(); if (abbrCode != m_abbr_idx) { s.Printf("error: DWARF has been modified\n"); } else if (abbrCode) { - const DWARFAbbreviationDeclaration *abbrevDecl = - cu->GetAbbreviations()->GetAbbreviationDeclaration(abbrCode); - + const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu); if (abbrevDecl) { s.PutCString(DW_TAG_value_to_name(abbrevDecl->Tag())); s.Printf(" [%u] %c\n", abbrCode, abbrevDecl->HasChildren() ? '*' : ' '); - // Dump all data in the .debug_info for the attributes + // Dump all data in the .debug_info/.debug_types for the attributes const uint32_t numAttributes = abbrevDecl->NumAttributes(); for (uint32_t i = 0; i < numAttributes; ++i) { DWARFFormValue form_value(cu); dw_attr_t attr; abbrevDecl->GetAttrAndFormValueByIndex(i, attr, form_value); - DumpAttribute(dwarf2Data, cu, debug_info_data, &offset, s, attr, - form_value); + DumpAttribute(cu, data, &offset, s, attr, form_value); } const DWARFDebugInfoEntry *child = GetFirstChild(); @@ -639,7 +435,7 @@ s.IndentMore(); while (child) { - child->Dump(dwarf2Data, cu, s, recurse_depth - 1); + child->Dump(cu, s, recurse_depth - 1); child = child->GetSibling(); } s.IndentLess(); @@ -654,34 +450,15 @@ } } -void DWARFDebugInfoEntry::DumpLocation(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu, Stream &s) const { - const DWARFBaseDIE cu_die = cu->GetUnitDIEOnly(); - const char *cu_name = NULL; - if (cu_die) - cu_name = cu_die.GetName(); - const char *obj_file_name = NULL; - ObjectFile *obj_file = dwarf2Data->GetObjectFile(); - if (obj_file) - obj_file_name = - obj_file->GetFileSpec().GetFilename().AsCString("<Unknown>"); - const char *die_name = GetName(dwarf2Data, cu); - s.Printf("0x%8.8x/0x%8.8x: %-30s (from %s in %s)", cu->GetOffset(), - GetOffset(), die_name ? die_name : "", cu_name ? cu_name : "<NULL>", - obj_file_name ? obj_file_name : "<NULL>"); -} - -//---------------------------------------------------------------------- // DumpAttribute // // Dumps a debug information entry attribute along with it's form. Any special // display of attributes is done (disassemble location lists, show enumeration // values for attributes, etc). -//---------------------------------------------------------------------- void DWARFDebugInfoEntry::DumpAttribute( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const DWARFDataExtractor &debug_info_data, lldb::offset_t *offset_ptr, - Stream &s, dw_attr_t attr, DWARFFormValue &form_value) { + const DWARFUnit *cu, const DWARFDataExtractor &data, + lldb::offset_t *offset_ptr, Stream &s, dw_attr_t attr, + DWARFFormValue &form_value) { bool show_form = s.GetFlags().Test(DWARFDebugInfo::eDumpFlag_ShowForm); s.Printf(" "); @@ -691,7 +468,7 @@ s.Printf("[%s", DW_FORM_value_to_name(form_value.Form())); } - if (!form_value.ExtractValue(debug_info_data, offset_ptr)) + if (!form_value.ExtractValue(data, offset_ptr)) return; if (show_form) { @@ -704,6 +481,8 @@ s.PutCString("( "); + SymbolFileDWARF &dwarf = cu->GetSymbolFileDWARF(); + // Check to see if we have any special attribute formatters switch (attr) { case DW_AT_stmt_list: @@ -724,7 +503,7 @@ const uint8_t *blockData = form_value.BlockData(); if (blockData) { // Location description is inlined in data in the form value - DWARFDataExtractor locationData(debug_info_data, + DWARFDataExtractor locationData(data, (*offset_ptr) - form_value.Unsigned(), form_value.Unsigned()); DWARFExpression::PrintDWARFExpression( @@ -733,38 +512,26 @@ // We have a location list offset as the value that is the offset into // the .debug_loc section that describes the value over it's lifetime uint64_t debug_loc_offset = form_value.Unsigned(); - if (dwarf2Data) { - DWARFExpression::PrintDWARFLocationList( - s, cu, dwarf2Data->DebugLocData(), debug_loc_offset); - } + DWARFExpression::PrintDWARFLocationList(s, cu, dwarf.DebugLocData(), + debug_loc_offset); } } break; case DW_AT_abstract_origin: case DW_AT_specification: { - uint64_t abstract_die_offset = form_value.Reference(); + DWARFDIE abstract_die = form_value.Reference(); form_value.Dump(s); - // *ostrm_ptr << HEX32 << abstract_die_offset << " ( "; - GetName(dwarf2Data, cu, abstract_die_offset, s); + // *ostrm_ptr << HEX32 << abstract_die.GetOffset() << " ( "; + abstract_die.GetName(s); } break; case DW_AT_type: { - uint64_t type_die_offset = form_value.Reference(); + DWARFDIE type_die = form_value.Reference(); s.PutCString(" ( "); - AppendTypeName(dwarf2Data, cu, type_die_offset, s); + type_die.AppendTypeName(s); s.PutCString(" )"); } break; - case DW_AT_ranges: { - if (!dwarf2Data) - break; - lldb::offset_t ranges_offset = - GetRangesOffset(dwarf2Data->DebugRanges(), form_value); - dw_addr_t base_addr = cu ? cu->GetBaseAddress() : 0; - DWARFDebugRanges::Dump(s, dwarf2Data->get_debug_ranges_data(), - &ranges_offset, base_addr); - } break; - default: break; } @@ -772,36 +539,17 @@ s.PutCString(" )\n"); } -//---------------------------------------------------------------------- // Get all attribute values for a given DIE, including following any // specification or abstract origin attributes and including those in the // results. Any duplicate attributes will have the first instance take // precedence (this can happen for declaration attributes). -//---------------------------------------------------------------------- size_t DWARFDebugInfoEntry::GetAttributes( - const DWARFUnit *cu, DWARFFormValue::FixedFormSizes fixed_form_sizes, - DWARFAttributes &attributes, uint32_t curr_depth) const { - SymbolFileDWARF *dwarf2Data = nullptr; - const DWARFAbbreviationDeclaration *abbrevDecl = nullptr; - lldb::offset_t offset = 0; - if (cu) { - if (m_tag != DW_TAG_compile_unit && m_tag != DW_TAG_partial_unit) { - SymbolFileDWARFDwo *dwo_symbol_file = cu->GetDwoSymbolFile(); - if (dwo_symbol_file) - return GetAttributes(dwo_symbol_file->GetCompileUnit(), - fixed_form_sizes, attributes, curr_depth); - } - - dwarf2Data = cu->GetSymbolFileDWARF(); - abbrevDecl = GetAbbreviationDeclarationPtr(dwarf2Data, cu, offset); - } - + const DWARFUnit *cu, DWARFAttributes &attributes, + uint32_t curr_depth) const { + const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu); if (abbrevDecl) { - const DWARFDataExtractor &debug_info_data = cu->GetData(); - - if (fixed_form_sizes.Empty()) - fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize( - cu->GetAddressByteSize(), cu->IsDWARF64()); + const DWARFDataExtractor &data = cu->GetData(); + lldb::offset_t offset = GetFirstAttributeOffset(); const uint32_t num_attributes = abbrevDecl->NumAttributes(); for (uint32_t i = 0; i < num_attributes; ++i) { @@ -829,19 +577,17 @@ } if ((attr == DW_AT_specification) || (attr == DW_AT_abstract_origin)) { - if (form_value.ExtractValue(debug_info_data, &offset)) { - dw_offset_t die_offset = form_value.Reference(); - DWARFDIE spec_die = - const_cast<DWARFUnit *>(cu)->GetDIE(die_offset); + if (form_value.ExtractValue(data, &offset)) { + DWARFDIE spec_die = form_value.Reference(); if (spec_die) spec_die.GetAttributes(attributes, curr_depth + 1); } } else { - const uint8_t fixed_skip_size = fixed_form_sizes.GetSize(form); + llvm::Optional<uint8_t> fixed_skip_size = DWARFFormValue::GetFixedSize(form, cu); if (fixed_skip_size) - offset += fixed_skip_size; + offset += *fixed_skip_size; else - DWARFFormValue::SkipValue(form, debug_info_data, &offset, cu); + DWARFFormValue::SkipValue(form, data, &offset, cu); } } } else { @@ -850,45 +596,32 @@ return attributes.Size(); } -//---------------------------------------------------------------------- // GetAttributeValue // -// Get the value of an attribute and return the .debug_info offset of the -// attribute if it was properly extracted into form_value, or zero if we fail -// since an offset of zero is invalid for an attribute (it would be a compile -// unit header). -//---------------------------------------------------------------------- +// Get the value of an attribute and return the .debug_info or .debug_types +// offset of the attribute if it was properly extracted into form_value, +// or zero if we fail since an offset of zero is invalid for an attribute (it +// would be a compile unit header). dw_offset_t DWARFDebugInfoEntry::GetAttributeValue( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, DWARFFormValue &form_value, + const DWARFUnit *cu, const dw_attr_t attr, DWARFFormValue &form_value, dw_offset_t *end_attr_offset_ptr, bool check_specification_or_abstract_origin) const { - SymbolFileDWARFDwo *dwo_symbol_file = cu->GetDwoSymbolFile(); - if (dwo_symbol_file && m_tag != DW_TAG_compile_unit && - m_tag != DW_TAG_partial_unit) - return GetAttributeValue(dwo_symbol_file, dwo_symbol_file->GetCompileUnit(), - attr, form_value, end_attr_offset_ptr, - check_specification_or_abstract_origin); - - lldb::offset_t offset; - const DWARFAbbreviationDeclaration *abbrevDecl = - GetAbbreviationDeclarationPtr(dwarf2Data, cu, offset); - - if (abbrevDecl) { + if (const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu)) { uint32_t attr_idx = abbrevDecl->FindAttributeIndex(attr); if (attr_idx != DW_INVALID_INDEX) { - const DWARFDataExtractor &debug_info_data = cu->GetData(); + const DWARFDataExtractor &data = cu->GetData(); + lldb::offset_t offset = GetFirstAttributeOffset(); uint32_t idx = 0; while (idx < attr_idx) DWARFFormValue::SkipValue(abbrevDecl->GetFormByIndex(idx++), - debug_info_data, &offset, cu); + data, &offset, cu); const dw_offset_t attr_offset = offset; - form_value.SetCompileUnit(cu); + form_value.SetUnit(cu); form_value.SetForm(abbrevDecl->GetFormByIndex(idx)); - if (form_value.ExtractValue(debug_info_data, &offset)) { + if (form_value.ExtractValue(data, &offset)) { if (end_attr_offset_ptr) *end_attr_offset_ptr = offset; return attr_offset; @@ -897,35 +630,35 @@ } if (check_specification_or_abstract_origin) { - if (GetAttributeValue(dwarf2Data, cu, DW_AT_specification, form_value)) { - DWARFDIE die = - const_cast<DWARFUnit *>(cu)->GetDIE(form_value.Reference()); + if (GetAttributeValue(cu, DW_AT_specification, form_value)) { + DWARFDIE die = form_value.Reference(); if (die) { dw_offset_t die_offset = die.GetDIE()->GetAttributeValue( - die.GetDWARF(), die.GetCU(), attr, form_value, end_attr_offset_ptr, - false); + die.GetCU(), attr, form_value, end_attr_offset_ptr, false); if (die_offset) return die_offset; } } - if (GetAttributeValue(dwarf2Data, cu, DW_AT_abstract_origin, form_value)) { - DWARFDIE die = - const_cast<DWARFUnit *>(cu)->GetDIE(form_value.Reference()); + if (GetAttributeValue(cu, DW_AT_abstract_origin, form_value)) { + DWARFDIE die = form_value.Reference(); if (die) { dw_offset_t die_offset = die.GetDIE()->GetAttributeValue( - die.GetDWARF(), die.GetCU(), attr, form_value, end_attr_offset_ptr, - false); + die.GetCU(), attr, form_value, end_attr_offset_ptr, false); if (die_offset) return die_offset; } } } + // If we're a unit DIE, also check the attributes of the dwo unit (if any). + if (GetParent()) + return 0; + SymbolFileDWARFDwo *dwo_symbol_file = cu->GetDwoSymbolFile(); if (!dwo_symbol_file) return 0; - DWARFUnit *dwo_cu = dwo_symbol_file->GetCompileUnit(); + DWARFCompileUnit *dwo_cu = dwo_symbol_file->GetCompileUnit(); if (!dwo_cu) return 0; @@ -934,105 +667,78 @@ return 0; return dwo_cu_die.GetDIE()->GetAttributeValue( - dwo_symbol_file, dwo_cu, attr, form_value, end_attr_offset_ptr, + dwo_cu, attr, form_value, end_attr_offset_ptr, check_specification_or_abstract_origin); } -//---------------------------------------------------------------------- // GetAttributeValueAsString // // Get the value of an attribute as a string return it. The resulting pointer // to the string data exists within the supplied SymbolFileDWARF and will only // be available as long as the SymbolFileDWARF is still around and it's content // doesn't change. -//---------------------------------------------------------------------- const char *DWARFDebugInfoEntry::GetAttributeValueAsString( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, const char *fail_value, + const DWARFUnit *cu, const dw_attr_t attr, const char *fail_value, bool check_specification_or_abstract_origin) const { DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, attr, form_value, nullptr, + if (GetAttributeValue(cu, attr, form_value, nullptr, check_specification_or_abstract_origin)) return form_value.AsCString(); return fail_value; } -//---------------------------------------------------------------------- // GetAttributeValueAsUnsigned // // Get the value of an attribute as unsigned and return it. -//---------------------------------------------------------------------- uint64_t DWARFDebugInfoEntry::GetAttributeValueAsUnsigned( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, uint64_t fail_value, + const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value, bool check_specification_or_abstract_origin) const { DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, attr, form_value, nullptr, + if (GetAttributeValue(cu, attr, form_value, nullptr, check_specification_or_abstract_origin)) return form_value.Unsigned(); return fail_value; } -//---------------------------------------------------------------------- -// GetAttributeValueAsSigned -// -// Get the value of an attribute a signed value and return it. -//---------------------------------------------------------------------- -int64_t DWARFDebugInfoEntry::GetAttributeValueAsSigned( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, int64_t fail_value, - bool check_specification_or_abstract_origin) const { - DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, attr, form_value, nullptr, - check_specification_or_abstract_origin)) - return form_value.Signed(); - return fail_value; -} - -//---------------------------------------------------------------------- // GetAttributeValueAsReference // // Get the value of an attribute as reference and fix up and compile unit // relative offsets as needed. -//---------------------------------------------------------------------- -uint64_t DWARFDebugInfoEntry::GetAttributeValueAsReference( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, uint64_t fail_value, +DWARFDIE DWARFDebugInfoEntry::GetAttributeValueAsReference( + const DWARFUnit *cu, const dw_attr_t attr, bool check_specification_or_abstract_origin) const { DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, attr, form_value, nullptr, + if (GetAttributeValue(cu, attr, form_value, nullptr, check_specification_or_abstract_origin)) return form_value.Reference(); - return fail_value; + return {}; } uint64_t DWARFDebugInfoEntry::GetAttributeValueAsAddress( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, uint64_t fail_value, + const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value, bool check_specification_or_abstract_origin) const { DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, attr, form_value, nullptr, + if (GetAttributeValue(cu, attr, form_value, nullptr, check_specification_or_abstract_origin)) return form_value.Address(); return fail_value; } -//---------------------------------------------------------------------- // GetAttributeHighPC // // Get the hi_pc, adding hi_pc to lo_pc when specified as an <offset-from-low- // pc>. // // Returns the hi_pc or fail_value. -//---------------------------------------------------------------------- dw_addr_t DWARFDebugInfoEntry::GetAttributeHighPC( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, dw_addr_t lo_pc, - uint64_t fail_value, bool check_specification_or_abstract_origin) const { + const DWARFUnit *cu, dw_addr_t lo_pc, uint64_t fail_value, + bool check_specification_or_abstract_origin) const { DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, DW_AT_high_pc, form_value, nullptr, + if (GetAttributeValue(cu, DW_AT_high_pc, form_value, nullptr, check_specification_or_abstract_origin)) { dw_form_t form = form_value.Form(); - if (form == DW_FORM_addr || form == DW_FORM_GNU_addr_index) + if (form == DW_FORM_addr || form == DW_FORM_addrx || + form == DW_FORM_GNU_addr_index) return form_value.Address(); // DWARF4 can specify the hi_pc as an <offset-from-lowpc> @@ -1041,22 +747,19 @@ return fail_value; } -//---------------------------------------------------------------------- // GetAttributeAddressRange // // Get the lo_pc and hi_pc, adding hi_pc to lo_pc when specified as an <offset- // from-low-pc>. // // Returns true or sets lo_pc and hi_pc to fail_value. -//---------------------------------------------------------------------- bool DWARFDebugInfoEntry::GetAttributeAddressRange( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, dw_addr_t &lo_pc, - dw_addr_t &hi_pc, uint64_t fail_value, - bool check_specification_or_abstract_origin) const { - lo_pc = GetAttributeValueAsAddress(dwarf2Data, cu, DW_AT_low_pc, fail_value, + const DWARFUnit *cu, dw_addr_t &lo_pc, dw_addr_t &hi_pc, + uint64_t fail_value, bool check_specification_or_abstract_origin) const { + lo_pc = GetAttributeValueAsAddress(cu, DW_AT_low_pc, fail_value, check_specification_or_abstract_origin); if (lo_pc != fail_value) { - hi_pc = GetAttributeHighPC(dwarf2Data, cu, lo_pc, fail_value, + hi_pc = GetAttributeHighPC(cu, lo_pc, fail_value, check_specification_or_abstract_origin); if (hi_pc != fail_value) return true; @@ -1067,21 +770,17 @@ } size_t DWARFDebugInfoEntry::GetAttributeAddressRanges( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - DWARFRangeList &ranges, bool check_hi_lo_pc, + const DWARFUnit *cu, DWARFRangeList &ranges, bool check_hi_lo_pc, bool check_specification_or_abstract_origin) const { ranges.Clear(); DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, DW_AT_ranges, form_value)) { - if (DWARFDebugRangesBase *debug_ranges = dwarf2Data->DebugRanges()) - debug_ranges->FindRanges(cu, GetRangesOffset(debug_ranges, form_value), - ranges); + if (GetAttributeValue(cu, DW_AT_ranges, form_value)) { + ranges = GetRangesOrReportError(*cu, *this, form_value); } else if (check_hi_lo_pc) { dw_addr_t lo_pc = LLDB_INVALID_ADDRESS; dw_addr_t hi_pc = LLDB_INVALID_ADDRESS; - if (GetAttributeAddressRange(dwarf2Data, cu, lo_pc, hi_pc, - LLDB_INVALID_ADDRESS, + if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS, check_specification_or_abstract_origin)) { if (lo_pc < hi_pc) ranges.Append(DWARFRangeList::Entry(lo_pc, hi_pc - lo_pc)); @@ -1090,250 +789,67 @@ return ranges.GetSize(); } -//---------------------------------------------------------------------- // GetName // // Get value of the DW_AT_name attribute and return it if one exists, else // return NULL. -//---------------------------------------------------------------------- -const char *DWARFDebugInfoEntry::GetName(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu) const { - return GetAttributeValueAsString(dwarf2Data, cu, DW_AT_name, nullptr, true); +const char *DWARFDebugInfoEntry::GetName(const DWARFUnit *cu) const { + return GetAttributeValueAsString(cu, DW_AT_name, nullptr, true); } -//---------------------------------------------------------------------- // GetMangledName // // Get value of the DW_AT_MIPS_linkage_name attribute and return it if one // exists, else return the value of the DW_AT_name attribute -//---------------------------------------------------------------------- const char * -DWARFDebugInfoEntry::GetMangledName(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, +DWARFDebugInfoEntry::GetMangledName(const DWARFUnit *cu, bool substitute_name_allowed) const { const char *name = nullptr; - name = GetAttributeValueAsString(dwarf2Data, cu, DW_AT_MIPS_linkage_name, - nullptr, true); + name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true); if (name) return name; - name = GetAttributeValueAsString(dwarf2Data, cu, DW_AT_linkage_name, nullptr, - true); + name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true); if (name) return name; if (!substitute_name_allowed) return nullptr; - name = GetAttributeValueAsString(dwarf2Data, cu, DW_AT_name, nullptr, true); + name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true); return name; } -//---------------------------------------------------------------------- // GetPubname // // Get value the name for a DIE as it should appear for a .debug_pubnames or // .debug_pubtypes section. -//---------------------------------------------------------------------- -const char *DWARFDebugInfoEntry::GetPubname(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu) const { +const char *DWARFDebugInfoEntry::GetPubname(const DWARFUnit *cu) const { const char *name = nullptr; - if (!dwarf2Data) + if (!cu) return name; - name = GetAttributeValueAsString(dwarf2Data, cu, DW_AT_MIPS_linkage_name, - nullptr, true); + name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true); if (name) return name; - name = GetAttributeValueAsString(dwarf2Data, cu, DW_AT_linkage_name, nullptr, - true); + name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true); if (name) return name; - name = GetAttributeValueAsString(dwarf2Data, cu, DW_AT_name, nullptr, true); + name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true); return name; } -//---------------------------------------------------------------------- -// GetName -// -// Get value of the DW_AT_name attribute for a debug information entry that -// exists at offset "die_offset" and place that value into the supplied stream -// object. If the DIE is a NULL object "NULL" is placed into the stream, and if -// no DW_AT_name attribute exists for the DIE then nothing is printed. -//---------------------------------------------------------------------- -bool DWARFDebugInfoEntry::GetName(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, - const dw_offset_t die_offset, Stream &s) { - if (dwarf2Data == NULL) { - s.PutCString("NULL"); - return false; - } - - DWARFDebugInfoEntry die; - lldb::offset_t offset = die_offset; - if (die.Extract(dwarf2Data, cu, &offset)) { - if (die.IsNULL()) { - s.PutCString("NULL"); - return true; - } else { - const char *name = die.GetAttributeValueAsString( - dwarf2Data, cu, DW_AT_name, nullptr, true); - if (name) { - s.PutCString(name); - return true; - } - } - } - return false; -} - -//---------------------------------------------------------------------- -// AppendTypeName -// -// Follows the type name definition down through all needed tags to end up with -// a fully qualified type name and dump the results to the supplied stream. -// This is used to show the name of types given a type identifier. -//---------------------------------------------------------------------- -bool DWARFDebugInfoEntry::AppendTypeName(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, - const dw_offset_t die_offset, - Stream &s) { - if (dwarf2Data == NULL) { - s.PutCString("NULL"); - return false; - } - - DWARFDebugInfoEntry die; - lldb::offset_t offset = die_offset; - if (die.Extract(dwarf2Data, cu, &offset)) { - if (die.IsNULL()) { - s.PutCString("NULL"); - return true; - } else { - const char *name = die.GetPubname(dwarf2Data, cu); - if (name) - s.PutCString(name); - else { - bool result = true; - const DWARFAbbreviationDeclaration *abbrevDecl = - die.GetAbbreviationDeclarationPtr(dwarf2Data, cu, offset); - - if (abbrevDecl == NULL) - return false; - - switch (abbrevDecl->Tag()) { - case DW_TAG_array_type: - break; // print out a "[]" after printing the full type of the element - // below - case DW_TAG_base_type: - s.PutCString("base "); - break; - case DW_TAG_class_type: - s.PutCString("class "); - break; - case DW_TAG_const_type: - s.PutCString("const "); - break; - case DW_TAG_enumeration_type: - s.PutCString("enum "); - break; - case DW_TAG_file_type: - s.PutCString("file "); - break; - case DW_TAG_interface_type: - s.PutCString("interface "); - break; - case DW_TAG_packed_type: - s.PutCString("packed "); - break; - case DW_TAG_pointer_type: - break; // print out a '*' after printing the full type below - case DW_TAG_ptr_to_member_type: - break; // print out a '*' after printing the full type below - case DW_TAG_reference_type: - break; // print out a '&' after printing the full type below - case DW_TAG_restrict_type: - s.PutCString("restrict "); - break; - case DW_TAG_set_type: - s.PutCString("set "); - break; - case DW_TAG_shared_type: - s.PutCString("shared "); - break; - case DW_TAG_string_type: - s.PutCString("string "); - break; - case DW_TAG_structure_type: - s.PutCString("struct "); - break; - case DW_TAG_subrange_type: - s.PutCString("subrange "); - break; - case DW_TAG_subroutine_type: - s.PutCString("function "); - break; - case DW_TAG_thrown_type: - s.PutCString("thrown "); - break; - case DW_TAG_union_type: - s.PutCString("union "); - break; - case DW_TAG_unspecified_type: - s.PutCString("unspecified "); - break; - case DW_TAG_volatile_type: - s.PutCString("volatile "); - break; - default: - return false; - } - - // Follow the DW_AT_type if possible - DWARFFormValue form_value; - if (die.GetAttributeValue(dwarf2Data, cu, DW_AT_type, form_value)) { - uint64_t next_die_offset = form_value.Reference(); - result = AppendTypeName(dwarf2Data, cu, next_die_offset, s); - } - - switch (abbrevDecl->Tag()) { - case DW_TAG_array_type: - s.PutCString("[]"); - break; - case DW_TAG_pointer_type: - s.PutChar('*'); - break; - case DW_TAG_ptr_to_member_type: - s.PutChar('*'); - break; - case DW_TAG_reference_type: - s.PutChar('&'); - break; - default: - break; - } - return result; - } - } - } - return false; -} - -//---------------------------------------------------------------------- // BuildAddressRangeTable -//---------------------------------------------------------------------- void DWARFDebugInfoEntry::BuildAddressRangeTable( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - DWARFDebugAranges *debug_aranges) const { + const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const { if (m_tag) { if (m_tag == DW_TAG_subprogram) { dw_addr_t lo_pc = LLDB_INVALID_ADDRESS; dw_addr_t hi_pc = LLDB_INVALID_ADDRESS; - if (GetAttributeAddressRange(dwarf2Data, cu, lo_pc, hi_pc, - LLDB_INVALID_ADDRESS)) { + if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) { /// printf("BuildAddressRangeTable() 0x%8.8x: %30s: [0x%8.8x - /// 0x%8.8x)\n", m_offset, DW_TAG_value_to_name(tag), lo_pc, hi_pc); debug_aranges->AppendRange(cu->GetOffset(), lo_pc, hi_pc); @@ -1342,29 +858,25 @@ const DWARFDebugInfoEntry *child = GetFirstChild(); while (child) { - child->BuildAddressRangeTable(dwarf2Data, cu, debug_aranges); + child->BuildAddressRangeTable(cu, debug_aranges); child = child->GetSibling(); } } } -//---------------------------------------------------------------------- // BuildFunctionAddressRangeTable // // This function is very similar to the BuildAddressRangeTable function except // that the actual DIE offset for the function is placed in the table instead // of the compile unit offset (which is the way the standard .debug_aranges // section does it). -//---------------------------------------------------------------------- void DWARFDebugInfoEntry::BuildFunctionAddressRangeTable( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - DWARFDebugAranges *debug_aranges) const { + const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const { if (m_tag) { if (m_tag == DW_TAG_subprogram) { dw_addr_t lo_pc = LLDB_INVALID_ADDRESS; dw_addr_t hi_pc = LLDB_INVALID_ADDRESS; - if (GetAttributeAddressRange(dwarf2Data, cu, lo_pc, hi_pc, - LLDB_INVALID_ADDRESS)) { + if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) { // printf("BuildAddressRangeTable() 0x%8.8x: [0x%16.16" PRIx64 " - // 0x%16.16" PRIx64 ")\n", m_offset, lo_pc, hi_pc); // DEBUG ONLY debug_aranges->AppendRange(GetOffset(), lo_pc, hi_pc); @@ -1373,57 +885,37 @@ const DWARFDebugInfoEntry *child = GetFirstChild(); while (child) { - child->BuildFunctionAddressRangeTable(dwarf2Data, cu, debug_aranges); + child->BuildFunctionAddressRangeTable(cu, debug_aranges); child = child->GetSibling(); } } } -void DWARFDebugInfoEntry::GetDeclContextDIEs( - DWARFUnit *cu, DWARFDIECollection &decl_context_dies) const { - - DWARFDIE die(cu, const_cast<DWARFDebugInfoEntry *>(this)); - die.GetDeclContextDIEs(decl_context_dies); -} - void DWARFDebugInfoEntry::GetDWARFDeclContext( - SymbolFileDWARF *dwarf2Data, DWARFUnit *cu, - DWARFDeclContext &dwarf_decl_ctx) const { + DWARFUnit *cu, DWARFDeclContext &dwarf_decl_ctx) const { const dw_tag_t tag = Tag(); if (tag != DW_TAG_compile_unit && tag != DW_TAG_partial_unit) { - dwarf_decl_ctx.AppendDeclContext(tag, GetName(dwarf2Data, cu)); - DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(dwarf2Data, cu); + dwarf_decl_ctx.AppendDeclContext(tag, GetName(cu)); + DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu); if (parent_decl_ctx_die && parent_decl_ctx_die.GetDIE() != this) { if (parent_decl_ctx_die.Tag() != DW_TAG_compile_unit && parent_decl_ctx_die.Tag() != DW_TAG_partial_unit) parent_decl_ctx_die.GetDIE()->GetDWARFDeclContext( - parent_decl_ctx_die.GetDWARF(), parent_decl_ctx_die.GetCU(), - dwarf_decl_ctx); + parent_decl_ctx_die.GetCU(), dwarf_decl_ctx); } } } -bool DWARFDebugInfoEntry::MatchesDWARFDeclContext( - SymbolFileDWARF *dwarf2Data, DWARFUnit *cu, - const DWARFDeclContext &dwarf_decl_ctx) const { - - DWARFDeclContext this_dwarf_decl_ctx; - GetDWARFDeclContext(dwarf2Data, cu, this_dwarf_decl_ctx); - return this_dwarf_decl_ctx == dwarf_decl_ctx; -} - DWARFDIE -DWARFDebugInfoEntry::GetParentDeclContextDIE(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu) const { +DWARFDebugInfoEntry::GetParentDeclContextDIE(DWARFUnit *cu) const { DWARFAttributes attributes; - GetAttributes(cu, DWARFFormValue::FixedFormSizes(), attributes); - return GetParentDeclContextDIE(dwarf2Data, cu, attributes); + GetAttributes(cu, attributes); + return GetParentDeclContextDIE(cu, attributes); } DWARFDIE DWARFDebugInfoEntry::GetParentDeclContextDIE( - SymbolFileDWARF *dwarf2Data, DWARFUnit *cu, - const DWARFAttributes &attributes) const { + DWARFUnit *cu, const DWARFAttributes &attributes) const { DWARFDIE die(cu, const_cast<DWARFDebugInfoEntry *>(this)); while (die) { @@ -1445,28 +937,18 @@ } } - dw_offset_t die_offset; - - die_offset = - attributes.FormValueAsUnsigned(DW_AT_specification, DW_INVALID_OFFSET); - if (die_offset != DW_INVALID_OFFSET) { - DWARFDIE spec_die = cu->GetDIE(die_offset); - if (spec_die) { - DWARFDIE decl_ctx_die = spec_die.GetParentDeclContextDIE(); - if (decl_ctx_die) - return decl_ctx_die; - } + DWARFDIE spec_die = attributes.FormValueAsReference(DW_AT_specification); + if (spec_die) { + DWARFDIE decl_ctx_die = spec_die.GetParentDeclContextDIE(); + if (decl_ctx_die) + return decl_ctx_die; } - die_offset = attributes.FormValueAsUnsigned(DW_AT_abstract_origin, - DW_INVALID_OFFSET); - if (die_offset != DW_INVALID_OFFSET) { - DWARFDIE abs_die = cu->GetDIE(die_offset); - if (abs_die) { - DWARFDIE decl_ctx_die = abs_die.GetParentDeclContextDIE(); - if (decl_ctx_die) - return decl_ctx_die; - } + DWARFDIE abs_die = attributes.FormValueAsReference(DW_AT_abstract_origin); + if (abs_die) { + DWARFDIE decl_ctx_die = abs_die.GetParentDeclContextDIE(); + if (decl_ctx_die) + return decl_ctx_die; } die = die.GetParent(); @@ -1474,22 +956,22 @@ return DWARFDIE(); } -const char *DWARFDebugInfoEntry::GetQualifiedName(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu, +const char *DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu, std::string &storage) const { DWARFAttributes attributes; - GetAttributes(cu, DWARFFormValue::FixedFormSizes(), attributes); - return GetQualifiedName(dwarf2Data, cu, attributes, storage); + GetAttributes(cu, attributes); + return GetQualifiedName(cu, attributes, storage); } -const char *DWARFDebugInfoEntry::GetQualifiedName( - SymbolFileDWARF *dwarf2Data, DWARFUnit *cu, - const DWARFAttributes &attributes, std::string &storage) const { +const char * +DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu, + const DWARFAttributes &attributes, + std::string &storage) const { - const char *name = GetName(dwarf2Data, cu); + const char *name = GetName(cu); if (name) { - DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(dwarf2Data, cu); + DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu); storage.clear(); // TODO: change this to get the correct decl context parent.... while (parent_decl_ctx_die) { @@ -1530,15 +1012,11 @@ storage.append(name); } if (storage.empty()) - return NULL; + return nullptr; return storage.c_str(); } -//---------------------------------------------------------------------- -// LookupAddress -//---------------------------------------------------------------------- bool DWARFDebugInfoEntry::LookupAddress(const dw_addr_t address, - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, DWARFDebugInfoEntry **function_die, DWARFDebugInfoEntry **block_die) { @@ -1555,13 +1033,9 @@ check_children = true; break; case DW_TAG_entry_point: - break; case DW_TAG_enumeration_type: - break; case DW_TAG_formal_parameter: - break; case DW_TAG_imported_declaration: - break; case DW_TAG_label: break; case DW_TAG_lexical_block: @@ -1569,9 +1043,7 @@ match_addr_range = true; break; case DW_TAG_member: - break; case DW_TAG_pointer_type: - break; case DW_TAG_reference_type: break; case DW_TAG_compile_unit: @@ -1583,20 +1055,15 @@ check_children = true; break; case DW_TAG_subroutine_type: - break; case DW_TAG_typedef: - break; case DW_TAG_union_type: - break; case DW_TAG_unspecified_parameters: - break; case DW_TAG_variant: break; case DW_TAG_common_block: check_children = true; break; case DW_TAG_common_inclusion: - break; case DW_TAG_inheritance: break; case DW_TAG_inlined_subroutine: @@ -1607,86 +1074,62 @@ match_addr_range = true; break; case DW_TAG_ptr_to_member_type: - break; case DW_TAG_set_type: - break; case DW_TAG_subrange_type: - break; case DW_TAG_with_stmt: - break; case DW_TAG_access_declaration: - break; case DW_TAG_base_type: break; case DW_TAG_catch_block: match_addr_range = true; break; case DW_TAG_const_type: - break; case DW_TAG_constant: - break; case DW_TAG_enumerator: - break; case DW_TAG_file_type: - break; case DW_TAG_friend: - break; case DW_TAG_namelist: - break; case DW_TAG_namelist_item: - break; case DW_TAG_packed_type: break; case DW_TAG_subprogram: match_addr_range = true; break; case DW_TAG_template_type_parameter: - break; case DW_TAG_template_value_parameter: - break; case DW_TAG_GNU_template_parameter_pack: - break; case DW_TAG_thrown_type: break; case DW_TAG_try_block: match_addr_range = true; break; case DW_TAG_variant_part: - break; case DW_TAG_variable: - break; case DW_TAG_volatile_type: - break; case DW_TAG_dwarf_procedure: - break; case DW_TAG_restrict_type: - break; case DW_TAG_interface_type: break; case DW_TAG_namespace: check_children = true; break; case DW_TAG_imported_module: - break; case DW_TAG_unspecified_type: break; case DW_TAG_partial_unit: match_addr_range = true; break; case DW_TAG_imported_unit: - break; case DW_TAG_shared_type: - break; default: break; } if (match_addr_range) { - dw_addr_t lo_pc = GetAttributeValueAsAddress(dwarf2Data, cu, DW_AT_low_pc, - LLDB_INVALID_ADDRESS); + dw_addr_t lo_pc = + GetAttributeValueAsAddress(cu, DW_AT_low_pc, LLDB_INVALID_ADDRESS); if (lo_pc != LLDB_INVALID_ADDRESS) { - dw_addr_t hi_pc = - GetAttributeHighPC(dwarf2Data, cu, lo_pc, LLDB_INVALID_ADDRESS); + dw_addr_t hi_pc = GetAttributeHighPC(cu, lo_pc, LLDB_INVALID_ADDRESS); if (hi_pc != LLDB_INVALID_ADDRESS) { // printf("\n0x%8.8x: %30s: address = 0x%8.8x [0x%8.8x - 0x%8.8x) ", // m_offset, DW_TAG_value_to_name(tag), address, lo_pc, hi_pc); @@ -1696,13 +1139,14 @@ switch (m_tag) { case DW_TAG_compile_unit: // File case DW_TAG_partial_unit: // File - check_children = ((function_die != NULL) || (block_die != NULL)); + check_children = + ((function_die != nullptr) || (block_die != nullptr)); break; case DW_TAG_subprogram: // Function if (function_die) *function_die = this; - check_children = (block_die != NULL); + check_children = (block_die != nullptr); break; case DW_TAG_inlined_subroutine: // Inlined Function @@ -1722,48 +1166,43 @@ // Compile units may not have a valid high/low pc when there // are address gaps in subroutines so we must always search // if there is no valid high and low PC. - check_children = (m_tag == DW_TAG_compile_unit || - m_tag == DW_TAG_partial_unit) && - ((function_die != NULL) || (block_die != NULL)); + check_children = + (m_tag == DW_TAG_compile_unit || m_tag == DW_TAG_partial_unit) && + ((function_die != nullptr) || (block_die != nullptr)); } } else { - DWARFFormValue form_value; - if (GetAttributeValue(dwarf2Data, cu, DW_AT_ranges, form_value)) { - DWARFRangeList ranges; - DWARFDebugRangesBase *debug_ranges = dwarf2Data->DebugRanges(); - debug_ranges->FindRanges( - cu, GetRangesOffset(debug_ranges, form_value), ranges); - - if (ranges.FindEntryThatContains(address)) { - found_address = true; - // puts("***MATCH***"); - switch (m_tag) { - case DW_TAG_compile_unit: // File - case DW_TAG_partial_unit: // File - check_children = ((function_die != NULL) || (block_die != NULL)); + DWARFRangeList ranges; + if (GetAttributeAddressRanges(cu, ranges, /*check_hi_lo_pc*/ false) && + ranges.FindEntryThatContains(address)) { + found_address = true; + // puts("***MATCH***"); + switch (m_tag) { + case DW_TAG_compile_unit: // File + case DW_TAG_partial_unit: // File + check_children = + ((function_die != nullptr) || (block_die != nullptr)); break; - case DW_TAG_subprogram: // Function - if (function_die) - *function_die = this; - check_children = (block_die != NULL); - break; + case DW_TAG_subprogram: // Function + if (function_die) + *function_die = this; + check_children = (block_die != nullptr); + break; - case DW_TAG_inlined_subroutine: // Inlined Function - case DW_TAG_lexical_block: // Block { } in code - if (block_die) { - *block_die = this; - check_children = true; - } - break; - - default: + case DW_TAG_inlined_subroutine: // Inlined Function + case DW_TAG_lexical_block: // Block { } in code + if (block_die) { + *block_die = this; check_children = true; - break; } - } else { - check_children = false; + break; + + default: + check_children = true; + break; } + } else { + check_children = false; } } } @@ -1772,8 +1211,7 @@ // printf("checking children\n"); DWARFDebugInfoEntry *child = GetFirstChild(); while (child) { - if (child->LookupAddress(address, dwarf2Data, cu, function_die, - block_die)) + if (child->LookupAddress(address, cu, function_die, block_die)) return true; child = child->GetSibling(); } @@ -1782,59 +1220,18 @@ return found_address; } +lldb::offset_t DWARFDebugInfoEntry::GetFirstAttributeOffset() const { + return GetOffset() + llvm::getULEB128Size(m_abbr_idx); +} + const DWARFAbbreviationDeclaration * -DWARFDebugInfoEntry::GetAbbreviationDeclarationPtr( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - lldb::offset_t &offset) const { - if (dwarf2Data) { - offset = GetOffset(); - +DWARFDebugInfoEntry::GetAbbreviationDeclarationPtr(const DWARFUnit *cu) const { + if (cu) { const DWARFAbbreviationDeclarationSet *abbrev_set = cu->GetAbbreviations(); - if (abbrev_set) { - const DWARFAbbreviationDeclaration *abbrev_decl = - abbrev_set->GetAbbreviationDeclaration(m_abbr_idx); - if (abbrev_decl) { - // Make sure the abbreviation code still matches. If it doesn't and the - // DWARF data was mmap'ed, the backing file might have been modified - // which is bad news. - const uint64_t abbrev_code = cu->GetData().GetULEB128(&offset); - - if (abbrev_decl->Code() == abbrev_code) - return abbrev_decl; - - dwarf2Data->GetObjectFile()->GetModule()->ReportErrorIfModifyDetected( - "0x%8.8x: the DWARF debug information has been modified (abbrev " - "code was %u, and is now %u)", - GetOffset(), (uint32_t)abbrev_decl->Code(), (uint32_t)abbrev_code); - } - } + if (abbrev_set) + return abbrev_set->GetAbbreviationDeclaration(m_abbr_idx); } - offset = DW_INVALID_OFFSET; - return NULL; -} - -bool DWARFDebugInfoEntry::OffsetLessThan(const DWARFDebugInfoEntry &a, - const DWARFDebugInfoEntry &b) { - return a.GetOffset() < b.GetOffset(); -} - -void DWARFDebugInfoEntry::DumpDIECollection( - Stream &strm, DWARFDebugInfoEntry::collection &die_collection) { - DWARFDebugInfoEntry::const_iterator pos; - DWARFDebugInfoEntry::const_iterator end = die_collection.end(); - strm.PutCString("\noffset parent sibling child\n"); - strm.PutCString("-------- -------- -------- --------\n"); - for (pos = die_collection.begin(); pos != end; ++pos) { - const DWARFDebugInfoEntry &die_ref = *pos; - const DWARFDebugInfoEntry *p = die_ref.GetParent(); - const DWARFDebugInfoEntry *s = die_ref.GetSibling(); - const DWARFDebugInfoEntry *c = die_ref.GetFirstChild(); - strm.Printf("%.8x: %.8x %.8x %.8x 0x%4.4x %s%s\n", die_ref.GetOffset(), - p ? p->GetOffset() : 0, s ? s->GetOffset() : 0, - c ? c->GetOffset() : 0, die_ref.Tag(), - DW_TAG_value_to_name(die_ref.Tag()), - die_ref.HasChildren() ? " *" : ""); - } + return nullptr; } bool DWARFDebugInfoEntry::operator==(const DWARFDebugInfoEntry &rhs) const {
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h index ec19fc8..1e7b5f2 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h
@@ -1,9 +1,8 @@ //===-- DWARFDebugInfoEntry.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,26 +19,6 @@ #include <set> #include <vector> -typedef std::map<const DWARFDebugInfoEntry *, dw_addr_t> DIEToAddressMap; -typedef DIEToAddressMap::iterator DIEToAddressMapIter; -typedef DIEToAddressMap::const_iterator DIEToAddressMapConstIter; - -typedef std::map<dw_addr_t, const DWARFDebugInfoEntry *> AddressToDIEMap; -typedef AddressToDIEMap::iterator AddressToDIEMapIter; -typedef AddressToDIEMap::const_iterator AddressToDIEMapConstIter; - -typedef std::map<dw_offset_t, dw_offset_t> DIEToDIEMap; -typedef DIEToDIEMap::iterator DIEToDIEMapIter; -typedef DIEToDIEMap::const_iterator DIEToDIEMapConstIter; - -typedef std::map<uint32_t, const DWARFDebugInfoEntry *> UInt32ToDIEMap; -typedef UInt32ToDIEMap::iterator UInt32ToDIEMapIter; -typedef UInt32ToDIEMap::const_iterator UInt32ToDIEMapConstIter; - -typedef std::multimap<uint32_t, const DWARFDebugInfoEntry *> UInt32ToDIEMMap; -typedef UInt32ToDIEMMap::iterator UInt32ToDIEMMapIter; -typedef UInt32ToDIEMMap::const_iterator UInt32ToDIEMMapConstIter; - class DWARFDeclContext; #define DIE_SIBLING_IDX_BITSIZE 31 @@ -50,10 +29,6 @@ typedef collection::iterator iterator; typedef collection::const_iterator const_iterator; - typedef std::vector<dw_offset_t> offset_collection; - typedef offset_collection::iterator offset_collection_iterator; - typedef offset_collection::const_iterator offset_collection_const_iterator; - DWARFDebugInfoEntry() : m_offset(DW_INVALID_OFFSET), m_parent_idx(0), m_sibling_idx(0), m_has_children(false), m_abbr_idx(0), m_tag(0) {} @@ -62,138 +37,90 @@ bool operator==(const DWARFDebugInfoEntry &rhs) const; bool operator!=(const DWARFDebugInfoEntry &rhs) const; - void BuildAddressRangeTable(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, + void BuildAddressRangeTable(const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const; - void BuildFunctionAddressRangeTable(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, + void BuildFunctionAddressRangeTable(const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const; - bool FastExtract(const lldb_private::DWARFDataExtractor &debug_info_data, - const DWARFUnit *cu, - const DWARFFormValue::FixedFormSizes &fixed_form_sizes, - lldb::offset_t *offset_ptr); + bool Extract(const lldb_private::DWARFDataExtractor &data, + const DWARFUnit *cu, lldb::offset_t *offset_ptr); - bool Extract(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - lldb::offset_t *offset_ptr); - - bool LookupAddress(const dw_addr_t address, SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, + bool LookupAddress(const dw_addr_t address, const DWARFUnit *cu, DWARFDebugInfoEntry **function_die, DWARFDebugInfoEntry **block_die); size_t GetAttributes(const DWARFUnit *cu, - DWARFFormValue::FixedFormSizes fixed_form_sizes, DWARFAttributes &attrs, uint32_t curr_depth = 0) const; // "curr_depth" for internal use only, don't set this yourself!!! dw_offset_t - GetAttributeValue(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, DWARFFormValue &formValue, + GetAttributeValue(const DWARFUnit *cu, const dw_attr_t attr, + DWARFFormValue &formValue, dw_offset_t *end_attr_offset_ptr = nullptr, bool check_specification_or_abstract_origin = false) const; const char *GetAttributeValueAsString( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, const char *fail_value, + const DWARFUnit *cu, const dw_attr_t attr, const char *fail_value, bool check_specification_or_abstract_origin = false) const; uint64_t GetAttributeValueAsUnsigned( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, uint64_t fail_value, + const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value, bool check_specification_or_abstract_origin = false) const; - uint64_t GetAttributeValueAsReference( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, uint64_t fail_value, - bool check_specification_or_abstract_origin = false) const; - - int64_t GetAttributeValueAsSigned( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, int64_t fail_value, + DWARFDIE GetAttributeValueAsReference( + const DWARFUnit *cu, const dw_attr_t attr, bool check_specification_or_abstract_origin = false) const; uint64_t GetAttributeValueAsAddress( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_attr_t attr, uint64_t fail_value, + const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value, bool check_specification_or_abstract_origin = false) const; dw_addr_t - GetAttributeHighPC(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - dw_addr_t lo_pc, uint64_t fail_value, + GetAttributeHighPC(const DWARFUnit *cu, dw_addr_t lo_pc, uint64_t fail_value, bool check_specification_or_abstract_origin = false) const; bool GetAttributeAddressRange( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, dw_addr_t &lo_pc, - dw_addr_t &hi_pc, uint64_t fail_value, + const DWARFUnit *cu, dw_addr_t &lo_pc, dw_addr_t &hi_pc, + uint64_t fail_value, bool check_specification_or_abstract_origin = false) const; size_t GetAttributeAddressRanges( - SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - DWARFRangeList &ranges, bool check_hi_lo_pc, + const DWARFUnit *cu, DWARFRangeList &ranges, bool check_hi_lo_pc, bool check_specification_or_abstract_origin = false) const; - const char *GetName(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu) const; + const char *GetName(const DWARFUnit *cu) const; - const char *GetMangledName(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, + const char *GetMangledName(const DWARFUnit *cu, bool substitute_name_allowed = true) const; - const char *GetPubname(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu) const; + const char *GetPubname(const DWARFUnit *cu) const; - static bool GetName(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const dw_offset_t die_offset, lldb_private::Stream &s); + const char *GetQualifiedName(DWARFUnit *cu, std::string &storage) const; - static bool AppendTypeName(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, - const dw_offset_t die_offset, - lldb_private::Stream &s); - - const char *GetQualifiedName(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu, + const char *GetQualifiedName(DWARFUnit *cu, const DWARFAttributes &attributes, std::string &storage) const; - const char *GetQualifiedName(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu, - const DWARFAttributes &attributes, - std::string &storage) const; - - static bool OffsetLessThan(const DWARFDebugInfoEntry &a, - const DWARFDebugInfoEntry &b); - - void Dump(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - lldb_private::Stream &s, uint32_t recurse_depth) const; - - void DumpAncestry(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const DWARFDebugInfoEntry *oldest, lldb_private::Stream &s, - uint32_t recurse_depth) const; + void Dump(const DWARFUnit *cu, lldb_private::Stream &s, + uint32_t recurse_depth) const; static void - DumpAttribute(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const lldb_private::DWARFDataExtractor &debug_info_data, + DumpAttribute(const DWARFUnit *cu, + const lldb_private::DWARFDataExtractor &data, lldb::offset_t *offset_ptr, lldb_private::Stream &s, dw_attr_t attr, DWARFFormValue &form_value); - // This one dumps the comp unit name, objfile name and die offset for this die - // so the stream S. - void DumpLocation(SymbolFileDWARF *dwarf2Data, DWARFUnit *cu, - lldb_private::Stream &s) const; - bool - GetDIENamesAndRanges(SymbolFileDWARF *dwarf2Data, const DWARFUnit *cu, - const char *&name, const char *&mangled, - DWARFRangeList &rangeList, int &decl_file, - int &decl_line, int &decl_column, int &call_file, - int &call_line, int &call_column, - lldb_private::DWARFExpression *frame_base = NULL) const; + bool GetDIENamesAndRanges( + const DWARFUnit *cu, const char *&name, const char *&mangled, + DWARFRangeList &rangeList, int &decl_file, int &decl_line, + int &decl_column, int &call_file, int &call_line, int &call_column, + lldb_private::DWARFExpression *frame_base = nullptr) const; const DWARFAbbreviationDeclaration * - GetAbbreviationDeclarationPtr(SymbolFileDWARF *dwarf2Data, - const DWARFUnit *cu, - lldb::offset_t &offset) const; + GetAbbreviationDeclarationPtr(const DWARFUnit *cu) const; + + lldb::offset_t GetFirstAttributeOffset() const; dw_tag_t Tag() const { return m_tag; } @@ -208,74 +135,41 @@ // We know we are kept in a vector of contiguous entries, so we know // our parent will be some index behind "this". DWARFDebugInfoEntry *GetParent() { - return m_parent_idx > 0 ? this - m_parent_idx : NULL; + return m_parent_idx > 0 ? this - m_parent_idx : nullptr; } const DWARFDebugInfoEntry *GetParent() const { - return m_parent_idx > 0 ? this - m_parent_idx : NULL; + return m_parent_idx > 0 ? this - m_parent_idx : nullptr; } // We know we are kept in a vector of contiguous entries, so we know // our sibling will be some index after "this". DWARFDebugInfoEntry *GetSibling() { - return m_sibling_idx > 0 ? this + m_sibling_idx : NULL; + return m_sibling_idx > 0 ? this + m_sibling_idx : nullptr; } const DWARFDebugInfoEntry *GetSibling() const { - return m_sibling_idx > 0 ? this + m_sibling_idx : NULL; + return m_sibling_idx > 0 ? this + m_sibling_idx : nullptr; } // We know we are kept in a vector of contiguous entries, so we know // we don't need to store our child pointer, if we have a child it will // be the next entry in the list... DWARFDebugInfoEntry *GetFirstChild() { - return HasChildren() ? this + 1 : NULL; + return HasChildren() ? this + 1 : nullptr; } const DWARFDebugInfoEntry *GetFirstChild() const { - return HasChildren() ? this + 1 : NULL; + return HasChildren() ? this + 1 : nullptr; } - void GetDeclContextDIEs(DWARFUnit *cu, - DWARFDIECollection &decl_context_dies) const; - - void GetDWARFDeclContext(SymbolFileDWARF *dwarf2Data, DWARFUnit *cu, + void GetDWARFDeclContext(DWARFUnit *cu, DWARFDeclContext &dwarf_decl_ctx) const; - bool MatchesDWARFDeclContext(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu, - const DWARFDeclContext &dwarf_decl_ctx) const; - - DWARFDIE GetParentDeclContextDIE(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu) const; - DWARFDIE GetParentDeclContextDIE(SymbolFileDWARF *dwarf2Data, - DWARFUnit *cu, + DWARFDIE GetParentDeclContextDIE(DWARFUnit *cu) const; + DWARFDIE GetParentDeclContextDIE(DWARFUnit *cu, const DWARFAttributes &attributes) const; - void SetParent(DWARFDebugInfoEntry *parent) { - if (parent) { - // We know we are kept in a vector of contiguous entries, so we know - // our parent will be some index behind "this". - m_parent_idx = this - parent; - } else - m_parent_idx = 0; - } - void SetSibling(DWARFDebugInfoEntry *sibling) { - if (sibling) { - // We know we are kept in a vector of contiguous entries, so we know - // our sibling will be some index after "this". - m_sibling_idx = sibling - this; - sibling->SetParent(GetParent()); - } else - m_sibling_idx = 0; - } - void SetSiblingIndex(uint32_t idx) { m_sibling_idx = idx; } - void SetParentIndex(uint32_t idx) { m_parent_idx = idx; } - static void - DumpDIECollection(lldb_private::Stream &strm, - DWARFDebugInfoEntry::collection &die_collection); - protected: - dw_offset_t - m_offset; // Offset within the .debug_info of the start of this entry + dw_offset_t m_offset; // Offset within the .debug_info/.debug_types uint32_t m_parent_idx; // How many to subtract from "this" to get the parent. // If zero this die has no parent uint32_t m_sibling_idx : 31, // How many to add to "this" to get the sibling.
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp index d9f5012..953089f 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp
@@ -1,9 +1,8 @@ //===-- DWARFDebugLine.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,12 +11,15 @@ //#define ENABLE_DEBUG_PRINTF // DO NOT LEAVE THIS DEFINED: DEBUG ONLY!!! #include <assert.h> +#include <memory> + #include "lldb/Core/FileSpecList.h" #include "lldb/Core/Module.h" #include "lldb/Host/Host.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Timer.h" +#include "DWARFUnit.h" #include "LogChannelDWARF.h" #include "SymbolFileDWARF.h" @@ -25,12 +27,10 @@ using namespace lldb_private; using namespace std; -//---------------------------------------------------------------------- // Parse // // Parse all information in the debug_line_data into an internal // representation. -//---------------------------------------------------------------------- void DWARFDebugLine::Parse(const DWARFDataExtractor &debug_line_data) { m_lineTableMap.clear(); lldb::offset_t offset = 0; @@ -38,7 +38,7 @@ while (debug_line_data.ValidOffset(offset)) { const lldb::offset_t debug_line_offset = offset; - if (line_table_sp.get() == NULL) + if (line_table_sp.get() == nullptr) break; if (ParseStatementTable(debug_line_data, &offset, line_table_sp.get(), nullptr)) { @@ -48,7 +48,7 @@ // DEBUG_PRINTF("m_lineTableMap[0x%8.8x] = line_table_sp\n", // debug_line_offset); m_lineTableMap[debug_line_offset] = line_table_sp; - line_table_sp.reset(new LineTable); + line_table_sp = std::make_shared<LineTable>(); } else ++offset; // Try next byte in line table } @@ -59,9 +59,7 @@ Parse(debug_line_data); } -//---------------------------------------------------------------------- // DWARFDebugLine::GetLineTable -//---------------------------------------------------------------------- DWARFDebugLine::LineTable::shared_ptr DWARFDebugLine::GetLineTable(const dw_offset_t offset) const { DWARFDebugLine::LineTable::shared_ptr line_table_shared_ptr; @@ -71,296 +69,11 @@ return line_table_shared_ptr; } -//---------------------------------------------------------------------- -// DumpStateToFile -//---------------------------------------------------------------------- -static void DumpStateToFile(dw_offset_t offset, - const DWARFDebugLine::State &state, - void *userData) { - Log *log = (Log *)userData; - if (state.row == DWARFDebugLine::State::StartParsingLineTable) { - // If the row is zero we are being called with the prologue only - state.prologue->Dump(log); - log->PutCString("Address Line Column File"); - log->PutCString("------------------ ------ ------ ------"); - } else if (state.row == DWARFDebugLine::State::DoneParsingLineTable) { - // Done parsing line table - } else { - log->Printf("0x%16.16" PRIx64 " %6u %6u %6u%s\n", state.address, state.line, - state.column, state.file, state.end_sequence ? " END" : ""); - } -} - -//---------------------------------------------------------------------- -// DWARFDebugLine::DumpLineTableRows -//---------------------------------------------------------------------- -bool DWARFDebugLine::DumpLineTableRows(Log *log, SymbolFileDWARF *dwarf2Data, - dw_offset_t debug_line_offset) { - const DWARFDataExtractor &debug_line_data = dwarf2Data->get_debug_line_data(); - - if (debug_line_offset == DW_INVALID_OFFSET) { - // Dump line table to a single file only - debug_line_offset = 0; - while (debug_line_data.ValidOffset(debug_line_offset)) - debug_line_offset = - DumpStatementTable(log, debug_line_data, debug_line_offset); - } else { - // Dump line table to a single file only - DumpStatementTable(log, debug_line_data, debug_line_offset); - } - return false; -} - -//---------------------------------------------------------------------- -// DWARFDebugLine::DumpStatementTable -//---------------------------------------------------------------------- -dw_offset_t -DWARFDebugLine::DumpStatementTable(Log *log, - const DWARFDataExtractor &debug_line_data, - const dw_offset_t debug_line_offset) { - if (debug_line_data.ValidOffset(debug_line_offset)) { - lldb::offset_t offset = debug_line_offset; - log->Printf("--------------------------------------------------------------" - "--------\n" - "debug_line[0x%8.8x]\n" - "--------------------------------------------------------------" - "--------\n", - debug_line_offset); - - if (ParseStatementTable(debug_line_data, &offset, DumpStateToFile, log, nullptr)) - return offset; - else - return debug_line_offset + 1; // Skip to next byte in .debug_line section - } - - return DW_INVALID_OFFSET; -} - -//---------------------------------------------------------------------- -// DumpOpcodes -//---------------------------------------------------------------------- -bool DWARFDebugLine::DumpOpcodes(Log *log, SymbolFileDWARF *dwarf2Data, - dw_offset_t debug_line_offset, - uint32_t dump_flags) { - const DWARFDataExtractor &debug_line_data = dwarf2Data->get_debug_line_data(); - - if (debug_line_data.GetByteSize() == 0) { - log->Printf("< EMPTY >\n"); - return false; - } - - if (debug_line_offset == DW_INVALID_OFFSET) { - // Dump line table to a single file only - debug_line_offset = 0; - while (debug_line_data.ValidOffset(debug_line_offset)) - debug_line_offset = DumpStatementOpcodes(log, debug_line_data, - debug_line_offset, dump_flags); - } else { - // Dump line table to a single file only - DumpStatementOpcodes(log, debug_line_data, debug_line_offset, dump_flags); - } - return false; -} - -//---------------------------------------------------------------------- -// DumpStatementOpcodes -//---------------------------------------------------------------------- -dw_offset_t DWARFDebugLine::DumpStatementOpcodes( - Log *log, const DWARFDataExtractor &debug_line_data, - const dw_offset_t debug_line_offset, uint32_t flags) { - lldb::offset_t offset = debug_line_offset; - if (debug_line_data.ValidOffset(offset)) { - Prologue prologue; - - if (ParsePrologue(debug_line_data, &offset, &prologue)) { - log->PutCString("--------------------------------------------------------" - "--------------"); - log->Printf("debug_line[0x%8.8x]", debug_line_offset); - log->PutCString("--------------------------------------------------------" - "--------------\n"); - prologue.Dump(log); - } else { - offset = debug_line_offset; - log->Printf("0x%8.8" PRIx64 ": skipping pad byte %2.2x", offset, - debug_line_data.GetU8(&offset)); - return offset; - } - - Row row(prologue.default_is_stmt); - const dw_offset_t end_offset = debug_line_offset + prologue.total_length + - sizeof(prologue.total_length); - - assert(debug_line_data.ValidOffset(end_offset - 1)); - - while (offset < end_offset) { - const uint32_t op_offset = offset; - uint8_t opcode = debug_line_data.GetU8(&offset); - switch (opcode) { - case 0: // Extended Opcodes always start with a zero opcode followed by - { // a uleb128 length so you can skip ones you don't know about - - dw_offset_t ext_offset = offset; - dw_uleb128_t len = debug_line_data.GetULEB128(&offset); - dw_offset_t arg_size = len - (offset - ext_offset); - uint8_t sub_opcode = debug_line_data.GetU8(&offset); - // if (verbose) - // log->Printf( "Extended: <%u> %2.2x ", len, - // sub_opcode); - - switch (sub_opcode) { - case DW_LNE_end_sequence: - log->Printf("0x%8.8x: DW_LNE_end_sequence", op_offset); - row.Dump(log); - row.Reset(prologue.default_is_stmt); - break; - - case DW_LNE_set_address: { - row.address = debug_line_data.GetMaxU64(&offset, arg_size); - log->Printf("0x%8.8x: DW_LNE_set_address (0x%" PRIx64 ")", op_offset, - row.address); - } break; - - case DW_LNE_define_file: { - FileNameEntry fileEntry; - fileEntry.name = debug_line_data.GetCStr(&offset); - fileEntry.dir_idx = debug_line_data.GetULEB128(&offset); - fileEntry.mod_time = debug_line_data.GetULEB128(&offset); - fileEntry.length = debug_line_data.GetULEB128(&offset); - log->Printf("0x%8.8x: DW_LNE_define_file('%s', dir=%i, " - "mod_time=0x%8.8x, length=%i )", - op_offset, fileEntry.name, fileEntry.dir_idx, - fileEntry.mod_time, fileEntry.length); - prologue.file_names.push_back(fileEntry); - } break; - - case DW_LNE_set_discriminator: { - uint64_t discriminator = debug_line_data.GetULEB128(&offset); - log->Printf("0x%8.8x: DW_LNE_set_discriminator (0x%" PRIx64 ")", - op_offset, discriminator); - } break; - default: - log->Printf("0x%8.8x: DW_LNE_??? (%2.2x) - Skipping unknown upcode", - op_offset, opcode); - // Length doesn't include the zero opcode byte or the length itself, - // but it does include the sub_opcode, so we have to adjust for that - // below - offset += arg_size; - break; - } - } break; - - // Standard Opcodes - case DW_LNS_copy: - log->Printf("0x%8.8x: DW_LNS_copy", op_offset); - row.Dump(log); - break; - - case DW_LNS_advance_pc: { - dw_uleb128_t addr_offset_n = debug_line_data.GetULEB128(&offset); - dw_uleb128_t addr_offset = addr_offset_n * prologue.min_inst_length; - log->Printf("0x%8.8x: DW_LNS_advance_pc (0x%x)", op_offset, - addr_offset); - row.address += addr_offset; - } break; - - case DW_LNS_advance_line: { - dw_sleb128_t line_offset = debug_line_data.GetSLEB128(&offset); - log->Printf("0x%8.8x: DW_LNS_advance_line (%i)", op_offset, - line_offset); - row.line += line_offset; - } break; - - case DW_LNS_set_file: - row.file = debug_line_data.GetULEB128(&offset); - log->Printf("0x%8.8x: DW_LNS_set_file (%u)", op_offset, row.file); - break; - - case DW_LNS_set_column: - row.column = debug_line_data.GetULEB128(&offset); - log->Printf("0x%8.8x: DW_LNS_set_column (%u)", op_offset, row.column); - break; - - case DW_LNS_negate_stmt: - row.is_stmt = !row.is_stmt; - log->Printf("0x%8.8x: DW_LNS_negate_stmt", op_offset); - break; - - case DW_LNS_set_basic_block: - row.basic_block = true; - log->Printf("0x%8.8x: DW_LNS_set_basic_block", op_offset); - break; - - case DW_LNS_const_add_pc: { - uint8_t adjust_opcode = 255 - prologue.opcode_base; - dw_addr_t addr_offset = - (adjust_opcode / prologue.line_range) * prologue.min_inst_length; - log->Printf("0x%8.8x: DW_LNS_const_add_pc (0x%8.8" PRIx64 ")", - op_offset, addr_offset); - row.address += addr_offset; - } break; - - case DW_LNS_fixed_advance_pc: { - uint16_t pc_offset = debug_line_data.GetU16(&offset); - log->Printf("0x%8.8x: DW_LNS_fixed_advance_pc (0x%4.4x)", op_offset, - pc_offset); - row.address += pc_offset; - } break; - - case DW_LNS_set_prologue_end: - row.prologue_end = true; - log->Printf("0x%8.8x: DW_LNS_set_prologue_end", op_offset); - break; - - case DW_LNS_set_epilogue_begin: - row.epilogue_begin = true; - log->Printf("0x%8.8x: DW_LNS_set_epilogue_begin", op_offset); - break; - - case DW_LNS_set_isa: - row.isa = debug_line_data.GetULEB128(&offset); - log->Printf("0x%8.8x: DW_LNS_set_isa (%u)", op_offset, row.isa); - break; - - // Special Opcodes - default: - if (opcode < prologue.opcode_base) { - // We have an opcode that this parser doesn't know about, skip the - // number of ULEB128 numbers that is says to skip in the prologue's - // standard_opcode_lengths array - uint8_t n = prologue.standard_opcode_lengths[opcode - 1]; - log->Printf("0x%8.8x: Special : Unknown skipping %u ULEB128 values.", - op_offset, n); - while (n > 0) { - debug_line_data.GetULEB128(&offset); - --n; - } - } else { - uint8_t adjust_opcode = opcode - prologue.opcode_base; - dw_addr_t addr_offset = - (adjust_opcode / prologue.line_range) * prologue.min_inst_length; - int32_t line_offset = - prologue.line_base + (adjust_opcode % prologue.line_range); - log->Printf("0x%8.8x: address += 0x%" PRIx64 ", line += %i\n", - op_offset, (uint64_t)addr_offset, line_offset); - row.address += addr_offset; - row.line += line_offset; - row.Dump(log); - } - break; - } - } - return end_offset; - } - return DW_INVALID_OFFSET; -} - -//---------------------------------------------------------------------- // Parse // // Parse the entire line table contents calling callback each time a new // prologue is parsed and every time a new row is to be added to the line // table. -//---------------------------------------------------------------------- void DWARFDebugLine::Parse(const DWARFDataExtractor &debug_line_data, DWARFDebugLine::State::Callback callback, void *userData) { @@ -392,9 +105,7 @@ } } // namespace -//---------------------------------------------------------------------- // DWARFDebugLine::ParsePrologue -//---------------------------------------------------------------------- bool DWARFDebugLine::ParsePrologue(const DWARFDataExtractor &debug_line_data, lldb::offset_t *offset_ptr, Prologue *prologue, DWARFUnit *dwarf_cu) { @@ -528,8 +239,7 @@ bool DWARFDebugLine::ParseSupportFiles( const lldb::ModuleSP &module_sp, const DWARFDataExtractor &debug_line_data, - const lldb_private::FileSpec &cu_comp_dir, dw_offset_t stmt_list, - FileSpecList &support_files, DWARFUnit *dwarf_cu) { + dw_offset_t stmt_list, FileSpecList &support_files, DWARFUnit *dwarf_cu) { lldb::offset_t offset = stmt_list; Prologue prologue; @@ -545,7 +255,9 @@ std::string remapped_file; for (uint32_t file_idx = 1; - prologue.GetFile(file_idx, cu_comp_dir, file_spec); ++file_idx) { + prologue.GetFile(file_idx, dwarf_cu->GetCompilationDirectory(), + dwarf_cu->GetPathStyle(), file_spec); + ++file_idx) { if (module_sp->RemapSourceFile(file_spec.GetPath(), remapped_file)) file_spec.SetFile(remapped_file, FileSpec::Style::native); support_files.Append(file_spec); @@ -553,13 +265,11 @@ return true; } -//---------------------------------------------------------------------- // ParseStatementTable // // Parse a single line table (prologue and all rows) and call the callback // function once for the prologue (row in state will be zero) and each time a // row is to be added to the line table. -//---------------------------------------------------------------------- bool DWARFDebugLine::ParseStatementTable( const DWARFDataExtractor &debug_line_data, lldb::offset_t *offset_ptr, DWARFDebugLine::State::Callback callback, void *userData, DWARFUnit *dwarf_cu) { @@ -832,9 +542,7 @@ return end_offset; } -//---------------------------------------------------------------------- // ParseStatementTableCallback -//---------------------------------------------------------------------- static void ParseStatementTableCallback(dw_offset_t offset, const DWARFDebugLine::State &state, void *userData) { @@ -851,12 +559,10 @@ } } -//---------------------------------------------------------------------- // ParseStatementTable // // Parse a line table at offset and populate the LineTable class with the // prologue and all rows. -//---------------------------------------------------------------------- bool DWARFDebugLine::ParseStatementTable( const DWARFDataExtractor &debug_line_data, lldb::offset_t *offset_ptr, LineTable *line_table, DWARFUnit *dwarf_cu) { @@ -868,9 +574,7 @@ return SymbolFileDWARF::SupportedVersion(version); } -//---------------------------------------------------------------------- // DWARFDebugLine::Prologue::Dump -//---------------------------------------------------------------------- void DWARFDebugLine::Prologue::Dump(Log *log) { uint32_t i; @@ -909,11 +613,9 @@ } } -//---------------------------------------------------------------------- // DWARFDebugLine::ParsePrologue::Append // // Append the contents of the prologue to the binary stream buffer -//---------------------------------------------------------------------- // void // DWARFDebugLine::Prologue::Append(BinaryStreamBuf& buff) const //{ @@ -947,10 +649,12 @@ //} bool DWARFDebugLine::Prologue::GetFile(uint32_t file_idx, - const lldb_private::FileSpec &comp_dir, FileSpec &file) const { + const FileSpec &comp_dir, + FileSpec::Style style, + FileSpec &file) const { uint32_t idx = file_idx - 1; // File indexes are 1 based... if (idx < file_names.size()) { - file.SetFile(file_names[idx].name, FileSpec::Style::native); + file.SetFile(file_names[idx].name, style); if (file.IsRelative()) { if (file_names[idx].dir_idx > 0) { const uint32_t dir_idx = file_names[idx].dir_idx - 1; @@ -969,42 +673,18 @@ return false; } -//---------------------------------------------------------------------- -// DWARFDebugLine::LineTable::Dump -//---------------------------------------------------------------------- -void DWARFDebugLine::LineTable::Dump(Log *log) const { - if (prologue.get()) - prologue->Dump(log); - - if (!rows.empty()) { - log->PutCString("Address Line Column File ISA Flags"); - log->PutCString( - "------------------ ------ ------ ------ --- -------------"); - Row::const_iterator pos = rows.begin(); - Row::const_iterator end = rows.end(); - while (pos != end) { - (*pos).Dump(log); - ++pos; - } - } -} - void DWARFDebugLine::LineTable::AppendRow(const DWARFDebugLine::Row &state) { rows.push_back(state); } -//---------------------------------------------------------------------- // Compare function for the binary search in // DWARFDebugLine::LineTable::LookupAddress() -//---------------------------------------------------------------------- static bool FindMatchingAddress(const DWARFDebugLine::Row &row1, const DWARFDebugLine::Row &row2) { return row1.address < row2.address; } -//---------------------------------------------------------------------- // DWARFDebugLine::LineTable::LookupAddress -//---------------------------------------------------------------------- uint32_t DWARFDebugLine::LineTable::LookupAddress(dw_addr_t address, dw_addr_t cu_high_pc) const { uint32_t index = UINT32_MAX; @@ -1037,26 +717,20 @@ return index; // Failed to find address } -//---------------------------------------------------------------------- // DWARFDebugLine::Row::Row -//---------------------------------------------------------------------- DWARFDebugLine::Row::Row(bool default_is_stmt) : address(0), line(1), column(0), file(1), is_stmt(default_is_stmt), basic_block(false), end_sequence(false), prologue_end(false), epilogue_begin(false), isa(0) {} -//---------------------------------------------------------------------- // Called after a row is appended to the matrix -//---------------------------------------------------------------------- void DWARFDebugLine::Row::PostAppend() { basic_block = false; prologue_end = false; epilogue_begin = false; } -//---------------------------------------------------------------------- // DWARFDebugLine::Row::Reset -//---------------------------------------------------------------------- void DWARFDebugLine::Row::Reset(bool default_is_stmt) { address = 0; line = 1; @@ -1069,9 +743,7 @@ epilogue_begin = false; isa = 0; } -//---------------------------------------------------------------------- // DWARFDebugLine::Row::Dump -//---------------------------------------------------------------------- void DWARFDebugLine::Row::Dump(Log *log) const { log->Printf("0x%16.16" PRIx64 " %6u %6u %6u %3u %s%s%s%s%s", address, line, column, file, isa, is_stmt ? " is_stmt" : "", @@ -1081,9 +753,7 @@ end_sequence ? " end_sequence" : ""); } -//---------------------------------------------------------------------- // Compare function LineTable structures -//---------------------------------------------------------------------- static bool AddressLessThan(const DWARFDebugLine::Row &a, const DWARFDebugLine::Row &b) { return a.address < b.address; @@ -1123,14 +793,7 @@ } } -void DWARFDebugLine::Row::Dump(Log *log, const Row::collection &state_coll) { - std::for_each(state_coll.begin(), state_coll.end(), - bind2nd(std::mem_fun_ref(&Row::Dump), log)); -} - -//---------------------------------------------------------------------- // DWARFDebugLine::State::State -//---------------------------------------------------------------------- DWARFDebugLine::State::State(Prologue::shared_ptr &p, Log *l, DWARFDebugLine::State::Callback cb, void *userData) : Row(p->default_is_stmt), prologue(p), log(l), callback(cb), @@ -1140,14 +803,10 @@ callback(0, *this, callbackUserData); } -//---------------------------------------------------------------------- // DWARFDebugLine::State::Reset -//---------------------------------------------------------------------- void DWARFDebugLine::State::Reset() { Row::Reset(prologue->default_is_stmt); } -//---------------------------------------------------------------------- // DWARFDebugLine::State::AppendRowToMatrix -//---------------------------------------------------------------------- void DWARFDebugLine::State::AppendRowToMatrix(dw_offset_t offset) { // Each time we are to add an entry into the line table matrix call the // callback function so that someone can do something with the current state @@ -1167,9 +826,7 @@ PostAppend(); } -//---------------------------------------------------------------------- // DWARFDebugLine::State::Finalize -//---------------------------------------------------------------------- void DWARFDebugLine::State::Finalize(dw_offset_t offset) { // Call the callback with a special row state when we are done parsing a line // table
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.h index 04f72e0..0d236ca 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.h
@@ -1,9 +1,8 @@ //===-- DWARFDebugLine.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,6 +13,7 @@ #include <string> #include <vector> +#include "lldb/Utility/FileSpec.h" #include "lldb/lldb-private.h" #include "DWARFDataExtractor.h" @@ -24,16 +24,13 @@ class DWARFUnit; class SymbolFileDWARF; -//---------------------------------------------------------------------- // DWARFDebugLine -//---------------------------------------------------------------------- class DWARFDebugLine { public: - //------------------------------------------------------------------ // FileNameEntry - //------------------------------------------------------------------ struct FileNameEntry { - FileNameEntry() : name(nullptr), dir_idx(0), mod_time(0), length(0) {} + FileNameEntry() + : name(nullptr), dir_idx(0), mod_time(0), length(0), checksum() {} const char *name; dw_sleb128_t dir_idx; @@ -42,9 +39,7 @@ llvm::MD5::MD5Result checksum; }; - //------------------------------------------------------------------ // Prologue - //------------------------------------------------------------------ struct Prologue { Prologue() @@ -99,6 +94,7 @@ file_names.clear(); } bool GetFile(uint32_t file_idx, const lldb_private::FileSpec &cu_comp_dir, + lldb_private::FileSpec::Style style, lldb_private::FileSpec &file) const; }; @@ -114,7 +110,6 @@ void Reset(bool default_is_stmt); void Dump(lldb_private::Log *log) const; static void Insert(Row::collection &state_coll, const Row &state); - static void Dump(lldb_private::Log *log, const Row::collection &state_coll); dw_addr_t address; // The program-counter value corresponding to a machine // instruction generated by the compiler. @@ -145,9 +140,7 @@ // instruction set architecture for the current instruction. }; - //------------------------------------------------------------------ // LineTable - //------------------------------------------------------------------ struct LineTable { typedef std::shared_ptr<LineTable> shared_ptr; @@ -160,15 +153,12 @@ } uint32_t LookupAddress(dw_addr_t address, dw_addr_t cu_high_pc) const; - void Dump(lldb_private::Log *log) const; Prologue::shared_ptr prologue; Row::collection rows; }; - //------------------------------------------------------------------ // State - //------------------------------------------------------------------ struct State : public Row { typedef void (*Callback)(dw_offset_t offset, const State &state, void *userData); @@ -196,20 +186,12 @@ DISALLOW_COPY_AND_ASSIGN(State); }; - static bool DumpOpcodes( - lldb_private::Log *log, SymbolFileDWARF *dwarf2Data, - dw_offset_t line_offset = DW_INVALID_OFFSET, - uint32_t dump_flags = 0); // If line_offset is invalid, dump everything - static bool DumpLineTableRows( - lldb_private::Log *log, SymbolFileDWARF *dwarf2Data, - dw_offset_t line_offset = - DW_INVALID_OFFSET); // If line_offset is invalid, dump everything static bool ParseSupportFiles(const lldb::ModuleSP &module_sp, const lldb_private::DWARFDataExtractor &debug_line_data, - const lldb_private::FileSpec &cu_comp_dir, dw_offset_t stmt_list, - lldb_private::FileSpecList &support_files, DWARFUnit *dwarf_cu); + lldb_private::FileSpecList &support_files, + DWARFUnit *dwarf_cu); static bool ParsePrologue(const lldb_private::DWARFDataExtractor &debug_line_data, lldb::offset_t *offset_ptr, Prologue *prologue, @@ -218,14 +200,6 @@ ParseStatementTable(const lldb_private::DWARFDataExtractor &debug_line_data, lldb::offset_t *offset_ptr, State::Callback callback, void *userData, DWARFUnit *dwarf_cu); - static dw_offset_t - DumpStatementTable(lldb_private::Log *log, - const lldb_private::DWARFDataExtractor &debug_line_data, - const dw_offset_t line_offset); - static dw_offset_t - DumpStatementOpcodes(lldb_private::Log *log, - const lldb_private::DWARFDataExtractor &debug_line_data, - const dw_offset_t line_offset, uint32_t flags); static bool ParseStatementTable(const lldb_private::DWARFDataExtractor &debug_line_data, lldb::offset_t *offset_ptr, LineTable *line_table,
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.cpp deleted file mode 100644 index 19074b8..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.cpp +++ /dev/null
@@ -1,39 +0,0 @@ -//===-- DWARFDebugMacinfo.cpp -----------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "DWARFDebugMacinfo.h" - -#include "DWARFDebugMacinfoEntry.h" -#include "SymbolFileDWARF.h" - -#include "lldb/Utility/Stream.h" - -using namespace lldb_private; -using namespace std; - -DWARFDebugMacinfo::DWARFDebugMacinfo() {} - -DWARFDebugMacinfo::~DWARFDebugMacinfo() {} - -void DWARFDebugMacinfo::Dump(Stream *s, const DWARFDataExtractor &macinfo_data, - lldb::offset_t offset) { - DWARFDebugMacinfoEntry maninfo_entry; - if (macinfo_data.GetByteSize() == 0) { - s->PutCString("< EMPTY >\n"); - return; - } - if (offset == LLDB_INVALID_OFFSET) { - offset = 0; - while (maninfo_entry.Extract(macinfo_data, &offset)) - maninfo_entry.Dump(s); - } else { - if (maninfo_entry.Extract(macinfo_data, &offset)) - maninfo_entry.Dump(s); - } -}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.h deleted file mode 100644 index ec9dc85..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.h +++ /dev/null
@@ -1,26 +0,0 @@ -//===-- DWARFDebugMacinfo.h -------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef SymbolFileDWARF_DWARFDebugMacinfo_h_ -#define SymbolFileDWARF_DWARFDebugMacinfo_h_ - -#include "SymbolFileDWARF.h" - -class DWARFDebugMacinfo { -public: - DWARFDebugMacinfo(); - - ~DWARFDebugMacinfo(); - - static void Dump(lldb_private::Stream *s, - const lldb_private::DWARFDataExtractor &macinfo_data, - lldb::offset_t offset = LLDB_INVALID_OFFSET); -}; - -#endif // SymbolFileDWARF_DWARFDebugMacinfo_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.cpp deleted file mode 100644 index f078fbd..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.cpp +++ /dev/null
@@ -1,111 +0,0 @@ -//===-- DWARFDebugMacinfoEntry.cpp ------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "DWARFDebugMacinfoEntry.h" - -#include "lldb/Utility/Stream.h" - -using namespace lldb_private; -using namespace std; - -DWARFDebugMacinfoEntry::DWARFDebugMacinfoEntry() - : m_type_code(0), m_line(0), m_op2() { - m_op2.cstr = NULL; -} - -DWARFDebugMacinfoEntry::~DWARFDebugMacinfoEntry() {} - -const char *DWARFDebugMacinfoEntry::GetCString() const { - switch (m_type_code) { - case 0: - case DW_MACINFO_start_file: - case DW_MACINFO_end_file: - return NULL; - default: - break; - } - return m_op2.cstr; -} - -void DWARFDebugMacinfoEntry::Dump(Stream *s) const { - if (m_type_code) { - s->PutCString(DW_MACINFO_value_to_name(m_type_code)); - - switch (m_type_code) { - case DW_MACINFO_define: - s->Printf(" line:%u #define %s\n", (uint32_t)m_line, m_op2.cstr); - break; - - case DW_MACINFO_undef: - s->Printf(" line:%u #undef %s\n", (uint32_t)m_line, m_op2.cstr); - break; - - default: - s->Printf(" line:%u str: '%s'\n", (uint32_t)m_line, m_op2.cstr); - break; - - case DW_MACINFO_start_file: - s->Printf(" line:%u file index: '%u'\n", (uint32_t)m_line, - (uint32_t)m_op2.file_idx); - break; - - case DW_MACINFO_end_file: - break; - } - } else { - s->PutCString(" END\n"); - } -} - -bool DWARFDebugMacinfoEntry::Extract(const DWARFDataExtractor &mac_info_data, - lldb::offset_t *offset_ptr) { - if (mac_info_data.ValidOffset(*offset_ptr)) { - m_type_code = mac_info_data.GetU8(offset_ptr); - - switch (m_type_code) { - - case DW_MACINFO_define: - case DW_MACINFO_undef: - // 2 operands: - // Arg 1: operand encodes the line number of the source line on which - // the relevant defining or undefining pre-processor directives - // appeared. - m_line = mac_info_data.GetULEB128(offset_ptr); - // Arg 2: define string - m_op2.cstr = mac_info_data.GetCStr(offset_ptr); - break; - - case DW_MACINFO_start_file: - // 2 operands: - // Op 1: line number of the source line on which the inclusion - // pre-processor directive occurred. - m_line = mac_info_data.GetULEB128(offset_ptr); - // Op 2: a source file name index to a file number in the statement - // information table for the relevant compilation unit. - m_op2.file_idx = mac_info_data.GetULEB128(offset_ptr); - break; - - case 0: // End of list - case DW_MACINFO_end_file: - // No operands - m_line = DW_INVALID_OFFSET; - m_op2.cstr = NULL; - break; - default: - // Vendor specific entries always have a ULEB128 and a string - m_line = mac_info_data.GetULEB128(offset_ptr); - m_op2.cstr = mac_info_data.GetCStr(offset_ptr); - break; - } - return true; - } else - m_type_code = 0; - - return false; -}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.h deleted file mode 100644 index 96829c2..0000000 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.h +++ /dev/null
@@ -1,42 +0,0 @@ -//===-- DWARFDebugMacinfoEntry.h --------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef SymbolFileDWARF_DWARFDebugMacinfoEntry_h_ -#define SymbolFileDWARF_DWARFDebugMacinfoEntry_h_ - -#include "SymbolFileDWARF.h" - -class DWARFDebugMacinfoEntry { -public: - DWARFDebugMacinfoEntry(); - - ~DWARFDebugMacinfoEntry(); - - uint8_t TypeCode() const { return m_type_code; } - - uint8_t GetLineNumber() const { return m_line; } - - void Dump(lldb_private::Stream *s) const; - - const char *GetCString() const; - - bool Extract(const lldb_private::DWARFDataExtractor &mac_info_data, - lldb::offset_t *offset_ptr); - -protected: -private: - uint8_t m_type_code; - dw_uleb128_t m_line; - union { - dw_uleb128_t file_idx; - const char *cstr; - } m_op2; -}; - -#endif // SymbolFileDWARF_DWARFDebugMacinfoEntry_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.cpp index d79acdc..4238be7 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.cpp
@@ -1,9 +1,8 @@ //===-- DWARFDebugMacro.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.h index 021b434..c3a93a9 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacro.h
@@ -1,10 +1,9 @@ //===-- DWARFDebugMacro.h ----------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.cpp index a0436dd..207c712 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.cpp
@@ -1,20 +1,16 @@ //===-- DWARFDebugRanges.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DWARFDebugRanges.h" #include "DWARFUnit.h" -#include "SymbolFileDWARF.h" #include "lldb/Utility/Stream.h" -#include <assert.h> using namespace lldb_private; -using namespace std; static dw_addr_t GetBaseAddressMarker(uint32_t addr_size) { switch(addr_size) { @@ -30,25 +26,24 @@ DWARFDebugRanges::DWARFDebugRanges() : m_range_map() {} -void DWARFDebugRanges::Extract(SymbolFileDWARF *dwarf2Data) { +void DWARFDebugRanges::Extract(DWARFContext &context) { DWARFRangeList range_list; lldb::offset_t offset = 0; dw_offset_t debug_ranges_offset = offset; - while (Extract(dwarf2Data, &offset, range_list)) { + while (Extract(context, &offset, range_list)) { range_list.Sort(); m_range_map[debug_ranges_offset] = range_list; debug_ranges_offset = offset; } } -bool DWARFDebugRanges::Extract(SymbolFileDWARF *dwarf2Data, +bool DWARFDebugRanges::Extract(DWARFContext &context, lldb::offset_t *offset_ptr, DWARFRangeList &range_list) { range_list.Clear(); lldb::offset_t range_offset = *offset_ptr; - const DWARFDataExtractor &debug_ranges_data = - dwarf2Data->get_debug_ranges_data(); + const DWARFDataExtractor &debug_ranges_data = context.getOrLoadRangesData(); uint32_t addr_size = debug_ranges_data.GetAddressByteSize(); dw_addr_t base_addr = 0; dw_addr_t base_addr_marker = GetBaseAddressMarker(addr_size); @@ -106,7 +101,7 @@ dw_addr_t begin_addr = begin + base_addr; dw_addr_t end_addr = end + base_addr; - s.AddressRange(begin_addr, end_addr, sizeof(dw_addr_t), NULL); + s.AddressRange(begin_addr, end_addr, sizeof(dw_addr_t), nullptr); } } } @@ -205,8 +200,10 @@ uint32_t index_size = cu->GetAddressByteSize(); dw_offset_t addr_base = cu->GetAddrBase(); lldb::offset_t offset = addr_base + index * index_size; - return cu->GetSymbolFileDWARF()->get_debug_addr_data().GetMaxU64(&offset, - index_size); + return cu->GetSymbolFileDWARF() + .GetDWARFContext() + .getOrLoadAddrData() + .GetMaxU64(&offset, index_size); } bool DWARFDebugRngLists::FindRanges(const DWARFUnit *cu, @@ -256,14 +253,12 @@ return false; } -void DWARFDebugRngLists::Extract(SymbolFileDWARF *dwarf2Data) { - const DWARFDataExtractor &data = dwarf2Data->get_debug_rnglists_data(); +void DWARFDebugRngLists::Extract(DWARFContext &context) { + const DWARFDataExtractor &data = context.getOrLoadRngListsData(); lldb::offset_t offset = 0; uint64_t length = data.GetU32(&offset); - bool isDwarf64 = (length == 0xffffffff); - if (isDwarf64) - length = data.GetU64(&offset); + // FIXME: Handle DWARF64. lldb::offset_t end = offset + length; // Check version. @@ -280,7 +275,7 @@ uint32_t offsetsAmount = data.GetU32(&offset); for (uint32_t i = 0; i < offsetsAmount; ++i) - Offsets.push_back(data.GetMaxU64(&offset, isDwarf64 ? 8 : 4)); + Offsets.push_back(data.GetMaxU64(&offset, 4)); lldb::offset_t listOffset = offset; std::vector<RngListEntry> rangeList;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.h index 5790f44..baf2667 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugRanges.h
@@ -1,25 +1,27 @@ //===-- DWARFDebugRanges.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 SymbolFileDWARF_DWARFDebugRanges_h_ #define SymbolFileDWARF_DWARFDebugRanges_h_ -#include "DWARFDIE.h" -#include "SymbolFileDWARF.h" - +#include "lldb/Core/dwarf.h" #include <map> +class DWARFUnit; +namespace lldb_private { +class DWARFContext; +} + class DWARFDebugRangesBase { public: virtual ~DWARFDebugRangesBase(){}; - virtual void Extract(SymbolFileDWARF *dwarf2Data) = 0; + virtual void Extract(lldb_private::DWARFContext &context) = 0; virtual bool FindRanges(const DWARFUnit *cu, dw_offset_t debug_ranges_offset, DWARFRangeList &range_list) const = 0; virtual uint64_t GetOffset(size_t Index) const = 0; @@ -29,7 +31,7 @@ public: DWARFDebugRanges(); - void Extract(SymbolFileDWARF *dwarf2Data) override; + void Extract(lldb_private::DWARFContext &context) override; bool FindRanges(const DWARFUnit *cu, dw_offset_t debug_ranges_offset, DWARFRangeList &range_list) const override; uint64_t GetOffset(size_t Index) const override; @@ -39,7 +41,7 @@ lldb::offset_t *offset_ptr, dw_addr_t cu_base_addr); protected: - bool Extract(SymbolFileDWARF *dwarf2Data, lldb::offset_t *offset_ptr, + bool Extract(lldb_private::DWARFContext &context, lldb::offset_t *offset_ptr, DWARFRangeList &range_list); typedef std::map<dw_offset_t, DWARFRangeList> range_map; @@ -57,7 +59,7 @@ }; public: - void Extract(SymbolFileDWARF *dwarf2Data) override; + void Extract(lldb_private::DWARFContext &context) override; bool FindRanges(const DWARFUnit *cu, dw_offset_t debug_ranges_offset, DWARFRangeList &range_list) const override; uint64_t GetOffset(size_t Index) const override;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.cpp index dbaf0b0..a664314 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.cpp
@@ -1,9 +1,8 @@ //===-- DWARFDeclContext.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,7 +29,7 @@ for (pos = begin; pos != end; ++pos) { if (pos != begin) m_qualified_name.append("::"); - if (pos->name == NULL) { + if (pos->name == nullptr) { if (pos->tag == DW_TAG_namespace) m_qualified_name.append("(anonymous namespace)"); else if (pos->tag == DW_TAG_class_type) @@ -48,7 +47,7 @@ } } if (m_qualified_name.empty()) - return NULL; + return nullptr; return m_qualified_name.c_str(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.h index aff5ea6..d0d70dd 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDeclContext.h
@@ -1,9 +1,8 @@ //===-- DWARFDeclContext.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,18 +14,16 @@ #include "lldb/Utility/ConstString.h" #include "DWARFDefines.h" -//---------------------------------------------------------------------- // DWARFDeclContext // // A class that represents a declaration context all the way down to a // DIE. This is useful when trying to find a DIE in one DWARF to a DIE // in another DWARF file. -//---------------------------------------------------------------------- class DWARFDeclContext { public: struct Entry { - Entry() : tag(0), name(NULL) {} + Entry() : tag(0), name(nullptr) {} Entry(dw_tag_t t, const char *n) : tag(t), name(n) {} bool NameMatches(const Entry &rhs) const {
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp index 99becdb..3bf0bb0 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp
@@ -1,9 +1,8 @@ //===-- DWARFDefines.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,17 +28,6 @@ return llvmstr.data(); } -const char *DW_CHILDREN_value_to_name(uint8_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::ChildrenString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_CHILDREN constant: 0x%x", - val); - return invalid; - } - return llvmstr.data(); -} - const char *DW_AT_value_to_name(uint32_t val) { static char invalid[100]; llvm::StringRef llvmstr = llvm::dwarf::AttributeString(val); @@ -391,38 +379,6 @@ return llvmstr.data(); } -const char *DW_ACCESS_value_to_name(uint32_t val) { - static char invalid[100]; - - llvm::StringRef llvmstr = llvm::dwarf::AccessibilityString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_ACCESS constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - -const char *DW_VIS_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::VisibilityString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_VIS constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - -const char *DW_VIRTUALITY_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::VirtualityString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_VIRTUALITY constant: 0x%x", - val); - return invalid; - } - return llvmstr.data(); -} - const char *DW_LANG_value_to_name(uint32_t val) { static char invalid[100]; llvm::StringRef llvmstr = llvm::dwarf::LanguageString(val); @@ -433,46 +389,6 @@ return llvmstr.data(); } -const char *DW_ID_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::CaseString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_ID constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - -const char *DW_CC_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::ConventionString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_CC constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - -const char *DW_INL_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::InlineCodeString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_INL constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - -const char *DW_ORD_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::ArrayOrderString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_ORD constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - const char *DW_LNS_value_to_name(uint32_t val) { static char invalid[100]; llvm::StringRef llvmstr = llvm::dwarf::LNStandardString(val); @@ -483,157 +399,4 @@ return llvmstr.data(); } -const char *DW_LNE_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::LNExtendedString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_LNE constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - -const char *DW_MACINFO_value_to_name(uint32_t val) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::MacinfoString(val); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_MACINFO constant: 0x%x", - val); - return invalid; - } - return llvmstr.data(); -} - -const char *DW_CFA_value_to_name(uint32_t val, llvm::Triple::ArchType Arch) { - static char invalid[100]; - llvm::StringRef llvmstr = llvm::dwarf::CallFrameString(val, Arch); - if (llvmstr.empty()) { - snprintf(invalid, sizeof(invalid), "Unknown DW_CFA constant: 0x%x", val); - return invalid; - } - return llvmstr.data(); -} - -DW_TAG_CategoryEnum get_tag_category(uint16_t tag) { - switch (tag) { - case DW_TAG_array_type: - return TagCategoryType; - case DW_TAG_class_type: - return TagCategoryType; - case DW_TAG_entry_point: - return TagCategoryProgram; - case DW_TAG_enumeration_type: - return TagCategoryType; - case DW_TAG_formal_parameter: - return TagCategoryVariable; - case DW_TAG_imported_declaration: - return TagCategoryProgram; - case DW_TAG_label: - return TagCategoryProgram; - case DW_TAG_lexical_block: - return TagCategoryProgram; - case DW_TAG_member: - return TagCategoryType; - case DW_TAG_pointer_type: - return TagCategoryType; - case DW_TAG_reference_type: - return TagCategoryType; - case DW_TAG_compile_unit: - return TagCategoryProgram; - case DW_TAG_string_type: - return TagCategoryType; - case DW_TAG_structure_type: - return TagCategoryType; - case DW_TAG_subroutine_type: - return TagCategoryType; - case DW_TAG_typedef: - return TagCategoryType; - case DW_TAG_union_type: - return TagCategoryType; - case DW_TAG_unspecified_parameters: - return TagCategoryVariable; - case DW_TAG_variant: - return TagCategoryType; - case DW_TAG_common_block: - return TagCategoryProgram; - case DW_TAG_common_inclusion: - return TagCategoryProgram; - case DW_TAG_inheritance: - return TagCategoryType; - case DW_TAG_inlined_subroutine: - return TagCategoryProgram; - case DW_TAG_module: - return TagCategoryProgram; - case DW_TAG_ptr_to_member_type: - return TagCategoryType; - case DW_TAG_set_type: - return TagCategoryType; - case DW_TAG_subrange_type: - return TagCategoryType; - case DW_TAG_with_stmt: - return TagCategoryProgram; - case DW_TAG_access_declaration: - return TagCategoryProgram; - case DW_TAG_base_type: - return TagCategoryType; - case DW_TAG_catch_block: - return TagCategoryProgram; - case DW_TAG_const_type: - return TagCategoryType; - case DW_TAG_constant: - return TagCategoryVariable; - case DW_TAG_enumerator: - return TagCategoryType; - case DW_TAG_file_type: - return TagCategoryType; - case DW_TAG_friend: - return TagCategoryType; - case DW_TAG_namelist: - return TagCategoryVariable; - case DW_TAG_namelist_item: - return TagCategoryVariable; - case DW_TAG_packed_type: - return TagCategoryType; - case DW_TAG_subprogram: - return TagCategoryProgram; - case DW_TAG_template_type_parameter: - return TagCategoryType; - case DW_TAG_template_value_parameter: - return TagCategoryType; - case DW_TAG_GNU_template_parameter_pack: - return TagCategoryType; - case DW_TAG_thrown_type: - return TagCategoryType; - case DW_TAG_try_block: - return TagCategoryProgram; - case DW_TAG_variant_part: - return TagCategoryType; - case DW_TAG_variable: - return TagCategoryVariable; - case DW_TAG_volatile_type: - return TagCategoryType; - case DW_TAG_dwarf_procedure: - return TagCategoryProgram; - case DW_TAG_restrict_type: - return TagCategoryType; - case DW_TAG_interface_type: - return TagCategoryType; - case DW_TAG_namespace: - return TagCategoryProgram; - case DW_TAG_imported_module: - return TagCategoryProgram; - case DW_TAG_unspecified_type: - return TagCategoryType; - case DW_TAG_partial_unit: - return TagCategoryProgram; - case DW_TAG_imported_unit: - return TagCategoryProgram; - case DW_TAG_shared_type: - return TagCategoryType; - default: - break; - } - return TagCategoryProgram; -} - } // namespace lldb_private
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.h index 0f5a885..d16cb07 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.h
@@ -1,9 +1,8 @@ //===-- DWARFDefines.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,23 +14,12 @@ namespace lldb_private { +enum class DWARFEnumState { MoreItems, Complete }; + typedef uint32_t DRC_class; // Holds DRC_* class bitfields -enum DW_TAG_Category { - TagCategoryVariable, - TagCategoryType, - TagCategoryProgram, - kNumTagCategories -}; - -typedef enum DW_TAG_Category DW_TAG_CategoryEnum; - const char *DW_TAG_value_to_name(uint32_t val); -DW_TAG_CategoryEnum get_tag_category(uint16_t tag); - -const char *DW_CHILDREN_value_to_name(uint8_t val); - const char *DW_AT_value_to_name(uint32_t val); const char *DW_FORM_value_to_name(uint32_t val); @@ -42,32 +30,10 @@ const char *DW_ATE_value_to_name(uint32_t val); -const char *DW_ACCESS_value_to_name(uint32_t val); - -const char *DW_VIS_value_to_name(uint32_t val); - -const char *DW_VIRTUALITY_value_to_name(uint32_t val); - const char *DW_LANG_value_to_name(uint32_t val); -const char *DW_ID_value_to_name(uint32_t val); - -const char *DW_CC_value_to_name(uint32_t val); - -const char *DW_INL_value_to_name(uint32_t val); - -const char *DW_ORD_value_to_name(uint32_t val); - const char *DW_LNS_value_to_name(uint32_t val); -const char *DW_LNE_value_to_name(uint32_t val); - -const char *DW_MACINFO_value_to_name(uint32_t val); - -const char *DW_CFA_value_to_name(uint32_t val, llvm::Triple::ArchType Arch); - -const char *DW_GNU_EH_PE_value_to_name(uint32_t val); - /* These DRC are entirely our own construction, although they are derived from various comments in the DWARF standard. Most of these are not useful to the parser, but the DW_AT and DW_FORM
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.cpp index 5d2a8ff..046ae67 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.cpp
@@ -1,169 +1,30 @@ //===-- DWARFFormValue.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <assert.h> +#include "lldb/Core/Module.h" #include "lldb/Core/dwarf.h" +#include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/Stream.h" -#include "DWARFUnit.h" +#include "DWARFDebugInfo.h" #include "DWARFFormValue.h" +#include "DWARFUnit.h" class DWARFUnit; using namespace lldb_private; -static uint8_t g_form_sizes_addr4[] = { - 0, // 0x00 unused - 4, // 0x01 DW_FORM_addr - 0, // 0x02 unused - 0, // 0x03 DW_FORM_block2 - 0, // 0x04 DW_FORM_block4 - 2, // 0x05 DW_FORM_data2 - 4, // 0x06 DW_FORM_data4 - 8, // 0x07 DW_FORM_data8 - 0, // 0x08 DW_FORM_string - 0, // 0x09 DW_FORM_block - 0, // 0x0a DW_FORM_block1 - 1, // 0x0b DW_FORM_data1 - 1, // 0x0c DW_FORM_flag - 0, // 0x0d DW_FORM_sdata - 4, // 0x0e DW_FORM_strp - 0, // 0x0f DW_FORM_udata - 0, // 0x10 DW_FORM_ref_addr (addr size for DWARF2 and earlier, 4 bytes for - // DWARF32, 8 bytes for DWARF32 in DWARF 3 and later - 1, // 0x11 DW_FORM_ref1 - 2, // 0x12 DW_FORM_ref2 - 4, // 0x13 DW_FORM_ref4 - 8, // 0x14 DW_FORM_ref8 - 0, // 0x15 DW_FORM_ref_udata - 0, // 0x16 DW_FORM_indirect - 4, // 0x17 DW_FORM_sec_offset - 0, // 0x18 DW_FORM_exprloc - 0, // 0x19 DW_FORM_flag_present - 0, // 0x1a - 0, // 0x1b - 0, // 0x1c - 0, // 0x1d - 0, // 0x1e - 0, // 0x1f - 8, // 0x20 DW_FORM_ref_sig8 - -}; - -static uint8_t g_form_sizes_addr8[] = { - 0, // 0x00 unused - 8, // 0x01 DW_FORM_addr - 0, // 0x02 unused - 0, // 0x03 DW_FORM_block2 - 0, // 0x04 DW_FORM_block4 - 2, // 0x05 DW_FORM_data2 - 4, // 0x06 DW_FORM_data4 - 8, // 0x07 DW_FORM_data8 - 0, // 0x08 DW_FORM_string - 0, // 0x09 DW_FORM_block - 0, // 0x0a DW_FORM_block1 - 1, // 0x0b DW_FORM_data1 - 1, // 0x0c DW_FORM_flag - 0, // 0x0d DW_FORM_sdata - 4, // 0x0e DW_FORM_strp - 0, // 0x0f DW_FORM_udata - 0, // 0x10 DW_FORM_ref_addr (addr size for DWARF2 and earlier, 4 bytes for - // DWARF32, 8 bytes for DWARF32 in DWARF 3 and later - 1, // 0x11 DW_FORM_ref1 - 2, // 0x12 DW_FORM_ref2 - 4, // 0x13 DW_FORM_ref4 - 8, // 0x14 DW_FORM_ref8 - 0, // 0x15 DW_FORM_ref_udata - 0, // 0x16 DW_FORM_indirect - 4, // 0x17 DW_FORM_sec_offset - 0, // 0x18 DW_FORM_exprloc - 0, // 0x19 DW_FORM_flag_present - 0, // 0x1a - 0, // 0x1b - 0, // 0x1c - 0, // 0x1d - 0, // 0x1e - 0, // 0x1f - 8, // 0x20 DW_FORM_ref_sig8 -}; - -// Difference with g_form_sizes_addr8: -// DW_FORM_strp and DW_FORM_sec_offset are 8 instead of 4 -static uint8_t g_form_sizes_addr8_dwarf64[] = { - 0, // 0x00 unused - 8, // 0x01 DW_FORM_addr - 0, // 0x02 unused - 0, // 0x03 DW_FORM_block2 - 0, // 0x04 DW_FORM_block4 - 2, // 0x05 DW_FORM_data2 - 4, // 0x06 DW_FORM_data4 - 8, // 0x07 DW_FORM_data8 - 0, // 0x08 DW_FORM_string - 0, // 0x09 DW_FORM_block - 0, // 0x0a DW_FORM_block1 - 1, // 0x0b DW_FORM_data1 - 1, // 0x0c DW_FORM_flag - 0, // 0x0d DW_FORM_sdata - 8, // 0x0e DW_FORM_strp - 0, // 0x0f DW_FORM_udata - 0, // 0x10 DW_FORM_ref_addr (addr size for DWARF2 and earlier, 4 bytes for - // DWARF32, 8 bytes for DWARF32 in DWARF 3 and later - 1, // 0x11 DW_FORM_ref1 - 2, // 0x12 DW_FORM_ref2 - 4, // 0x13 DW_FORM_ref4 - 8, // 0x14 DW_FORM_ref8 - 0, // 0x15 DW_FORM_ref_udata - 0, // 0x16 DW_FORM_indirect - 8, // 0x17 DW_FORM_sec_offset - 0, // 0x18 DW_FORM_exprloc - 0, // 0x19 DW_FORM_flag_present - 0, // 0x1a - 0, // 0x1b - 0, // 0x1c - 0, // 0x1d - 0, // 0x1e - 0, // 0x1f - 8, // 0x20 DW_FORM_ref_sig8 -}; - -DWARFFormValue::FixedFormSizes -DWARFFormValue::GetFixedFormSizesForAddressSize(uint8_t addr_size, - bool is_dwarf64) { - if (!is_dwarf64) { - switch (addr_size) { - case 4: - return FixedFormSizes(g_form_sizes_addr4, sizeof(g_form_sizes_addr4)); - case 8: - return FixedFormSizes(g_form_sizes_addr8, sizeof(g_form_sizes_addr8)); - } - } else { - if (addr_size == 8) - return FixedFormSizes(g_form_sizes_addr8_dwarf64, - sizeof(g_form_sizes_addr8_dwarf64)); - // is_dwarf64 && addr_size == 4 : no provider does this. - } - return FixedFormSizes(); -} - -DWARFFormValue::DWARFFormValue() : m_cu(NULL), m_form(0), m_value() {} - -DWARFFormValue::DWARFFormValue(const DWARFUnit *cu) - : m_cu(cu), m_form(0), m_value() {} - -DWARFFormValue::DWARFFormValue(const DWARFUnit *cu, dw_form_t form) - : m_cu(cu), m_form(form), m_value() {} - void DWARFFormValue::Clear() { - m_cu = nullptr; + m_unit = nullptr; m_form = 0; - memset(&m_value, 0, sizeof(m_value)); + m_value = ValueTypeTag(); } bool DWARFFormValue::ExtractValue(const DWARFDataExtractor &data, @@ -173,7 +34,7 @@ bool indirect = false; bool is_block = false; - m_value.data = NULL; + m_value.data = nullptr; uint8_t ref_addr_size; // Read the value for the form into value and follow and DW_FORM_indirect // instances we run into @@ -181,9 +42,9 @@ indirect = false; switch (m_form) { case DW_FORM_addr: - assert(m_cu); + assert(m_unit); m_value.value.uval = - data.GetMaxU64(offset_ptr, DWARFUnit::GetAddressByteSize(m_cu)); + data.GetMaxU64(offset_ptr, DWARFUnit::GetAddressByteSize(m_unit)); break; case DW_FORM_block1: m_value.value.uval = data.GetU8(offset_ptr); @@ -215,9 +76,7 @@ case DW_FORM_strp: case DW_FORM_line_strp: case DW_FORM_sec_offset: - assert(m_cu); - m_value.value.uval = - data.GetMaxU64(offset_ptr, DWARFUnit::IsDWARF64(m_cu) ? 8 : 4); + m_value.value.uval = data.GetMaxU64(offset_ptr, 4); break; case DW_FORM_addrx1: case DW_FORM_strx1: @@ -257,11 +116,11 @@ m_value.value.uval = data.GetULEB128(offset_ptr); break; case DW_FORM_ref_addr: - assert(m_cu); - if (m_cu->GetVersion() <= 2) - ref_addr_size = m_cu->GetAddressByteSize(); + assert(m_unit); + if (m_unit->GetVersion() <= 2) + ref_addr_size = m_unit->GetAddressByteSize(); else - ref_addr_size = m_cu->IsDWARF64() ? 8 : 4; + ref_addr_size = 4; m_value.value.uval = data.GetMaxU64(offset_ptr, ref_addr_size); break; case DW_FORM_indirect: @@ -278,7 +137,7 @@ if (is_block) { m_value.data = data.PeekData(*offset_ptr, m_value.value.uval); - if (m_value.data != NULL) { + if (m_value.data != nullptr) { *offset_ptr += m_value.value.uval; } } @@ -286,15 +145,68 @@ return true; } +struct FormSize { + uint8_t valid:1, size:7; +}; +static FormSize g_form_sizes[] = { + {0,0}, // 0x00 unused + {0,0}, // 0x01 DW_FORM_addr + {0,0}, // 0x02 unused + {0,0}, // 0x03 DW_FORM_block2 + {0,0}, // 0x04 DW_FORM_block4 + {1,2}, // 0x05 DW_FORM_data2 + {1,4}, // 0x06 DW_FORM_data4 + {1,8}, // 0x07 DW_FORM_data8 + {0,0}, // 0x08 DW_FORM_string + {0,0}, // 0x09 DW_FORM_block + {0,0}, // 0x0a DW_FORM_block1 + {1,1}, // 0x0b DW_FORM_data1 + {1,1}, // 0x0c DW_FORM_flag + {0,0}, // 0x0d DW_FORM_sdata + {1,4}, // 0x0e DW_FORM_strp + {0,0}, // 0x0f DW_FORM_udata + {0,0}, // 0x10 DW_FORM_ref_addr (addr size for DWARF2 and earlier, 4 bytes for + // DWARF32, 8 bytes for DWARF32 in DWARF 3 and later + {1,1}, // 0x11 DW_FORM_ref1 + {1,2}, // 0x12 DW_FORM_ref2 + {1,4}, // 0x13 DW_FORM_ref4 + {1,8}, // 0x14 DW_FORM_ref8 + {0,0}, // 0x15 DW_FORM_ref_udata + {0,0}, // 0x16 DW_FORM_indirect + {1,4}, // 0x17 DW_FORM_sec_offset + {0,0}, // 0x18 DW_FORM_exprloc + {1,0}, // 0x19 DW_FORM_flag_present + {0,0}, // 0x1a + {0,0}, // 0x1b + {0,0}, // 0x1c + {0,0}, // 0x1d + {0,0}, // 0x1e + {0,0}, // 0x1f + {1,8}, // 0x20 DW_FORM_ref_sig8 +}; + +llvm::Optional<uint8_t> +DWARFFormValue::GetFixedSize(dw_form_t form, const DWARFUnit *u) { + if (form <= DW_FORM_ref_sig8 && g_form_sizes[form].valid) + return g_form_sizes[form].size; + if (form == DW_FORM_addr && u) + return u->GetAddressByteSize(); + return llvm::None; +} + +llvm::Optional<uint8_t> DWARFFormValue::GetFixedSize() const { + return GetFixedSize(m_form, m_unit); +} + bool DWARFFormValue::SkipValue(const DWARFDataExtractor &debug_info_data, lldb::offset_t *offset_ptr) const { - return DWARFFormValue::SkipValue(m_form, debug_info_data, offset_ptr, m_cu); + return DWARFFormValue::SkipValue(m_form, debug_info_data, offset_ptr, m_unit); } bool DWARFFormValue::SkipValue(dw_form_t form, const DWARFDataExtractor &debug_info_data, lldb::offset_t *offset_ptr, - const DWARFUnit *cu) { + const DWARFUnit *unit) { uint8_t ref_addr_size; switch (form) { // Blocks if inlined data that have a length field and the data bytes inlined @@ -328,17 +240,17 @@ // Compile unit address sized values case DW_FORM_addr: - *offset_ptr += DWARFUnit::GetAddressByteSize(cu); + *offset_ptr += DWARFUnit::GetAddressByteSize(unit); return true; case DW_FORM_ref_addr: ref_addr_size = 4; - assert(cu); // CU must be valid for DW_FORM_ref_addr objects or we will get - // this wrong - if (cu->GetVersion() <= 2) - ref_addr_size = cu->GetAddressByteSize(); + assert(unit); // Unit must be valid for DW_FORM_ref_addr objects or we will + // get this wrong + if (unit->GetVersion() <= 2) + ref_addr_size = unit->GetAddressByteSize(); else - ref_addr_size = cu->IsDWARF64() ? 8 : 4; + ref_addr_size = 4; *offset_ptr += ref_addr_size; return true; @@ -373,8 +285,7 @@ // 32 bit for DWARF 32, 64 for DWARF 64 case DW_FORM_sec_offset: case DW_FORM_strp: - assert(cu); - *offset_ptr += (cu->IsDWARF64() ? 8 : 4); + *offset_ptr += 4; return true; // 4 byte values @@ -407,7 +318,7 @@ case DW_FORM_indirect: { dw_form_t indirect_form = debug_info_data.GetULEB128(offset_ptr); return DWARFFormValue::SkipValue(indirect_form, debug_info_data, offset_ptr, - cu); + unit); } default: @@ -418,7 +329,7 @@ void DWARFFormValue::Dump(Stream &s) const { uint64_t uvalue = Unsigned(); - bool cu_relative_offset = false; + bool unit_relative_offset = false; switch (m_form) { case DW_FORM_addr: @@ -495,9 +406,9 @@ } break; case DW_FORM_ref_addr: { - assert(m_cu); // CU must be valid for DW_FORM_ref_addr objects or we will - // get this wrong - if (m_cu->GetVersion() <= 2) + assert(m_unit); // Unit must be valid for DW_FORM_ref_addr objects or we + // will get this wrong + if (m_unit->GetVersion() <= 2) s.Address(uvalue, sizeof(uint64_t) * 2); else s.Address(uvalue, 4 * 2); // 4 for DWARF32, 8 for DWARF64, but we don't @@ -505,19 +416,19 @@ break; } case DW_FORM_ref1: - cu_relative_offset = true; + unit_relative_offset = true; break; case DW_FORM_ref2: - cu_relative_offset = true; + unit_relative_offset = true; break; case DW_FORM_ref4: - cu_relative_offset = true; + unit_relative_offset = true; break; case DW_FORM_ref8: - cu_relative_offset = true; + unit_relative_offset = true; break; case DW_FORM_ref_udata: - cu_relative_offset = true; + unit_relative_offset = true; break; // All DW_FORM_indirect attributes should be resolved prior to calling this @@ -532,33 +443,29 @@ break; } - if (cu_relative_offset) { - assert(m_cu); // CU must be valid for DW_FORM_ref forms that are compile - // unit relative or we will get this wrong - s.Printf("{0x%8.8" PRIx64 "}", uvalue + m_cu->GetOffset()); + if (unit_relative_offset) { + assert(m_unit); // Unit must be valid for DW_FORM_ref forms that are compile + // unit relative or we will get this wrong + s.Printf("{0x%8.8" PRIx64 "}", uvalue + m_unit->GetOffset()); } } const char *DWARFFormValue::AsCString() const { - SymbolFileDWARF *symbol_file = m_cu->GetSymbolFileDWARF(); + SymbolFileDWARF &symbol_file = m_unit->GetSymbolFileDWARF(); if (m_form == DW_FORM_string) { return m_value.value.cstr; } else if (m_form == DW_FORM_strp) { - if (!symbol_file) - return nullptr; - - return symbol_file->get_debug_str_data().PeekCStr(m_value.value.uval); + return symbol_file.GetDWARFContext().getOrLoadStrData().PeekCStr( + m_value.value.uval); } else if (m_form == DW_FORM_GNU_str_index) { - if (!symbol_file) - return nullptr; - - uint32_t index_size = m_cu->IsDWARF64() ? 8 : 4; + uint32_t index_size = 4; lldb::offset_t offset = m_value.value.uval * index_size; dw_offset_t str_offset = - symbol_file->get_debug_str_offsets_data().GetMaxU64(&offset, - index_size); - return symbol_file->get_debug_str_data().PeekCStr(str_offset); + symbol_file.GetDWARFContext().getOrLoadStrOffsetsData().GetMaxU64( + &offset, index_size); + return symbol_file.GetDWARFContext().getOrLoadStrData().PeekCStr( + str_offset); } if (m_form == DW_FORM_strx || m_form == DW_FORM_strx1 || @@ -566,44 +473,41 @@ m_form == DW_FORM_strx4) { // The same code as above. - if (!symbol_file) - return nullptr; - - uint32_t indexSize = m_cu->IsDWARF64() ? 8 : 4; + uint32_t indexSize = 4; lldb::offset_t offset = - m_cu->GetStrOffsetsBase() + m_value.value.uval * indexSize; + m_unit->GetStrOffsetsBase() + m_value.value.uval * indexSize; dw_offset_t strOffset = - symbol_file->get_debug_str_offsets_data().GetMaxU64(&offset, indexSize); - return symbol_file->get_debug_str_data().PeekCStr(strOffset); + symbol_file.GetDWARFContext().getOrLoadStrOffsetsData().GetMaxU64( + &offset, indexSize); + return symbol_file.GetDWARFContext().getOrLoadStrData().PeekCStr(strOffset); } if (m_form == DW_FORM_line_strp) - return symbol_file->get_debug_line_str_data().PeekCStr(m_value.value.uval); + return symbol_file.GetDWARFContext().getOrLoadLineStrData().PeekCStr( + m_value.value.uval); return nullptr; } dw_addr_t DWARFFormValue::Address() const { - SymbolFileDWARF *symbol_file = m_cu->GetSymbolFileDWARF(); + SymbolFileDWARF &symbol_file = m_unit->GetSymbolFileDWARF(); if (m_form == DW_FORM_addr) return Unsigned(); - assert(m_cu); + assert(m_unit); assert(m_form == DW_FORM_GNU_addr_index || m_form == DW_FORM_addrx || m_form == DW_FORM_addrx1 || m_form == DW_FORM_addrx2 || m_form == DW_FORM_addrx3 || m_form == DW_FORM_addrx4); - if (!symbol_file) - return 0; - - uint32_t index_size = m_cu->GetAddressByteSize(); - dw_offset_t addr_base = m_cu->GetAddrBase(); + uint32_t index_size = m_unit->GetAddressByteSize(); + dw_offset_t addr_base = m_unit->GetAddrBase(); lldb::offset_t offset = addr_base + m_value.value.uval * index_size; - return symbol_file->get_debug_addr_data().GetMaxU64(&offset, index_size); + return symbol_file.GetDWARFContext().getOrLoadAddrData().GetMaxU64( + &offset, index_size); } -uint64_t DWARFFormValue::Reference() const { +DWARFDIE DWARFFormValue::Reference() const { uint64_t value = m_value.value.uval; switch (m_form) { case DW_FORM_ref1: @@ -611,17 +515,40 @@ case DW_FORM_ref4: case DW_FORM_ref8: case DW_FORM_ref_udata: - assert(m_cu); // CU must be valid for DW_FORM_ref forms that are compile - // unit relative or we will get this wrong - return value + m_cu->GetOffset(); + assert(m_unit); // Unit must be valid for DW_FORM_ref forms that are compile + // unit relative or we will get this wrong + value += m_unit->GetOffset(); + if (!m_unit->ContainsDIEOffset(value)) { + m_unit->GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError( + "DW_FORM_ref* DIE reference 0x%" PRIx64 " is outside of its CU", + value); + return {}; + } + return const_cast<DWARFUnit *>(m_unit)->GetDIE(value); - case DW_FORM_ref_addr: - case DW_FORM_ref_sig8: - case DW_FORM_GNU_ref_alt: - return value; + case DW_FORM_ref_addr: { + DWARFUnit *ref_cu = + m_unit->GetSymbolFileDWARF().DebugInfo()->GetUnitContainingDIEOffset( + DIERef::Section::DebugInfo, value); + if (!ref_cu) { + m_unit->GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError( + "DW_FORM_ref_addr DIE reference 0x%" PRIx64 " has no matching CU", + value); + return {}; + } + return ref_cu->GetDIE(value); + } + + case DW_FORM_ref_sig8: { + DWARFTypeUnit *tu = + m_unit->GetSymbolFileDWARF().DebugInfo()->GetTypeUnitForHash(value); + if (!tu) + return {}; + return tu->GetDIE(tu->GetTypeOffset()); + } default: - return DW_INVALID_OFFSET; + return {}; } } @@ -682,6 +609,7 @@ return 1; switch (a_form) { case DW_FORM_addr: + case DW_FORM_addrx: case DW_FORM_flag: case DW_FORM_data1: case DW_FORM_data2: @@ -721,7 +649,7 @@ return 0; else if (a_string && b_string) return strcmp(a_string, b_string); - else if (a_string == NULL) + else if (a_string == nullptr) return -1; // A string is NULL, and B is valid else return 1; // A string valid, and B is NULL @@ -747,8 +675,8 @@ case DW_FORM_ref4: case DW_FORM_ref8: case DW_FORM_ref_udata: { - uint64_t a = a_value.Reference(); - uint64_t b = b_value.Reference(); + uint64_t a = a_value.m_value.value.uval; + uint64_t b = b_value.m_value.value.uval; if (a < b) return -1; if (a > b)
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.h index 0890f0c..848db29 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFFormValue.h
@@ -1,9 +1,8 @@ //===-- DWARFFormValue.h ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,14 +11,16 @@ #include "DWARFDataExtractor.h" #include <stddef.h> +#include "llvm/ADT/Optional.h" class DWARFUnit; class SymbolFileDWARF; +class DWARFDIE; class DWARFFormValue { public: typedef struct ValueTypeTag { - ValueTypeTag() : value(), data(NULL) { value.uval = 0; } + ValueTypeTag() : value(), data(nullptr) { value.uval = 0; } union { uint64_t uval; @@ -29,24 +30,6 @@ const uint8_t *data; } ValueType; - class FixedFormSizes { - public: - FixedFormSizes() : m_fix_sizes(nullptr), m_size(0) {} - - FixedFormSizes(const uint8_t *fix_sizes, size_t size) - : m_fix_sizes(fix_sizes), m_size(size) {} - - uint8_t GetSize(uint32_t index) const { - return index < m_size ? m_fix_sizes[index] : 0; - } - - bool Empty() const { return m_size == 0; } - - private: - const uint8_t *m_fix_sizes; - size_t m_size; - }; - enum { eValueTypeInvalid = 0, eValueTypeUnsigned, @@ -55,11 +38,11 @@ eValueTypeBlock }; - DWARFFormValue(); - DWARFFormValue(const DWARFUnit *cu); - DWARFFormValue(const DWARFUnit *cu, dw_form_t form); - const DWARFUnit *GetCompileUnit() const { return m_cu; } - void SetCompileUnit(const DWARFUnit *cu) { m_cu = cu; } + DWARFFormValue() = default; + DWARFFormValue(const DWARFUnit *unit) : m_unit(unit) {} + DWARFFormValue(const DWARFUnit *unit, dw_form_t form) + : m_unit(unit), m_form(form) {} + void SetUnit(const DWARFUnit *unit) { m_unit = unit; } dw_form_t Form() const { return m_form; } dw_form_t& FormRef() { return m_form; } void SetForm(dw_form_t form) { m_form = form; } @@ -71,7 +54,10 @@ bool ExtractValue(const lldb_private::DWARFDataExtractor &data, lldb::offset_t *offset_ptr); const uint8_t *BlockData() const; - uint64_t Reference() const; + static llvm::Optional<uint8_t> GetFixedSize(dw_form_t form, + const DWARFUnit *u); + llvm::Optional<uint8_t> GetFixedSize() const; + DWARFDIE Reference() const; uint64_t Reference(dw_offset_t offset) const; bool Boolean() const { return m_value.value.uval != 0; } uint64_t Unsigned() const { return m_value.value.uval; } @@ -85,18 +71,18 @@ lldb::offset_t *offset_ptr) const; static bool SkipValue(const dw_form_t form, const lldb_private::DWARFDataExtractor &debug_info_data, - lldb::offset_t *offset_ptr, const DWARFUnit *cu); + lldb::offset_t *offset_ptr, const DWARFUnit *unit); static bool IsBlockForm(const dw_form_t form); static bool IsDataForm(const dw_form_t form); - static FixedFormSizes GetFixedFormSizesForAddressSize(uint8_t addr_size, - bool is_dwarf64); static int Compare(const DWARFFormValue &a, const DWARFFormValue &b); void Clear(); static bool FormIsSupported(dw_form_t form); protected: - const DWARFUnit *m_cu; // Compile unit for this form - dw_form_t m_form; // Form for this value + // Compile unit where m_value was located. + // It may be different from compile unit where m_value refers to. + const DWARFUnit *m_unit = nullptr; // Unit for this form + dw_form_t m_form = 0; // Form for this value ValueType m_value; // Contains all data for the form };
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.cpp index 4577f05..c122f75 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.cpp
@@ -1,17 +1,15 @@ //===-- DWARFIndex.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "Plugins/SymbolFile/DWARF/DWARFIndex.h" -#include "Plugins/SymbolFile/DWARF/DWARFDIE.h" -#include "Plugins/SymbolFile/DWARF/DWARFDebugInfo.h" - #include "Plugins/Language/ObjC/ObjCLanguage.h" +#include "Plugins/SymbolFile/DWARF/DWARFDIE.h" +#include "Plugins/SymbolFile/DWARF/SymbolFileDWARF.h" using namespace lldb_private; using namespace lldb; @@ -19,13 +17,13 @@ DWARFIndex::~DWARFIndex() = default; void DWARFIndex::ProcessFunctionDIE(llvm::StringRef name, DIERef ref, - DWARFDebugInfo &info, + SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) { - DWARFDIE die = info.GetDIE(ref); + DWARFDIE die = dwarf.GetDIE(ref); if (!die) { - ReportInvalidDIEOffset(ref.die_offset, name); + ReportInvalidDIERef(ref, name); return; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.h index 77af67b..e3c7c5e 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFIndex.h
@@ -1,9 +1,8 @@ //===-- DWARFIndex.h -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,7 +13,6 @@ #include "Plugins/SymbolFile/DWARF/DWARFDIE.h" #include "Plugins/SymbolFile/DWARF/DWARFFormValue.h" -class DWARFDebugInfo; class DWARFDeclContext; class DWARFDIE; @@ -41,15 +39,14 @@ virtual void GetTypes(ConstString name, DIEArray &offsets) = 0; virtual void GetTypes(const DWARFDeclContext &context, DIEArray &offsets) = 0; virtual void GetNamespaces(ConstString name, DIEArray &offsets) = 0; - virtual void GetFunctions(ConstString name, DWARFDebugInfo &info, + virtual void GetFunctions(ConstString name, SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) = 0; virtual void GetFunctions(const RegularExpression ®ex, DIEArray &offsets) = 0; - virtual void ReportInvalidDIEOffset(dw_offset_t offset, - llvm::StringRef name) = 0; + virtual void ReportInvalidDIERef(const DIERef &ref, llvm::StringRef name) = 0; virtual void Dump(Stream &s) = 0; protected: @@ -60,7 +57,7 @@ /// "parent_decl_ctx" and "name_type_mask", it is inserted into the "dies" /// vector. void ProcessFunctionDIE(llvm::StringRef name, DIERef ref, - DWARFDebugInfo &info, + SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies); };
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFTypeUnit.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFTypeUnit.cpp new file mode 100644 index 0000000..fcc031b --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFTypeUnit.cpp
@@ -0,0 +1,23 @@ +//===-- DWARFTypeUnit.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 "DWARFTypeUnit.h" + +#include "SymbolFileDWARF.h" +#include "lldb/Utility/Stream.h" + +using namespace lldb; +using namespace lldb_private; + +void DWARFTypeUnit::Dump(Stream *s) const { + s->Printf("0x%8.8x: Type Unit: length = 0x%8.8x, version = 0x%4.4x, " + "abbr_offset = 0x%8.8x, addr_size = 0x%2.2x (next CU at " + "{0x%8.8x})\n", + GetOffset(), GetLength(), GetVersion(), GetAbbrevOffset(), + GetAddressByteSize(), GetNextUnitOffset()); +}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFTypeUnit.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFTypeUnit.h new file mode 100644 index 0000000..6ff73ec --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFTypeUnit.h
@@ -0,0 +1,37 @@ +//===-- DWARFTypeUnit.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 SymbolFileDWARF_DWARFTypeUnit_h_ +#define SymbolFileDWARF_DWARFTypeUnit_h_ + +#include "DWARFUnit.h" +#include "llvm/Support/Error.h" + +class DWARFTypeUnit : public DWARFUnit { +public: + void BuildAddressRangeTable(DWARFDebugAranges *debug_aranges) override {} + + void Dump(lldb_private::Stream *s) const override; + + uint64_t GetTypeHash() { return m_header.GetTypeHash(); } + + dw_offset_t GetTypeOffset() { return GetOffset() + m_header.GetTypeOffset(); } + + static bool classof(const DWARFUnit *unit) { return unit->IsTypeUnit(); } + +private: + DWARFTypeUnit(SymbolFileDWARF &dwarf, lldb::user_id_t uid, + const DWARFUnitHeader &header, + const DWARFAbbreviationDeclarationSet &abbrevs, + DIERef::Section section) + : DWARFUnit(dwarf, uid, header, abbrevs, section) {} + + friend class DWARFUnit; +}; + +#endif // SymbolFileDWARF_DWARFTypeUnit_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp index 7afc71b..33e83d1 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
@@ -1,9 +1,8 @@ //===-- DWARFUnit.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,18 +10,17 @@ #include "lldb/Core/Module.h" #include "lldb/Host/StringConvert.h" -#include "lldb/Symbol/CompileUnit.h" -#include "lldb/Symbol/LineTable.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" +#include "llvm/Object/Error.h" -#include "DWARFDIECollection.h" +#include "DWARFCompileUnit.h" #include "DWARFDebugAranges.h" #include "DWARFDebugInfo.h" +#include "DWARFTypeUnit.h" #include "LogChannelDWARF.h" -#include "SymbolFileDWARFDebugMap.h" #include "SymbolFileDWARFDwo.h" using namespace lldb; @@ -31,14 +29,16 @@ extern int g_verbose; -DWARFUnit::DWARFUnit(SymbolFileDWARF *dwarf) - : m_dwarf(dwarf), m_cancel_scopes(false) {} +DWARFUnit::DWARFUnit(SymbolFileDWARF &dwarf, lldb::user_id_t uid, + const DWARFUnitHeader &header, + const DWARFAbbreviationDeclarationSet &abbrevs, + DIERef::Section section) + : UserID(uid), m_dwarf(dwarf), m_header(header), m_abbrevs(&abbrevs), + m_cancel_scopes(false), m_section(section) {} -DWARFUnit::~DWARFUnit() {} +DWARFUnit::~DWARFUnit() = default; -//---------------------------------------------------------------------- // Parses first DIE of a compile unit. -//---------------------------------------------------------------------- void DWARFUnit::ExtractUnitDIEIfNeeded() { { llvm::sys::ScopedReader lock(m_first_die_mutex); @@ -50,8 +50,8 @@ return; // Already parsed static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); - Timer scoped_timer( - func_cat, "%8.8x: DWARFUnit::ExtractUnitDIEIfNeeded()", m_offset); + Timer scoped_timer(func_cat, "%8.8x: DWARFUnit::ExtractUnitDIEIfNeeded()", + GetOffset()); // Set the offset to that of the first DIE and calculate the start of the // next compilation unit header. @@ -60,22 +60,15 @@ // We are in our compile unit, parse starting at the offset we were told to // parse const DWARFDataExtractor &data = GetData(); - DWARFFormValue::FixedFormSizes fixed_form_sizes = - DWARFFormValue::GetFixedFormSizesForAddressSize(GetAddressByteSize(), - IsDWARF64()); - if (offset < GetNextCompileUnitOffset() && - m_first_die.FastExtract(data, this, fixed_form_sizes, &offset)) { + if (offset < GetNextUnitOffset() && + m_first_die.Extract(data, this, &offset)) { AddUnitDIE(m_first_die); return; } - - ExtractDIEsEndCheck(offset); } -//---------------------------------------------------------------------- // Parses a compile unit and indexes its DIEs if it hasn't already been done. // It will leave this compile unit extracted forever. -//---------------------------------------------------------------------- void DWARFUnit::ExtractDIEsIfNeeded() { m_cancel_scopes = true; @@ -91,15 +84,13 @@ ExtractDIEsRWLocked(); } -//---------------------------------------------------------------------- // Parses a compile unit and indexes its DIEs if it hasn't already been done. // It will clear this compile unit after returned instance gets out of scope, // no other ScopedExtractDIEs instance is running for this compile unit // and no ExtractDIEsIfNeeded() has been executed during this ScopedExtractDIEs // lifetime. -//---------------------------------------------------------------------- DWARFUnit::ScopedExtractDIEs DWARFUnit::ExtractDIEsScoped() { - ScopedExtractDIEs scoped(this); + ScopedExtractDIEs scoped(*this); { llvm::sys::ScopedReader lock(m_die_array_mutex); @@ -118,8 +109,7 @@ return scoped; } -DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(DWARFUnit *cu) : m_cu(cu) { - lldbassert(m_cu); +DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(DWARFUnit &cu) : m_cu(&cu) { m_cu->m_die_array_scoped_mutex.lock_shared(); } @@ -150,33 +140,21 @@ return *this; } -//---------------------------------------------------------------------- // Parses a compile unit and indexes its DIEs, m_die_array_mutex must be // held R/W and m_die_array must be empty. -//---------------------------------------------------------------------- void DWARFUnit::ExtractDIEsRWLocked() { llvm::sys::ScopedWriter first_die_lock(m_first_die_mutex); static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); - Timer scoped_timer( - func_cat, "%8.8x: DWARFUnit::ExtractDIEsIfNeeded()", m_offset); + Timer scoped_timer(func_cat, "%8.8x: DWARFUnit::ExtractDIEsIfNeeded()", + GetOffset()); // Set the offset to that of the first DIE and calculate the start of the // next compilation unit header. lldb::offset_t offset = GetFirstDIEOffset(); - lldb::offset_t next_cu_offset = GetNextCompileUnitOffset(); + lldb::offset_t next_cu_offset = GetNextUnitOffset(); DWARFDebugInfoEntry die; - // Keep a flat array of the DIE for binary lookup by DIE offset - Log *log( - LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_LOOKUPS)); - if (log) { - m_dwarf->GetObjectFile()->GetModule()->LogMessageVerboseBacktrace( - log, - "DWARFUnit::ExtractDIEsIfNeeded () for compile unit at " - ".debug_info[0x%8.8x]", - GetOffset()); - } uint32_t depth = 0; // We are in our compile unit, parse starting at the offset we were told to @@ -186,11 +164,7 @@ die_index_stack.reserve(32); die_index_stack.push_back(0); bool prev_die_had_children = false; - DWARFFormValue::FixedFormSizes fixed_form_sizes = - DWARFFormValue::GetFixedFormSizesForAddressSize(GetAddressByteSize(), - IsDWARF64()); - while (offset < next_cu_offset && - die.FastExtract(data, this, fixed_form_sizes, &offset)) { + while (offset < next_cu_offset && die.Extract(data, this, &offset)) { const bool null_die = die.IsNULL(); if (depth == 0) { assert(m_die_array.empty() && "Compile unit DIE already added"); @@ -208,6 +182,17 @@ if (!m_first_die) AddUnitDIE(m_die_array.front()); + + // With -fsplit-dwarf-inlining, clang will emit non-empty skeleton compile + // units. We are not able to access these DIE *and* the dwo file + // simultaneously. We also don't need to do that as the dwo file will + // contain a superset of information. So, we don't even attempt to parse + // any remaining DIEs. + if (m_dwo_symbol_file) { + m_die_array.front().SetHasChildren(false); + break; + } + } else { if (null_die) { if (prev_die_had_children) { @@ -264,40 +249,12 @@ m_die_array.shrink_to_fit(); - ExtractDIEsEndCheck(offset); - if (m_dwo_symbol_file) { DWARFUnit *dwo_cu = m_dwo_symbol_file->GetCompileUnit(); dwo_cu->ExtractDIEsIfNeeded(); } } -//-------------------------------------------------------------------------- -// Final checks for both ExtractUnitDIEIfNeeded() and ExtractDIEsIfNeeded(). -//-------------------------------------------------------------------------- -void DWARFUnit::ExtractDIEsEndCheck(lldb::offset_t offset) const { - // Give a little bit of info if we encounter corrupt DWARF (our offset should - // always terminate at or before the start of the next compilation unit - // header). - if (offset > GetNextCompileUnitOffset()) { - m_dwarf->GetObjectFile()->GetModule()->ReportWarning( - "DWARF compile unit extends beyond its bounds cu 0x%8.8x at " - "0x%8.8" PRIx64 "\n", - GetOffset(), offset); - } - - Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO)); - if (log && log->GetVerbose()) { - StreamString strm; - Dump(&strm); - if (m_die_array.empty()) - strm.Printf("error: no DIE for compile unit"); - else - m_die_array[0].Dump(m_dwarf, this, strm, UINT32_MAX); - log->PutString(strm.GetString()); - } -} - // This is used when a split dwarf is enabled. // A skeleton compilation unit may contain the DW_AT_str_offsets_base attribute // that points to the first string offset of the CU contribution to the @@ -308,7 +265,7 @@ lldb::offset_t baseOffset = 0; const DWARFDataExtractor &strOffsets = - dwo_cu->GetSymbolFileDWARF()->get_debug_str_offsets_data(); + dwo_cu->GetSymbolFileDWARF().GetDWARFContext().getOrLoadStrOffsetsData(); uint64_t length = strOffsets.GetU32(&baseOffset); if (length == 0xffffffff) length = strOffsets.GetU64(&baseOffset); @@ -325,28 +282,50 @@ // m_die_array_mutex must be already held as read/write. void DWARFUnit::AddUnitDIE(const DWARFDebugInfoEntry &cu_die) { - dw_addr_t addr_base = cu_die.GetAttributeValueAsUnsigned( - m_dwarf, this, DW_AT_addr_base, LLDB_INVALID_ADDRESS); - if (addr_base != LLDB_INVALID_ADDRESS) - SetAddrBase(addr_base); + llvm::Optional<uint64_t> addr_base, gnu_addr_base, ranges_base, + gnu_ranges_base; - dw_addr_t ranges_base = cu_die.GetAttributeValueAsUnsigned( - m_dwarf, this, DW_AT_rnglists_base, LLDB_INVALID_ADDRESS); - if (ranges_base != LLDB_INVALID_ADDRESS) - SetRangesBase(ranges_base); - - SetStrOffsetsBase(cu_die.GetAttributeValueAsUnsigned( - m_dwarf, this, DW_AT_str_offsets_base, 0)); - - uint64_t base_addr = cu_die.GetAttributeValueAsAddress( - m_dwarf, this, DW_AT_low_pc, LLDB_INVALID_ADDRESS); - if (base_addr == LLDB_INVALID_ADDRESS) - base_addr = cu_die.GetAttributeValueAsAddress( - m_dwarf, this, DW_AT_entry_pc, 0); - SetBaseAddress(base_addr); + DWARFAttributes attributes; + size_t num_attributes = cu_die.GetAttributes(this, attributes); + for (size_t i = 0; i < num_attributes; ++i) { + dw_attr_t attr = attributes.AttributeAtIndex(i); + DWARFFormValue form_value; + if (!attributes.ExtractFormValueAtIndex(i, form_value)) + continue; + switch (attr) { + case DW_AT_addr_base: + addr_base = form_value.Unsigned(); + SetAddrBase(*addr_base); + break; + case DW_AT_rnglists_base: + ranges_base = form_value.Unsigned(); + SetRangesBase(*ranges_base); + break; + case DW_AT_str_offsets_base: + SetStrOffsetsBase(form_value.Unsigned()); + break; + case DW_AT_low_pc: + SetBaseAddress(form_value.Address()); + break; + case DW_AT_entry_pc: + // If the value was already set by DW_AT_low_pc, don't update it. + if (m_base_addr == LLDB_INVALID_ADDRESS) + SetBaseAddress(form_value.Address()); + break; + case DW_AT_stmt_list: + m_line_table_offset = form_value.Unsigned(); + break; + case DW_AT_GNU_addr_base: + gnu_addr_base = form_value.Unsigned(); + break; + case DW_AT_GNU_ranges_base: + gnu_ranges_base = form_value.Unsigned(); + break; + } + } std::unique_ptr<SymbolFileDWARFDwo> dwo_symbol_file = - m_dwarf->GetDwoSymbolFileForCompileUnit(*this, cu_die); + m_dwarf.GetDwoSymbolFileForCompileUnit(*this, cu_die); if (!dwo_symbol_file) return; @@ -359,7 +338,7 @@ return; // Can't fetch the compile unit DIE from the dwo file. uint64_t main_dwo_id = - cu_die.GetAttributeValueAsUnsigned(m_dwarf, this, DW_AT_GNU_dwo_id, 0); + cu_die.GetAttributeValueAsUnsigned(this, DW_AT_GNU_dwo_id, 0); uint64_t sub_dwo_id = dwo_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_dwo_id, 0); if (main_dwo_id != sub_dwo_id) @@ -374,19 +353,20 @@ // attributes which were applicable to the DWO units. The corresponding // DW_AT_* attributes standardized in DWARF v5 are also applicable to the main // unit in contrast. - if (addr_base == LLDB_INVALID_ADDRESS) - addr_base = cu_die.GetAttributeValueAsUnsigned(m_dwarf, this, - DW_AT_GNU_addr_base, 0); - dwo_cu->SetAddrBase(addr_base); + if (addr_base) + dwo_cu->SetAddrBase(*addr_base); + else if (gnu_addr_base) + dwo_cu->SetAddrBase(*gnu_addr_base); - if (ranges_base == LLDB_INVALID_ADDRESS) - ranges_base = cu_die.GetAttributeValueAsUnsigned(m_dwarf, this, - DW_AT_GNU_ranges_base, 0); - dwo_cu->SetRangesBase(ranges_base); + if (ranges_base) + dwo_cu->SetRangesBase(*ranges_base); + else if (gnu_ranges_base) + dwo_cu->SetRangesBase(*gnu_ranges_base); - dwo_cu->SetBaseObjOffset(m_offset); - - SetDwoStrOffsetsBase(dwo_cu); + for (size_t i = 0; i < m_dwo_symbol_file->DebugInfo()->GetNumUnits(); ++i) { + DWARFUnit *unit = m_dwo_symbol_file->DebugInfo()->GetUnitAtIndex(i); + SetDwoStrOffsetsBase(unit); + } } DWARFDIE DWARFUnit::LookupAddress(const dw_addr_t address) { @@ -401,35 +381,21 @@ } size_t DWARFUnit::AppendDIEsWithTag(const dw_tag_t tag, - DWARFDIECollection &dies, - uint32_t depth) const { - size_t old_size = dies.Size(); + std::vector<DWARFDIE> &dies, + uint32_t depth) const { + size_t old_size = dies.size(); { llvm::sys::ScopedReader lock(m_die_array_mutex); DWARFDebugInfoEntry::const_iterator pos; DWARFDebugInfoEntry::const_iterator end = m_die_array.end(); for (pos = m_die_array.begin(); pos != end; ++pos) { if (pos->Tag() == tag) - dies.Append(DWARFDIE(this, &(*pos))); + dies.emplace_back(this, &(*pos)); } } // Return the number of DIEs added to the collection - return dies.Size() - old_size; -} - - -lldb::user_id_t DWARFUnit::GetID() const { - dw_offset_t local_id = - m_base_obj_offset != DW_INVALID_OFFSET ? m_base_obj_offset : m_offset; - if (m_dwarf) - return DIERef(local_id, local_id).GetUID(m_dwarf); - else - return local_id; -} - -dw_offset_t DWARFUnit::GetNextCompileUnitOffset() const { - return m_offset + GetLengthByteSize() + GetLength(); + return dies.size() - old_size; } size_t DWARFUnit::GetDebugInfoSize() const { @@ -444,16 +410,17 @@ return m_abbrevs ? m_abbrevs->GetOffset() : DW_INVALID_OFFSET; } +dw_offset_t DWARFUnit::GetLineTableOffset() { + ExtractUnitDIEIfNeeded(); + return m_line_table_offset; +} + void DWARFUnit::SetAddrBase(dw_addr_t addr_base) { m_addr_base = addr_base; } void DWARFUnit::SetRangesBase(dw_addr_t ranges_base) { m_ranges_base = ranges_base; } -void DWARFUnit::SetBaseObjOffset(dw_offset_t base_obj_offset) { - m_base_obj_offset = base_obj_offset; -} - void DWARFUnit::SetStrOffsetsBase(dw_offset_t str_offsets_base) { m_str_offsets_base = str_offsets_base; } @@ -467,132 +434,27 @@ m_dwo_symbol_file->GetCompileUnit()->ClearDIEsRWLocked(); } -void DWARFUnit::BuildAddressRangeTable(SymbolFileDWARF *dwarf, - DWARFDebugAranges *debug_aranges) { - // This function is usually called if there in no .debug_aranges section in - // order to produce a compile unit level set of address ranges that is - // accurate. - - size_t num_debug_aranges = debug_aranges->GetNumRanges(); - - // First get the compile unit DIE only and check if it has a DW_AT_ranges - const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly(); - - const dw_offset_t cu_offset = GetOffset(); - if (die) { - DWARFRangeList ranges; - const size_t num_ranges = - die->GetAttributeAddressRanges(dwarf, this, ranges, false); - if (num_ranges > 0) { - // This compile unit has DW_AT_ranges, assume this is correct if it is - // present since clang no longer makes .debug_aranges by default and it - // emits DW_AT_ranges for DW_TAG_compile_units. GCC also does this with - // recent GCC builds. - for (size_t i = 0; i < num_ranges; ++i) { - const DWARFRangeList::Entry &range = ranges.GetEntryRef(i); - debug_aranges->AppendRange(cu_offset, range.GetRangeBase(), - range.GetRangeEnd()); - } - - return; // We got all of our ranges from the DW_AT_ranges attribute - } - } - // We don't have a DW_AT_ranges attribute, so we need to parse the DWARF - - // If the DIEs weren't parsed, then we don't want all dies for all compile - // units to stay loaded when they weren't needed. So we can end up parsing - // the DWARF and then throwing them all away to keep memory usage down. - ScopedExtractDIEs clear_dies(ExtractDIEsScoped()); - - die = DIEPtr(); - if (die) - die->BuildAddressRangeTable(dwarf, this, debug_aranges); - - if (debug_aranges->GetNumRanges() == num_debug_aranges) { - // We got nothing from the functions, maybe we have a line tables only - // situation. Check the line tables and build the arange table from this. - SymbolContext sc; - sc.comp_unit = dwarf->GetCompUnitForDWARFCompUnit(this); - if (sc.comp_unit) { - SymbolFileDWARFDebugMap *debug_map_sym_file = - m_dwarf->GetDebugMapSymfile(); - if (debug_map_sym_file == NULL) { - LineTable *line_table = sc.comp_unit->GetLineTable(); - - if (line_table) { - LineTable::FileAddressRanges file_ranges; - const bool append = true; - const size_t num_ranges = - line_table->GetContiguousFileAddressRanges(file_ranges, append); - for (uint32_t idx = 0; idx < num_ranges; ++idx) { - const LineTable::FileAddressRanges::Entry &range = - file_ranges.GetEntryRef(idx); - debug_aranges->AppendRange(cu_offset, range.GetRangeBase(), - range.GetRangeEnd()); - } - } - } else - debug_map_sym_file->AddOSOARanges(dwarf, debug_aranges); - } - } - - if (debug_aranges->GetNumRanges() == num_debug_aranges) { - // We got nothing from the functions, maybe we have a line tables only - // situation. Check the line tables and build the arange table from this. - SymbolContext sc; - sc.comp_unit = dwarf->GetCompUnitForDWARFCompUnit(this); - if (sc.comp_unit) { - LineTable *line_table = sc.comp_unit->GetLineTable(); - - if (line_table) { - LineTable::FileAddressRanges file_ranges; - const bool append = true; - const size_t num_ranges = - line_table->GetContiguousFileAddressRanges(file_ranges, append); - for (uint32_t idx = 0; idx < num_ranges; ++idx) { - const LineTable::FileAddressRanges::Entry &range = - file_ranges.GetEntryRef(idx); - debug_aranges->AppendRange(GetOffset(), range.GetRangeBase(), - range.GetRangeEnd()); - } - } - } - } -} - lldb::ByteOrder DWARFUnit::GetByteOrder() const { - return m_dwarf->GetObjectFile()->GetByteOrder(); + return m_dwarf.GetObjectFile()->GetByteOrder(); } TypeSystem *DWARFUnit::GetTypeSystem() { - if (m_dwarf) - return m_dwarf->GetTypeSystemForLanguage(GetLanguageType()); - else - return nullptr; -} - -DWARFFormValue::FixedFormSizes DWARFUnit::GetFixedFormSizes() { - return DWARFFormValue::GetFixedFormSizesForAddressSize(GetAddressByteSize(), - IsDWARF64()); + return m_dwarf.GetTypeSystemForLanguage(GetLanguageType()); } void DWARFUnit::SetBaseAddress(dw_addr_t base_addr) { m_base_addr = base_addr; } -//---------------------------------------------------------------------- // Compare function DWARFDebugAranges::Range structures -//---------------------------------------------------------------------- static bool CompareDIEOffset(const DWARFDebugInfoEntry &die, const dw_offset_t die_offset) { return die.GetOffset() < die_offset; } -//---------------------------------------------------------------------- // GetDIE() // // Get the DIE (Debug Information Entry) with the specified offset by first // checking if the DIE is contained within this compile unit and grabbing the // DIE from this compile unit. Otherwise we grab the DIE from the DWARF file. -//---------------------------------------------------------------------- DWARFDIE DWARFUnit::GetDIE(dw_offset_t die_offset) { if (die_offset != DW_INVALID_OFFSET) { @@ -608,28 +470,26 @@ if (die_offset == (*pos).GetOffset()) return DWARFDIE(this, &(*pos)); } - } else { - // Don't specify the compile unit offset as we don't know it because the - // DIE belongs to - // a different compile unit in the same symbol file. - return m_dwarf->DebugInfo()->GetDIEForDIEOffset(die_offset); - } + } else + GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError( + "GetDIE for DIE 0x%" PRIx32 " is outside of its CU 0x%" PRIx32, + die_offset, GetOffset()); } return DWARFDIE(); // Not found } +DWARFUnit &DWARFUnit::GetNonSkeletonUnit() { + if (SymbolFileDWARFDwo *dwo = GetDwoSymbolFile()) + return *dwo->GetCompileUnit(); + return *this; +} + uint8_t DWARFUnit::GetAddressByteSize(const DWARFUnit *cu) { if (cu) return cu->GetAddressByteSize(); return DWARFUnit::GetDefaultAddressSize(); } -bool DWARFUnit::IsDWARF64(const DWARFUnit *cu) { - if (cu) - return cu->IsDWARF64(); - return false; -} - uint8_t DWARFUnit::GetDefaultAddressSize() { return 4; } void *DWARFUnit::GetUserData() const { return m_user_data; } @@ -660,8 +520,6 @@ // info } -SymbolFileDWARF *DWARFUnit::GetSymbolFileDWARF() const { return m_dwarf; } - void DWARFUnit::ParseProducerInfo() { m_producer_version_major = UINT32_MAX; m_producer_version_minor = UINT32_MAX; @@ -671,7 +529,7 @@ if (die) { const char *producer_cstr = - die->GetAttributeValueAsString(m_dwarf, this, DW_AT_producer, NULL); + die->GetAttributeValueAsString(this, DW_AT_producer, nullptr); if (producer_cstr) { RegularExpression llvm_gcc_regex( llvm::StringRef("^4\\.[012]\\.[01] \\(Based on Apple " @@ -748,7 +606,7 @@ const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly(); if (die) m_language_type = LanguageTypeFromDWARF( - die->GetAttributeValueAsUnsigned(m_dwarf, this, DW_AT_language, 0)); + die->GetAttributeValueAsUnsigned(this, DW_AT_language, 0)); return m_language_type; } @@ -757,8 +615,8 @@ const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly(); if (die) { m_is_optimized = eLazyBoolNo; - if (die->GetAttributeValueAsUnsigned(m_dwarf, this, DW_AT_APPLE_optimized, - 0) == 1) { + if (die->GetAttributeValueAsUnsigned(this, DW_AT_APPLE_optimized, 0) == + 1) { m_is_optimized = eLazyBoolYes; } } @@ -766,40 +624,255 @@ return m_is_optimized == eLazyBoolYes; } +FileSpec::Style DWARFUnit::GetPathStyle() { + if (!m_comp_dir) + ComputeCompDirAndGuessPathStyle(); + return m_comp_dir->GetPathStyle(); +} + +const FileSpec &DWARFUnit::GetCompilationDirectory() { + if (!m_comp_dir) + ComputeCompDirAndGuessPathStyle(); + return *m_comp_dir; +} + +const FileSpec &DWARFUnit::GetAbsolutePath() { + if (!m_file_spec) + ComputeAbsolutePath(); + return *m_file_spec; +} + +FileSpec DWARFUnit::GetFile(size_t file_idx) { + return m_dwarf.GetFile(*this, file_idx); +} + +// DWARF2/3 suggests the form hostname:pathname for compilation directory. +// Remove the host part if present. +static llvm::StringRef +removeHostnameFromPathname(llvm::StringRef path_from_dwarf) { + llvm::StringRef host, path; + std::tie(host, path) = path_from_dwarf.split(':'); + + if (host.contains('/')) + return path_from_dwarf; + + // check whether we have a windows path, and so the first character is a + // drive-letter not a hostname. + if (host.size() == 1 && llvm::isAlpha(host[0]) && path.startswith("\\")) + return path_from_dwarf; + + return path; +} + +static FileSpec resolveCompDir(const FileSpec &path) { + bool is_symlink = SymbolFileDWARF::GetSymlinkPaths().FindFileIndex( + 0, path, /*full*/ true) != UINT32_MAX; + + if (!is_symlink) + return path; + + namespace fs = llvm::sys::fs; + if (fs::get_file_type(path.GetPath(), false) != fs::file_type::symlink_file) + return path; + + FileSpec resolved_symlink; + const auto error = FileSystem::Instance().Readlink(path, resolved_symlink); + if (error.Success()) + return resolved_symlink; + + return path; +} + +void DWARFUnit::ComputeCompDirAndGuessPathStyle() { + m_comp_dir = FileSpec(); + const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly(); + if (!die) + return; + + llvm::StringRef comp_dir = removeHostnameFromPathname( + die->GetAttributeValueAsString(this, DW_AT_comp_dir, nullptr)); + if (!comp_dir.empty()) { + FileSpec::Style comp_dir_style = + FileSpec::GuessPathStyle(comp_dir).getValueOr(FileSpec::Style::native); + m_comp_dir = resolveCompDir(FileSpec(comp_dir, comp_dir_style)); + } else { + // Try to detect the style based on the DW_AT_name attribute, but just store + // the detected style in the m_comp_dir field. + const char *name = + die->GetAttributeValueAsString(this, DW_AT_name, nullptr); + m_comp_dir = FileSpec( + "", FileSpec::GuessPathStyle(name).getValueOr(FileSpec::Style::native)); + } +} + +void DWARFUnit::ComputeAbsolutePath() { + m_file_spec = FileSpec(); + const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly(); + if (!die) + return; + + m_file_spec = + FileSpec(die->GetAttributeValueAsString(this, DW_AT_name, nullptr), + GetPathStyle()); + + if (m_file_spec->IsRelative()) + m_file_spec->MakeAbsolute(GetCompilationDirectory()); +} + SymbolFileDWARFDwo *DWARFUnit::GetDwoSymbolFile() const { return m_dwo_symbol_file.get(); } -dw_offset_t DWARFUnit::GetBaseObjOffset() const { return m_base_obj_offset; } - const DWARFDebugAranges &DWARFUnit::GetFunctionAranges() { - if (m_func_aranges_ap.get() == NULL) { - m_func_aranges_ap.reset(new DWARFDebugAranges()); - Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_ARANGES)); - - if (log) { - m_dwarf->GetObjectFile()->GetModule()->LogMessage( - log, - "DWARFUnit::GetFunctionAranges() for compile unit at " - ".debug_info[0x%8.8x]", - GetOffset()); - } + if (m_func_aranges_up == nullptr) { + m_func_aranges_up.reset(new DWARFDebugAranges()); const DWARFDebugInfoEntry *die = DIEPtr(); if (die) - die->BuildFunctionAddressRangeTable(m_dwarf, this, - m_func_aranges_ap.get()); + die->BuildFunctionAddressRangeTable(this, m_func_aranges_up.get()); if (m_dwo_symbol_file) { DWARFUnit *dwo_cu = m_dwo_symbol_file->GetCompileUnit(); const DWARFDebugInfoEntry *dwo_die = dwo_cu->DIEPtr(); if (dwo_die) - dwo_die->BuildFunctionAddressRangeTable(m_dwo_symbol_file.get(), dwo_cu, - m_func_aranges_ap.get()); + dwo_die->BuildFunctionAddressRangeTable(dwo_cu, + m_func_aranges_up.get()); } const bool minimize = false; - m_func_aranges_ap->Sort(minimize); + m_func_aranges_up->Sort(minimize); } - return *m_func_aranges_ap.get(); + return *m_func_aranges_up; } +llvm::Expected<DWARFUnitHeader> +DWARFUnitHeader::extract(const DWARFDataExtractor &data, DIERef::Section section, + lldb::offset_t *offset_ptr) { + DWARFUnitHeader header; + header.m_offset = *offset_ptr; + header.m_length = data.GetDWARFInitialLength(offset_ptr); + header.m_version = data.GetU16(offset_ptr); + if (header.m_version == 5) { + header.m_unit_type = data.GetU8(offset_ptr); + header.m_addr_size = data.GetU8(offset_ptr); + header.m_abbr_offset = data.GetDWARFOffset(offset_ptr); + if (header.m_unit_type == llvm::dwarf::DW_UT_skeleton) + header.m_dwo_id = data.GetU64(offset_ptr); + } else { + header.m_abbr_offset = data.GetDWARFOffset(offset_ptr); + header.m_addr_size = data.GetU8(offset_ptr); + header.m_unit_type = + section == DIERef::Section::DebugTypes ? DW_UT_type : DW_UT_compile; + } + + if (header.IsTypeUnit()) { + header.m_type_hash = data.GetU64(offset_ptr); + header.m_type_offset = data.GetDWARFOffset(offset_ptr); + } + + bool length_OK = data.ValidOffset(header.GetNextUnitOffset() - 1); + bool version_OK = SymbolFileDWARF::SupportedVersion(header.m_version); + bool addr_size_OK = (header.m_addr_size == 4) || (header.m_addr_size == 8); + bool type_offset_OK = + !header.IsTypeUnit() || (header.m_type_offset <= header.GetLength()); + + if (!length_OK) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Invalid unit length"); + if (!version_OK) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Unsupported unit version"); + if (!addr_size_OK) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Invalid unit address size"); + if (!type_offset_OK) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Type offset out of range"); + + return header; +} + +llvm::Expected<DWARFUnitSP> +DWARFUnit::extract(SymbolFileDWARF &dwarf, user_id_t uid, + const DWARFDataExtractor &debug_info, + DIERef::Section section, lldb::offset_t *offset_ptr) { + assert(debug_info.ValidOffset(*offset_ptr)); + + auto expected_header = + DWARFUnitHeader::extract(debug_info, section, offset_ptr); + if (!expected_header) + return expected_header.takeError(); + + const DWARFDebugAbbrev *abbr = dwarf.DebugAbbrev(); + if (!abbr) + return llvm::make_error<llvm::object::GenericBinaryError>( + "No debug_abbrev data"); + + bool abbr_offset_OK = + dwarf.GetDWARFContext().getOrLoadAbbrevData().ValidOffset( + expected_header->GetAbbrOffset()); + if (!abbr_offset_OK) + return llvm::make_error<llvm::object::GenericBinaryError>( + "Abbreviation offset for unit is not valid"); + + const DWARFAbbreviationDeclarationSet *abbrevs = + abbr->GetAbbreviationDeclarationSet(expected_header->GetAbbrOffset()); + if (!abbrevs) + return llvm::make_error<llvm::object::GenericBinaryError>( + "No abbrev exists at the specified offset."); + + if (expected_header->IsTypeUnit()) + return DWARFUnitSP( + new DWARFTypeUnit(dwarf, uid, *expected_header, *abbrevs, section)); + return DWARFUnitSP( + new DWARFCompileUnit(dwarf, uid, *expected_header, *abbrevs, section)); +} + +const lldb_private::DWARFDataExtractor &DWARFUnit::GetData() const { + return m_section == DIERef::Section::DebugTypes + ? m_dwarf.GetDWARFContext().getOrLoadDebugTypesData() + : m_dwarf.GetDWARFContext().getOrLoadDebugInfoData(); +} + +uint32_t DWARFUnit::GetHeaderByteSize() const { + switch (m_header.GetUnitType()) { + case llvm::dwarf::DW_UT_compile: + case llvm::dwarf::DW_UT_partial: + return GetVersion() < 5 ? 11 : 12; + case llvm::dwarf::DW_UT_skeleton: + case llvm::dwarf::DW_UT_split_compile: + return 20; + case llvm::dwarf::DW_UT_type: + case llvm::dwarf::DW_UT_split_type: + return GetVersion() < 5 ? 23 : 24; + } + llvm_unreachable("invalid UnitType."); +} + +llvm::Expected<DWARFRangeList> +DWARFUnit::FindRnglistFromOffset(dw_offset_t offset) const { + const DWARFDebugRangesBase *debug_ranges; + llvm::StringRef section; + if (GetVersion() <= 4) { + debug_ranges = m_dwarf.GetDebugRanges(); + section = "debug_ranges"; + } else { + debug_ranges = m_dwarf.GetDebugRngLists(); + section = "debug_rnglists"; + } + if (!debug_ranges) + return llvm::make_error<llvm::object::GenericBinaryError>("No " + section + + " section"); + + DWARFRangeList ranges; + debug_ranges->FindRanges(this, offset, ranges); + return ranges; +} + +llvm::Expected<DWARFRangeList> +DWARFUnit::FindRnglistFromIndex(uint32_t index) const { + const DWARFDebugRangesBase *debug_rnglists = m_dwarf.GetDebugRngLists(); + if (!debug_rnglists) + return llvm::make_error<llvm::object::GenericBinaryError>( + "No debug_rnglists section"); + return FindRnglistFromOffset(debug_rnglists->GetOffset(index)); +}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.h index 178c894..8aa1e44 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.h
@@ -1,9 +1,8 @@ //===-- DWARFUnit.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,11 +31,52 @@ eProcucerOther }; -class DWARFUnit { +/// Base class describing the header of any kind of "unit." Some information +/// is specific to certain unit types. We separate this class out so we can +/// parse the header before deciding what specific kind of unit to construct. +class DWARFUnitHeader { + dw_offset_t m_offset = 0; + dw_offset_t m_length = 0; + uint16_t m_version = 0; + dw_offset_t m_abbr_offset = 0; + uint8_t m_unit_type = 0; + uint8_t m_addr_size = 0; + + uint64_t m_type_hash = 0; + uint32_t m_type_offset = 0; + + uint64_t m_dwo_id = 0; + + DWARFUnitHeader() = default; + +public: + dw_offset_t GetOffset() const { return m_offset; } + uint16_t GetVersion() const { return m_version; } + uint16_t GetAddressByteSize() const { return m_addr_size; } + dw_offset_t GetLength() const { return m_length; } + dw_offset_t GetAbbrOffset() const { return m_abbr_offset; } + uint8_t GetUnitType() const { return m_unit_type; } + uint64_t GetTypeHash() const { return m_type_hash; } + dw_offset_t GetTypeOffset() const { return m_type_offset; } + bool IsTypeUnit() const { + return m_unit_type == DW_UT_type || m_unit_type == DW_UT_split_type; + } + uint32_t GetNextUnitOffset() const { return m_offset + m_length + 4; } + + static llvm::Expected<DWARFUnitHeader> + extract(const lldb_private::DWARFDataExtractor &data, DIERef::Section section, + lldb::offset_t *offset_ptr); +}; + +class DWARFUnit : public lldb_private::UserID { using die_iterator_range = llvm::iterator_range<DWARFDebugInfoEntry::collection::iterator>; public: + static llvm::Expected<DWARFUnitSP> + extract(SymbolFileDWARF &dwarf2Data, lldb::user_id_t uid, + const lldb_private::DWARFDataExtractor &debug_info, + DIERef::Section section, lldb::offset_t *offset_ptr); virtual ~DWARFUnit(); void ExtractUnitDIEIfNeeded(); @@ -46,7 +86,7 @@ DWARFUnit *m_cu; public: bool m_clear_dies = false; - ScopedExtractDIEs(DWARFUnit *cu); + ScopedExtractDIEs(DWARFUnit &cu); ~ScopedExtractDIEs(); DISALLOW_COPY_AND_ASSIGN(ScopedExtractDIEs); ScopedExtractDIEs(ScopedExtractDIEs &&rhs); @@ -55,69 +95,61 @@ ScopedExtractDIEs ExtractDIEsScoped(); DWARFDIE LookupAddress(const dw_addr_t address); - size_t AppendDIEsWithTag(const dw_tag_t tag, - DWARFDIECollection &matching_dies, + size_t AppendDIEsWithTag(const dw_tag_t tag, std::vector<DWARFDIE> &dies, uint32_t depth = UINT32_MAX) const; bool Verify(lldb_private::Stream *s) const; virtual void Dump(lldb_private::Stream *s) const = 0; - //------------------------------------------------------------------ /// Get the data that contains the DIE information for this unit. /// /// This will return the correct bytes that contain the data for /// this DWARFUnit. It could be .debug_info or .debug_types /// depending on where the data for this unit originates. /// - /// @return + /// \return /// The correct data for the DIE information in this unit. - //------------------------------------------------------------------ - virtual const lldb_private::DWARFDataExtractor &GetData() const = 0; - //------------------------------------------------------------------ - /// Get the size in bytes of the compile unit header. + const lldb_private::DWARFDataExtractor &GetData() const; + + /// Get the size in bytes of the unit header. /// - /// @return - /// Byte size of the compile unit header - //------------------------------------------------------------------ - virtual uint32_t GetHeaderByteSize() const = 0; + /// \return + /// Byte size of the unit header + uint32_t GetHeaderByteSize() const; + // Offset of the initial length field. - dw_offset_t GetOffset() const { return m_offset; } - lldb::user_id_t GetID() const; - //------------------------------------------------------------------ + dw_offset_t GetOffset() const { return m_header.GetOffset(); } /// Get the size in bytes of the length field in the header. /// - /// In DWARF32 this is just 4 bytes, and DWARF64 it is 12 where 4 - /// are 0xFFFFFFFF followed by the actual 64 bit length. + /// In DWARF32 this is just 4 bytes /// - /// @return + /// \return /// Byte size of the compile unit header length field - //------------------------------------------------------------------ - size_t GetLengthByteSize() const { return IsDWARF64() ? 12 : 4; } - + size_t GetLengthByteSize() const { return 4; } + bool ContainsDIEOffset(dw_offset_t die_offset) const { return die_offset >= GetFirstDIEOffset() && - die_offset < GetNextCompileUnitOffset(); + die_offset < GetNextUnitOffset(); } dw_offset_t GetFirstDIEOffset() const { - return m_offset + GetHeaderByteSize(); + return GetOffset() + GetHeaderByteSize(); } - dw_offset_t GetNextCompileUnitOffset() const; + dw_offset_t GetNextUnitOffset() const { return m_header.GetNextUnitOffset(); } // Size of the CU data (without initial length and without header). size_t GetDebugInfoSize() const; // Size of the CU data incl. header but without initial length. - uint32_t GetLength() const { return m_length; } - uint16_t GetVersion() const { return m_version; } + uint32_t GetLength() const { return m_header.GetLength(); } + uint16_t GetVersion() const { return m_header.GetVersion(); } const DWARFAbbreviationDeclarationSet *GetAbbreviations() const; dw_offset_t GetAbbrevOffset() const; - uint8_t GetAddressByteSize() const { return m_addr_size; } - dw_addr_t GetBaseAddress() const { return m_base_addr; } + uint8_t GetAddressByteSize() const { return m_header.GetAddressByteSize(); } dw_addr_t GetAddrBase() const { return m_addr_base; } + dw_addr_t GetBaseAddress() const { return m_base_addr; } + dw_offset_t GetLineTableOffset(); dw_addr_t GetRangesBase() const { return m_ranges_base; } dw_addr_t GetStrOffsetsBase() const { return m_str_offsets_base; } void SetAddrBase(dw_addr_t addr_base); void SetRangesBase(dw_addr_t ranges_base); - void SetBaseObjOffset(dw_offset_t base_obj_offset); void SetStrOffsetsBase(dw_offset_t str_offsets_base); - void BuildAddressRangeTable(SymbolFileDWARF *dwarf, - DWARFDebugAranges *debug_aranges); + virtual void BuildAddressRangeTable(DWARFDebugAranges *debug_aranges) = 0; lldb::ByteOrder GetByteOrder() const; @@ -125,8 +157,6 @@ const DWARFDebugAranges &GetFunctionAranges(); - DWARFFormValue::FixedFormSizes GetFixedFormSizes(); - void SetBaseAddress(dw_addr_t base_addr); DWARFBaseDIE GetUnitDIEOnly() { return DWARFDIE(this, GetUnitDIEPtrOnly()); } @@ -135,9 +165,9 @@ DWARFDIE GetDIE(dw_offset_t die_offset); - static uint8_t GetAddressByteSize(const DWARFUnit *cu); + DWARFUnit &GetNonSkeletonUnit(); - static bool IsDWARF64(const DWARFUnit *cu); + static uint8_t GetAddressByteSize(const DWARFUnit *cu); static uint8_t GetDefaultAddressSize(); @@ -151,7 +181,7 @@ bool Supports_unnamed_objc_bitfields(); - SymbolFileDWARF *GetSymbolFileDWARF() const; + SymbolFileDWARF &GetSymbolFileDWARF() const { return m_dwarf; } DWARFProducer GetProducer(); @@ -165,70 +195,45 @@ lldb::LanguageType GetLanguageType(); - bool IsDWARF64() const { return m_is_dwarf64; } - bool GetIsOptimized(); - SymbolFileDWARFDwo *GetDwoSymbolFile() const; + const lldb_private::FileSpec &GetCompilationDirectory(); + const lldb_private::FileSpec &GetAbsolutePath(); + lldb_private::FileSpec GetFile(size_t file_idx); + lldb_private::FileSpec::Style GetPathStyle(); - dw_offset_t GetBaseObjOffset() const; + SymbolFileDWARFDwo *GetDwoSymbolFile() const; die_iterator_range dies() { ExtractDIEsIfNeeded(); return die_iterator_range(m_die_array.begin(), m_die_array.end()); } + DIERef::Section GetDebugSection() const { return m_section; } + + uint8_t GetUnitType() const { return m_header.GetUnitType(); } + bool IsTypeUnit() const { return m_header.IsTypeUnit(); } + + /// Return a list of address ranges resulting from a (possibly encoded) + /// range list starting at a given offset in the appropriate ranges section. + llvm::Expected<DWARFRangeList> FindRnglistFromOffset(dw_offset_t offset) const; + + /// Return a list of address ranges retrieved from an encoded range + /// list whose offset is found via a table lookup given an index (DWARF v5 + /// and later). + llvm::Expected<DWARFRangeList> FindRnglistFromIndex(uint32_t index) const; + protected: - DWARFUnit(SymbolFileDWARF *dwarf); + DWARFUnit(SymbolFileDWARF &dwarf, lldb::user_id_t uid, + const DWARFUnitHeader &header, + const DWARFAbbreviationDeclarationSet &abbrevs, + DIERef::Section section); - SymbolFileDWARF *m_dwarf = nullptr; - std::unique_ptr<SymbolFileDWARFDwo> m_dwo_symbol_file; - const DWARFAbbreviationDeclarationSet *m_abbrevs = nullptr; - void *m_user_data = nullptr; - // The compile unit debug information entry item - DWARFDebugInfoEntry::collection m_die_array; - mutable llvm::sys::RWMutex m_die_array_mutex; - // It is used for tracking of ScopedExtractDIEs instances. - mutable llvm::sys::RWMutex m_die_array_scoped_mutex; - // ScopedExtractDIEs instances should not call ClearDIEsRWLocked() - // as someone called ExtractDIEsIfNeeded(). - std::atomic<bool> m_cancel_scopes; - // GetUnitDIEPtrOnly() needs to return pointer to the first DIE. - // But the first element of m_die_array after ExtractUnitDIEIfNeeded() - // would possibly move in memory after later ExtractDIEsIfNeeded(). - DWARFDebugInfoEntry m_first_die; - llvm::sys::RWMutex m_first_die_mutex; - // A table similar to the .debug_aranges table, but this one points to the - // exact DW_TAG_subprogram DIEs - std::unique_ptr<DWARFDebugAranges> m_func_aranges_ap; - dw_addr_t m_base_addr = 0; - dw_offset_t m_length = 0; - uint16_t m_version = 0; - uint8_t m_addr_size = 0; - uint8_t m_unit_type = 0; - uint64_t m_dwo_id = 0; - DWARFProducer m_producer = eProducerInvalid; - uint32_t m_producer_version_major = 0; - uint32_t m_producer_version_minor = 0; - uint32_t m_producer_version_update = 0; - lldb::LanguageType m_language_type = lldb::eLanguageTypeUnknown; - bool m_is_dwarf64 = false; - lldb_private::LazyBool m_is_optimized = lldb_private::eLazyBoolCalculate; - dw_addr_t m_addr_base = 0; // Value of DW_AT_addr_base - dw_addr_t m_ranges_base = 0; // Value of DW_AT_ranges_base - // If this is a dwo compile unit this is the offset of the base compile unit - // in the main object file - dw_offset_t m_base_obj_offset = DW_INVALID_OFFSET; - dw_offset_t m_str_offsets_base = 0; // Value of DW_AT_str_offsets_base. - // Offset of the initial length field. - dw_offset_t m_offset; + llvm::Error ExtractHeader(SymbolFileDWARF &dwarf, + const lldb_private::DWARFDataExtractor &data, + lldb::offset_t *offset_ptr); -private: - void ParseProducerInfo(); - void ExtractDIEsRWLocked(); - void ClearDIEsRWLocked(); - - // Get the DWARF unit DWARF debug informration entry. Parse the single DIE + // Get the DWARF unit DWARF debug information entry. Parse the single DIE // if needed. const DWARFDebugInfoEntry *GetUnitDIEPtrOnly() { ExtractUnitDIEIfNeeded(); @@ -246,8 +251,54 @@ return &m_die_array[0]; } + SymbolFileDWARF &m_dwarf; + std::unique_ptr<SymbolFileDWARFDwo> m_dwo_symbol_file; + DWARFUnitHeader m_header; + const DWARFAbbreviationDeclarationSet *m_abbrevs = nullptr; + void *m_user_data = nullptr; + // The compile unit debug information entry item + DWARFDebugInfoEntry::collection m_die_array; + mutable llvm::sys::RWMutex m_die_array_mutex; + // It is used for tracking of ScopedExtractDIEs instances. + mutable llvm::sys::RWMutex m_die_array_scoped_mutex; + // ScopedExtractDIEs instances should not call ClearDIEsRWLocked() + // as someone called ExtractDIEsIfNeeded(). + std::atomic<bool> m_cancel_scopes; + // GetUnitDIEPtrOnly() needs to return pointer to the first DIE. + // But the first element of m_die_array after ExtractUnitDIEIfNeeded() + // would possibly move in memory after later ExtractDIEsIfNeeded(). + DWARFDebugInfoEntry m_first_die; + llvm::sys::RWMutex m_first_die_mutex; + // A table similar to the .debug_aranges table, but this one points to the + // exact DW_TAG_subprogram DIEs + std::unique_ptr<DWARFDebugAranges> m_func_aranges_up; + dw_addr_t m_base_addr = 0; + DWARFProducer m_producer = eProducerInvalid; + uint32_t m_producer_version_major = 0; + uint32_t m_producer_version_minor = 0; + uint32_t m_producer_version_update = 0; + lldb::LanguageType m_language_type = lldb::eLanguageTypeUnknown; + lldb_private::LazyBool m_is_optimized = lldb_private::eLazyBoolCalculate; + llvm::Optional<lldb_private::FileSpec> m_comp_dir; + llvm::Optional<lldb_private::FileSpec> m_file_spec; + dw_addr_t m_addr_base = 0; // Value of DW_AT_addr_base + dw_addr_t m_ranges_base = 0; // Value of DW_AT_ranges_base + + /// Value of DW_AT_stmt_list. + dw_offset_t m_line_table_offset = DW_INVALID_OFFSET; + + dw_offset_t m_str_offsets_base = 0; // Value of DW_AT_str_offsets_base. + const DIERef::Section m_section; + +private: + void ParseProducerInfo(); + void ExtractDIEsRWLocked(); + void ClearDIEsRWLocked(); + void AddUnitDIE(const DWARFDebugInfoEntry &cu_die); - void ExtractDIEsEndCheck(lldb::offset_t offset) const; + + void ComputeCompDirAndGuessPathStyle(); + void ComputeAbsolutePath(); DISALLOW_COPY_AND_ASSIGN(DWARFUnit); };
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.cpp index c043272..9746ad7 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.cpp
@@ -1,9 +1,8 @@ //===-- DebugNamesDWARFIndex.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,13 +16,6 @@ using namespace lldb_private; using namespace lldb; -static llvm::DWARFDataExtractor ToLLVM(const DWARFDataExtractor &data) { - return llvm::DWARFDataExtractor( - llvm::StringRef(reinterpret_cast<const char *>(data.GetDataStart()), - data.GetByteSize()), - data.GetByteOrder() == eByteOrderLittle, data.GetAddressByteSize()); -} - llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> DebugNamesDWARFIndex::Create(Module &module, DWARFDataExtractor debug_names, DWARFDataExtractor debug_str, @@ -32,8 +24,8 @@ return llvm::make_error<llvm::StringError>("debug info null", llvm::inconvertibleErrorCode()); } - auto index_up = - llvm::make_unique<DebugNames>(ToLLVM(debug_names), ToLLVM(debug_str)); + auto index_up = llvm::make_unique<DebugNames>(debug_names.GetAsLLVM(), + debug_str.GetAsLLVM()); if (llvm::Error E = index_up->extract()) return std::move(E); @@ -51,31 +43,33 @@ return result; } -DIERef DebugNamesDWARFIndex::ToDIERef(const DebugNames::Entry &entry) { +llvm::Optional<DIERef> +DebugNamesDWARFIndex::ToDIERef(const DebugNames::Entry &entry) { llvm::Optional<uint64_t> cu_offset = entry.getCUOffset(); if (!cu_offset) - return DIERef(); + return llvm::None; - DWARFUnit *cu = m_debug_info.GetCompileUnit(*cu_offset); + DWARFUnit *cu = m_debug_info.GetUnitAtOffset(DIERef::Section::DebugInfo, *cu_offset); if (!cu) - return DIERef(); + return llvm::None; // This initializes the DWO symbol file. It's not possible for // GetDwoSymbolFile to call this automatically because of mutual recursion // between this and DWARFDebugInfoEntry::GetAttributeValue. cu->ExtractUnitDIEIfNeeded(); - uint64_t die_bias = cu->GetDwoSymbolFile() ? 0 : *cu_offset; + cu = &cu->GetNonSkeletonUnit(); if (llvm::Optional<uint64_t> die_offset = entry.getDIEUnitOffset()) - return DIERef(*cu_offset, die_bias + *die_offset); + return DIERef(cu->GetSymbolFileDWARF().GetDwoNum(), + DIERef::Section::DebugInfo, cu->GetOffset() + *die_offset); - return DIERef(); + return llvm::None; } void DebugNamesDWARFIndex::Append(const DebugNames::Entry &entry, DIEArray &offsets) { - if (DIERef ref = ToDIERef(entry)) - offsets.push_back(ref); + if (llvm::Optional<DIERef> ref = ToDIERef(entry)) + offsets.push_back(*ref); } void DebugNamesDWARFIndex::MaybeLogLookupError(llvm::Error error, @@ -161,27 +155,27 @@ entry.tag() != DW_TAG_class_type) continue; - DIERef ref = ToDIERef(entry); + llvm::Optional<DIERef> ref = ToDIERef(entry); if (!ref) continue; - DWARFUnit *cu = m_debug_info.GetCompileUnit(ref.cu_offset); + DWARFUnit *cu = m_debug_info.GetUnit(*ref); if (!cu || !cu->Supports_DW_AT_APPLE_objc_complete_type()) { - incomplete_types.push_back(ref); + incomplete_types.push_back(*ref); continue; } // FIXME: We should return DWARFDIEs so we don't have to resolve it twice. - DWARFDIE die = m_debug_info.GetDIE(ref); + DWARFDIE die = m_debug_info.GetDIE(*ref); if (!die) continue; if (die.GetAttributeValueAsUnsigned(DW_AT_APPLE_objc_complete_type, 0)) { // If we find the complete version we're done. - offsets.push_back(ref); + offsets.push_back(*ref); return; } else { - incomplete_types.push_back(ref); + incomplete_types.push_back(*ref); } } @@ -221,12 +215,12 @@ } void DebugNamesDWARFIndex::GetFunctions( - ConstString name, DWARFDebugInfo &info, + ConstString name, SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) { std::vector<DWARFDIE> v; - m_fallback.GetFunctions(name, info, parent_decl_ctx, name_type_mask, v); + m_fallback.GetFunctions(name, dwarf, parent_decl_ctx, name_type_mask, v); for (const DebugNames::Entry &entry : m_debug_names_up->equal_range(name.GetStringRef())) { @@ -234,8 +228,8 @@ if (tag != DW_TAG_subprogram && tag != DW_TAG_inlined_subroutine) continue; - if (DIERef ref = ToDIERef(entry)) - ProcessFunctionDIE(name.GetStringRef(), ref, info, parent_decl_ctx, + if (llvm::Optional<DIERef> ref = ToDIERef(entry)) + ProcessFunctionDIE(name.GetStringRef(), *ref, dwarf, parent_decl_ctx, name_type_mask, v); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.h index 30423c7..dca2549 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/DebugNamesDWARFIndex.h
@@ -1,9 +1,8 @@ //===-- DebugNamesDWARFIndex.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,15 +34,14 @@ void GetTypes(ConstString name, DIEArray &offsets) override; void GetTypes(const DWARFDeclContext &context, DIEArray &offsets) override; void GetNamespaces(ConstString name, DIEArray &offsets) override; - void GetFunctions(ConstString name, DWARFDebugInfo &info, + void GetFunctions(ConstString name, SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) override; void GetFunctions(const RegularExpression ®ex, DIEArray &offsets) override; - void ReportInvalidDIEOffset(dw_offset_t offset, - llvm::StringRef name) override {} + void ReportInvalidDIERef(const DIERef &ref, llvm::StringRef name) override {} void Dump(Stream &s) override; private: @@ -68,7 +66,7 @@ std::unique_ptr<DebugNames> m_debug_names_up; ManualDWARFIndex m_fallback; - DIERef ToDIERef(const DebugNames::Entry &entry); + llvm::Optional<DIERef> ToDIERef(const DebugNames::Entry &entry); void Append(const DebugNames::Entry &entry, DIEArray &offsets); static void MaybeLogLookupError(llvm::Error error,
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp index f83ba66..62b0ad3 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp
@@ -1,9 +1,8 @@ //===-- HashedNameToDIE.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,8 +13,7 @@ DIEArray &die_offsets) { const size_t count = die_info_array.size(); for (size_t i = 0; i < count; ++i) - die_offsets.emplace_back(die_info_array[i].cu_offset, - die_info_array[i].offset); + die_offsets.emplace_back(die_info_array[i]); } void DWARFMappedHash::ExtractDIEArray(const DIEInfoArray &die_info_array, @@ -34,8 +32,7 @@ tag == DW_TAG_structure_type || tag == DW_TAG_class_type; } if (tag_matches) - die_offsets.emplace_back(die_info_array[i].cu_offset, - die_info_array[i].offset); + die_offsets.emplace_back(die_info_array[i]); } } } @@ -59,8 +56,7 @@ tag == DW_TAG_structure_type || tag == DW_TAG_class_type; } if (tag_matches) - die_offsets.emplace_back(die_info_array[i].cu_offset, - die_info_array[i].offset); + die_offsets.emplace_back(die_info_array[i]); } } } @@ -78,17 +74,14 @@ // We found the one true definition for this class, so only return // that die_offsets.clear(); - die_offsets.emplace_back(die_info_array[i].cu_offset, - die_info_array[i].offset); + die_offsets.emplace_back(die_info_array[i]); return; } else { // Put the one true definition as the first entry so it matches first - die_offsets.emplace(die_offsets.begin(), die_info_array[i].cu_offset, - die_info_array[i].offset); + die_offsets.emplace(die_offsets.begin(), die_info_array[i]); } } else { - die_offsets.emplace_back(die_info_array[i].cu_offset, - die_info_array[i].offset); + die_offsets.emplace_back(die_info_array[i]); } } } @@ -100,8 +93,7 @@ const size_t count = die_info_array.size(); for (size_t i = 0; i < count; ++i) { if ((die_info_array[i].type_flags & type_flag_mask) == type_flag_value) - die_offsets.emplace_back(die_info_array[i].cu_offset, - die_info_array[i].offset); + die_offsets.emplace_back(die_info_array[i]); } } @@ -125,13 +117,9 @@ return "<invalid>"; } -DWARFMappedHash::DIEInfo::DIEInfo() - : cu_offset(DW_INVALID_OFFSET), offset(DW_INVALID_OFFSET), tag(0), - type_flags(0), qualified_name_hash(0) {} - -DWARFMappedHash::DIEInfo::DIEInfo(dw_offset_t c, dw_offset_t o, dw_tag_t t, - uint32_t f, uint32_t h) - : cu_offset(c), offset(o), tag(t), type_flags(f), qualified_name_hash(h) {} +DWARFMappedHash::DIEInfo::DIEInfo(dw_offset_t o, dw_tag_t t, uint32_t f, + uint32_t h) + : die_offset(o), tag(t), type_flags(f), qualified_name_hash(h) {} DWARFMappedHash::Prologue::Prologue(dw_offset_t _die_base_offset) : die_base_offset(_die_base_offset), atoms(), atom_mask(0), @@ -167,6 +155,7 @@ case DW_FORM_ref_sig8: llvm_unreachable("Unhandled atom form"); + case DW_FORM_addrx: case DW_FORM_string: case DW_FORM_block: case DW_FORM_block1: @@ -271,14 +260,14 @@ return false; for (size_t i = 0; i < num_atoms; ++i) { - DWARFFormValue form_value(NULL, header_data.atoms[i].form); + DWARFFormValue form_value(nullptr, header_data.atoms[i].form); if (!form_value.ExtractValue(data, offset_ptr)) return false; switch (header_data.atoms[i].type) { case eAtomTypeDIEOffset: // DIE offset, check form for encoding - hash_data.offset = + hash_data.die_offset = DWARFFormValue::IsDataForm(form_value.Form()) ? form_value.Unsigned() : form_value.Reference(header_data.die_base_offset); @@ -301,50 +290,7 @@ break; } } - return true; -} - -void DWARFMappedHash::Header::Dump(lldb_private::Stream &strm, - const DIEInfo &hash_data) const { - const size_t num_atoms = header_data.atoms.size(); - for (size_t i = 0; i < num_atoms; ++i) { - if (i > 0) - strm.PutCString(", "); - - DWARFFormValue form_value(NULL, header_data.atoms[i].form); - switch (header_data.atoms[i].type) { - case eAtomTypeDIEOffset: // DIE offset, check form for encoding - strm.Printf("{0x%8.8x}", hash_data.offset); - break; - - case eAtomTypeTag: // DW_TAG value for the DIE - { - const char *tag_cstr = lldb_private::DW_TAG_value_to_name(hash_data.tag); - if (tag_cstr) - strm.PutCString(tag_cstr); - else - strm.Printf("DW_TAG_(0x%4.4x)", hash_data.tag); - } break; - - case eAtomTypeTypeFlags: // Flags from enum TypeFlags - strm.Printf("0x%2.2x", hash_data.type_flags); - if (hash_data.type_flags) { - strm.PutCString(" ("); - if (hash_data.type_flags & eTypeFlagClassIsImplementation) - strm.PutCString(" implementation"); - strm.PutCString(" )"); - } - break; - - case eAtomTypeQualNameHash: // Flags from enum TypeFlags - strm.Printf("0x%8.8x", hash_data.qualified_name_hash); - break; - - default: - strm.Printf("AtomType(0x%x)", header_data.atoms[i].type); - break; - } - } + return hash_data.die_offset != DW_INVALID_OFFSET; } DWARFMappedHash::MemoryTable::MemoryTable( @@ -391,7 +337,7 @@ // There definitely should be a string for this string offset, if there // isn't, there is something wrong, return and error const char *strp_cstr = m_string_table.PeekCStr(pair.key); - if (strp_cstr == NULL) { + if (strp_cstr == nullptr) { *hash_data_offset_ptr = UINT32_MAX; return eResultError; } @@ -458,7 +404,7 @@ // There definitely should be a string for this string offset, if there // isn't, there is something wrong, return and error const char *strp_cstr = m_string_table.PeekCStr(pair.key); - if (strp_cstr == NULL) + if (strp_cstr == nullptr) return eResultError; const uint32_t count = m_data.GetU32(hash_data_offset_ptr); @@ -556,10 +502,10 @@ for (uint32_t i = 0; i < count; ++i) { DIEInfo die_info; if (m_header.Read(m_data, &hash_data_offset, die_info)) { - if (die_info.offset == 0) + if (die_info.die_offset == 0) done = true; - if (die_offset_start <= die_info.offset && - die_info.offset < die_offset_end) + if (die_offset_start <= die_info.die_offset && + die_info.die_offset < die_offset_end) die_info_array.push_back(die_info); } }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.h index 17600df..a01612b 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.h
@@ -1,9 +1,8 @@ //===-- HashedNameToDIE.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -49,14 +48,21 @@ }; struct DIEInfo { - dw_offset_t cu_offset; - dw_offset_t offset; // The DIE offset - dw_tag_t tag; - uint32_t type_flags; // Any flags for this DIEInfo - uint32_t qualified_name_hash; // A 32 bit hash of the fully qualified name + dw_offset_t die_offset = DW_INVALID_OFFSET; + dw_tag_t tag = 0; - DIEInfo(); - DIEInfo(dw_offset_t c, dw_offset_t o, dw_tag_t t, uint32_t f, uint32_t h); + /// Any flags for this DIEInfo + uint32_t type_flags = 0; + + /// A 32 bit hash of the fully qualified name + uint32_t qualified_name_hash = 0; + + DIEInfo() = default; + DIEInfo(dw_offset_t o, dw_tag_t t, uint32_t f, uint32_t h); + + explicit operator DIERef() const { + return DIERef(llvm::None, DIERef::Section::DebugInfo, die_offset); + } }; struct Atom { @@ -105,8 +111,6 @@ bool Read(const lldb_private::DWARFDataExtractor &data, lldb::offset_t *offset_ptr, DIEInfo &hash_data) const; - - void Dump(lldb_private::Stream &strm, const DIEInfo &hash_data) const; }; // A class for reading and using a saved hash table from a block of data
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.cpp index 0b06713..8495016 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.cpp
@@ -1,9 +1,8 @@ //===-- LogChannelDWARF.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,9 +11,6 @@ using namespace lldb_private; static constexpr Log::Category g_categories[] = { - {{"aranges"}, - {"log the parsing of .debug_aranges"}, - DWARF_LOG_DEBUG_ARANGES}, {{"comp"}, {"log insertions of object files into DWARF debug maps"}, DWARF_LOG_TYPE_COMPLETION}, @@ -26,12 +22,6 @@ {{"map"}, {"log struct/unions/class type completions"}, DWARF_LOG_DEBUG_MAP}, - {{"pubnames"}, - {"log the parsing of .debug_pubnames"}, - DWARF_LOG_DEBUG_PUBNAMES}, - {{"pubtypes"}, - {"log the parsing of .debug_pubtypes"}, - DWARF_LOG_DEBUG_PUBTYPES}, }; Log::Channel LogChannelDWARF::g_channel(g_categories, DWARF_LOG_DEFAULT);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.h index 038e9b8..a89c686 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/LogChannelDWARF.h
@@ -1,9 +1,8 @@ //===-- LogChannelDWARF.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,12 +13,9 @@ #define DWARF_LOG_DEBUG_INFO (1u << 1) #define DWARF_LOG_DEBUG_LINE (1u << 2) -#define DWARF_LOG_DEBUG_PUBNAMES (1u << 3) -#define DWARF_LOG_DEBUG_PUBTYPES (1u << 4) -#define DWARF_LOG_DEBUG_ARANGES (1u << 5) -#define DWARF_LOG_LOOKUPS (1u << 6) -#define DWARF_LOG_TYPE_COMPLETION (1u << 7) -#define DWARF_LOG_DEBUG_MAP (1u << 8) +#define DWARF_LOG_LOOKUPS (1u << 3) +#define DWARF_LOG_TYPE_COMPLETION (1u << 4) +#define DWARF_LOG_DEBUG_MAP (1u << 5) #define DWARF_LOG_ALL (UINT32_MAX) #define DWARF_LOG_DEFAULT (DWARF_LOG_DEBUG_INFO)
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp index 6438f02..aff8b5d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp
@@ -1,9 +1,8 @@ //===-- ManualDWARFIndex.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -33,9 +32,9 @@ Timer scoped_timer(func_cat, "%p", static_cast<void *>(&debug_info)); std::vector<DWARFUnit *> units_to_index; - units_to_index.reserve(debug_info.GetNumCompileUnits()); - for (size_t U = 0; U < debug_info.GetNumCompileUnits(); ++U) { - DWARFUnit *unit = debug_info.GetCompileUnitAtIndex(U); + units_to_index.reserve(debug_info.GetNumUnits()); + for (size_t U = 0; U < debug_info.GetNumUnits(); ++U) { + DWARFUnit *unit = debug_info.GetUnitAtIndex(U); if (unit && m_units_to_avoid.count(unit->GetOffset()) == 0) units_to_index.push_back(unit); } @@ -44,10 +43,8 @@ std::vector<IndexSet> sets(units_to_index.size()); - //---------------------------------------------------------------------- - // Keep memory down by clearing DIEs for any compile units if indexing - // caused us to load the compile unit's DIEs. - //---------------------------------------------------------------------- + // Keep memory down by clearing DIEs for any units if indexing + // caused us to load the unit's DIEs. std::vector<llvm::Optional<DWARFUnit::ScopedExtractDIEs>> clear_cu_dies( units_to_index.size()); auto parser_fn = [&](size_t cu_idx) { @@ -58,19 +55,17 @@ clear_cu_dies[cu_idx] = units_to_index[cu_idx]->ExtractDIEsScoped(); }; - // Create a task runner that extracts dies for each DWARF compile unit in a + // Create a task runner that extracts dies for each DWARF unit in a // separate thread - //---------------------------------------------------------------------- - // First figure out which compile units didn't have their DIEs already + // First figure out which units didn't have their DIEs already // parsed and remember this. If no DIEs were parsed prior to this index // function call, we are going to want to clear the CU dies after we are // done indexing to make sure we don't pull in all DWARF dies, but we need - // to wait until all compile units have been indexed in case a DIE in one - // compile unit refers to another and the indexes accesses those DIEs. - //---------------------------------------------------------------------- + // to wait until all units have been indexed in case a DIE in one + // unit refers to another and the indexes accesses those DIEs. TaskMapOverInt(0, units_to_index.size(), extract_fn); - // Now create a task runner that can index each DWARF compile unit in a + // Now create a task runner that can index each DWARF unit in a // separate thread so we can index quickly. TaskMapOverInt(0, units_to_index.size(), parser_fn); @@ -93,30 +88,32 @@ } void ManualDWARFIndex::IndexUnit(DWARFUnit &unit, IndexSet &set) { + assert( + !unit.GetSymbolFileDWARF().GetBaseCompileUnit() && + "DWARFUnit associated with .dwo or .dwp should not be indexed directly"); + Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS); if (log) { m_module.LogMessage( - log, "ManualDWARFIndex::IndexUnit for compile unit at .debug_info[0x%8.8x]", + log, "ManualDWARFIndex::IndexUnit for unit at .debug_info[0x%8.8x]", unit.GetOffset()); } const LanguageType cu_language = unit.GetLanguageType(); - DWARFFormValue::FixedFormSizes fixed_form_sizes = unit.GetFixedFormSizes(); - IndexUnitImpl(unit, cu_language, fixed_form_sizes, unit.GetOffset(), set); + IndexUnitImpl(unit, cu_language, set); - SymbolFileDWARFDwo *dwo_symbol_file = unit.GetDwoSymbolFile(); - if (dwo_symbol_file && dwo_symbol_file->GetCompileUnit()) { - IndexUnitImpl(*dwo_symbol_file->GetCompileUnit(), cu_language, - fixed_form_sizes, unit.GetOffset(), set); + if (SymbolFileDWARFDwo *dwo_symbol_file = unit.GetDwoSymbolFile()) { + DWARFDebugInfo &dwo_info = *dwo_symbol_file->DebugInfo(); + for (size_t i = 0; i < dwo_info.GetNumUnits(); ++i) + IndexUnitImpl(*dwo_info.GetUnitAtIndex(i), cu_language, set); } } -void ManualDWARFIndex::IndexUnitImpl( - DWARFUnit &unit, const LanguageType cu_language, - const DWARFFormValue::FixedFormSizes &fixed_form_sizes, - const dw_offset_t cu_offset, IndexSet &set) { +void ManualDWARFIndex::IndexUnitImpl(DWARFUnit &unit, + const LanguageType cu_language, + IndexSet &set) { for (const DWARFDebugInfoEntry &die : unit.dies()) { const dw_tag_t tag = die.Tag(); @@ -143,8 +140,8 @@ } DWARFAttributes attributes; - const char *name = NULL; - const char *mangled_cstr = NULL; + const char *name = nullptr; + const char *mangled_cstr = nullptr; bool is_declaration = false; // bool is_artificial = false; bool has_address = false; @@ -152,8 +149,7 @@ bool is_global_or_static_variable = false; DWARFFormValue specification_die_form; - const size_t num_attributes = - die.GetAttributes(&unit, fixed_form_sizes, attributes); + const size_t num_attributes = die.GetAttributes(&unit, attributes); if (num_attributes > 0) { for (uint32_t i = 0; i < num_attributes; ++i) { dw_attr_t attr = attributes.AttributeAtIndex(i); @@ -196,7 +192,7 @@ has_location_or_const_value = true; if (tag == DW_TAG_variable) { const DWARFDebugInfoEntry *parent_die = die.GetParent(); - while (parent_die != NULL) { + while (parent_die != nullptr) { switch (parent_die->Tag()) { case DW_TAG_subprogram: case DW_TAG_lexical_block: @@ -215,19 +211,19 @@ // if (block_data) { // uint32_t block_length = form_value.Unsigned(); // if (block_length == 1 + - // attributes.CompileUnitAtIndex(i)->GetAddressByteSize()) { + // attributes.UnitAtIndex(i)->GetAddressByteSize()) { // if (block_data[0] == DW_OP_addr) // add_die = true; // } // } // } - parent_die = NULL; // Terminate the while loop. + parent_die = nullptr; // Terminate the while loop. break; case DW_TAG_compile_unit: case DW_TAG_partial_unit: is_global_or_static_variable = true; - parent_die = NULL; // Terminate the while loop. + parent_die = nullptr; // Terminate the while loop. break; default: @@ -247,51 +243,48 @@ } } + DIERef ref = *DWARFDIE(&unit, &die).GetDIERef(); switch (tag) { case DW_TAG_inlined_subroutine: case DW_TAG_subprogram: if (has_address) { if (name) { - ObjCLanguage::MethodName objc_method(name, true); - if (objc_method.IsValid(true)) { - ConstString objc_class_name_with_category( - objc_method.GetClassNameWithCategory()); - ConstString objc_selector_name(objc_method.GetSelector()); - ConstString objc_fullname_no_category_name( - objc_method.GetFullNameWithoutCategory(true)); - ConstString objc_class_name_no_category(objc_method.GetClassName()); - set.function_fullnames.Insert(ConstString(name), - DIERef(cu_offset, die.GetOffset())); - if (objc_class_name_with_category) - set.objc_class_selectors.Insert( - objc_class_name_with_category, - DIERef(cu_offset, die.GetOffset())); - if (objc_class_name_no_category && - objc_class_name_no_category != objc_class_name_with_category) - set.objc_class_selectors.Insert( - objc_class_name_no_category, - DIERef(cu_offset, die.GetOffset())); - if (objc_selector_name) - set.function_selectors.Insert(objc_selector_name, - DIERef(cu_offset, die.GetOffset())); - if (objc_fullname_no_category_name) - set.function_fullnames.Insert(objc_fullname_no_category_name, - DIERef(cu_offset, die.GetOffset())); + bool is_objc_method = false; + if (cu_language == eLanguageTypeObjC || + cu_language == eLanguageTypeObjC_plus_plus) { + ObjCLanguage::MethodName objc_method(name, true); + if (objc_method.IsValid(true)) { + is_objc_method = true; + ConstString class_name_with_category( + objc_method.GetClassNameWithCategory()); + ConstString objc_selector_name(objc_method.GetSelector()); + ConstString objc_fullname_no_category_name( + objc_method.GetFullNameWithoutCategory(true)); + ConstString class_name_no_category(objc_method.GetClassName()); + set.function_fullnames.Insert(ConstString(name), ref); + if (class_name_with_category) + set.objc_class_selectors.Insert(class_name_with_category, ref); + if (class_name_no_category && + class_name_no_category != class_name_with_category) + set.objc_class_selectors.Insert(class_name_no_category, ref); + if (objc_selector_name) + set.function_selectors.Insert(objc_selector_name, ref); + if (objc_fullname_no_category_name) + set.function_fullnames.Insert(objc_fullname_no_category_name, + ref); + } } // If we have a mangled name, then the DW_AT_name attribute is // usually the method name without the class or any parameters bool is_method = DWARFDIE(&unit, &die).IsMethod(); if (is_method) - set.function_methods.Insert(ConstString(name), - DIERef(cu_offset, die.GetOffset())); + set.function_methods.Insert(ConstString(name), ref); else - set.function_basenames.Insert(ConstString(name), - DIERef(cu_offset, die.GetOffset())); + set.function_basenames.Insert(ConstString(name), ref); - if (!is_method && !mangled_cstr && !objc_method.IsValid(true)) - set.function_fullnames.Insert(ConstString(name), - DIERef(cu_offset, die.GetOffset())); + if (!is_method && !mangled_cstr && !is_objc_method) + set.function_fullnames.Insert(ConstString(name), ref); } if (mangled_cstr) { // Make sure our mangled name isn't the same string table entry as @@ -301,8 +294,7 @@ if (name && name != mangled_cstr && ((mangled_cstr[0] == '_') || (::strcmp(name, mangled_cstr) != 0))) { - set.function_fullnames.Insert(ConstString(mangled_cstr), - DIERef(cu_offset, die.GetOffset())); + set.function_fullnames.Insert(ConstString(mangled_cstr), ref); } } } @@ -320,22 +312,19 @@ case DW_TAG_union_type: case DW_TAG_unspecified_type: if (name && !is_declaration) - set.types.Insert(ConstString(name), DIERef(cu_offset, die.GetOffset())); + set.types.Insert(ConstString(name), ref); if (mangled_cstr && !is_declaration) - set.types.Insert(ConstString(mangled_cstr), - DIERef(cu_offset, die.GetOffset())); + set.types.Insert(ConstString(mangled_cstr), ref); break; case DW_TAG_namespace: if (name) - set.namespaces.Insert(ConstString(name), - DIERef(cu_offset, die.GetOffset())); + set.namespaces.Insert(ConstString(name), ref); break; case DW_TAG_variable: if (name && has_location_or_const_value && is_global_or_static_variable) { - set.globals.Insert(ConstString(name), - DIERef(cu_offset, die.GetOffset())); + set.globals.Insert(ConstString(name), ref); // Be sure to include variables by their mangled and demangled names if // they have any since a variable can have a basename "i", a mangled // named "_ZN12_GLOBAL__N_11iE" and a demangled mangled name @@ -347,8 +336,7 @@ // entries if (mangled_cstr && name != mangled_cstr && ((mangled_cstr[0] == '_') || (::strcmp(name, mangled_cstr) != 0))) { - set.globals.Insert(ConstString(mangled_cstr), - DIERef(cu_offset, die.GetOffset())); + set.globals.Insert(ConstString(mangled_cstr), ref); } } break; @@ -370,10 +358,10 @@ m_set.globals.Find(regex, offsets); } -void ManualDWARFIndex::GetGlobalVariables(const DWARFUnit &cu, +void ManualDWARFIndex::GetGlobalVariables(const DWARFUnit &unit, DIEArray &offsets) { Index(); - m_set.globals.FindAllEntriesForCompileUnit(cu.GetOffset(), offsets); + m_set.globals.FindAllEntriesForUnit(unit, offsets); } void ManualDWARFIndex::GetObjCMethods(ConstString class_name, @@ -405,7 +393,7 @@ m_set.namespaces.Find(name, offsets); } -void ManualDWARFIndex::GetFunctions(ConstString name, DWARFDebugInfo &info, +void ManualDWARFIndex::GetFunctions(ConstString name, SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) { @@ -417,7 +405,7 @@ m_set.function_methods.Find(name, offsets); m_set.function_fullnames.Find(name, offsets); for (const DIERef &die_ref: offsets) { - DWARFDIE die = info.GetDIE(die_ref); + DWARFDIE die = dwarf.GetDIE(die_ref); if (!die) continue; if (SymbolFileDWARF::DIEInDeclContext(&parent_decl_ctx, die)) @@ -428,7 +416,7 @@ DIEArray offsets; m_set.function_basenames.Find(name, offsets); for (const DIERef &die_ref: offsets) { - DWARFDIE die = info.GetDIE(die_ref); + DWARFDIE die = dwarf.GetDIE(die_ref); if (!die) continue; if (SymbolFileDWARF::DIEInDeclContext(&parent_decl_ctx, die)) @@ -441,7 +429,7 @@ DIEArray offsets; m_set.function_methods.Find(name, offsets); for (const DIERef &die_ref: offsets) { - if (DWARFDIE die = info.GetDIE(die_ref)) + if (DWARFDIE die = dwarf.GetDIE(die_ref)) dies.push_back(die); } } @@ -451,7 +439,7 @@ DIEArray offsets; m_set.function_selectors.Find(name, offsets); for (const DIERef &die_ref: offsets) { - if (DWARFDIE die = info.GetDIE(die_ref)) + if (DWARFDIE die = dwarf.GetDIE(die_ref)) dies.push_back(die); } }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.h index 79ab1d9..dd03b10 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.h
@@ -1,9 +1,8 @@ -//===-- ManulaDWARFIndex.h -------------------------------------*- C++ -*-===// +//===-- ManualDWARFIndex.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,6 +13,8 @@ #include "Plugins/SymbolFile/DWARF/NameToDIE.h" #include "llvm/ADT/DenseSet.h" +class DWARFDebugInfo; + namespace lldb_private { class ManualDWARFIndex : public DWARFIndex { public: @@ -27,21 +28,20 @@ void GetGlobalVariables(ConstString basename, DIEArray &offsets) override; void GetGlobalVariables(const RegularExpression ®ex, DIEArray &offsets) override; - void GetGlobalVariables(const DWARFUnit &cu, DIEArray &offsets) override; + void GetGlobalVariables(const DWARFUnit &unit, DIEArray &offsets) override; void GetObjCMethods(ConstString class_name, DIEArray &offsets) override; void GetCompleteObjCClass(ConstString class_name, bool must_be_implementation, DIEArray &offsets) override; void GetTypes(ConstString name, DIEArray &offsets) override; void GetTypes(const DWARFDeclContext &context, DIEArray &offsets) override; void GetNamespaces(ConstString name, DIEArray &offsets) override; - void GetFunctions(ConstString name, DWARFDebugInfo &info, + void GetFunctions(ConstString name, SymbolFileDWARF &dwarf, const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask, std::vector<DWARFDIE> &dies) override; void GetFunctions(const RegularExpression ®ex, DIEArray &offsets) override; - void ReportInvalidDIEOffset(dw_offset_t offset, - llvm::StringRef name) override {} + void ReportInvalidDIERef(const DIERef &ref, llvm::StringRef name) override {} void Dump(Stream &s) override; private: @@ -58,10 +58,9 @@ void Index(); void IndexUnit(DWARFUnit &unit, IndexSet &set); - static void - IndexUnitImpl(DWARFUnit &unit, const lldb::LanguageType cu_language, - const DWARFFormValue::FixedFormSizes &fixed_form_sizes, - const dw_offset_t cu_offset, IndexSet &set); + static void IndexUnitImpl(DWARFUnit &unit, + const lldb::LanguageType cu_language, + IndexSet &set); /// Non-null value means we haven't built the index yet. DWARFDebugInfo *m_debug_info;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.cpp index c8d6bba..7d81afb 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.cpp
@@ -1,23 +1,19 @@ //===-- NameToDIE.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "NameToDIE.h" +#include "DWARFUnit.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" -#include "DWARFDebugInfo.h" -#include "DWARFDebugInfoEntry.h" -#include "SymbolFileDWARF.h" - using namespace lldb; using namespace lldb_private; @@ -26,11 +22,11 @@ m_map.SizeToFit(); } -void NameToDIE::Insert(const ConstString &name, const DIERef &die_ref) { +void NameToDIE::Insert(ConstString name, const DIERef &die_ref) { m_map.Append(name, die_ref); } -size_t NameToDIE::Find(const ConstString &name, DIEArray &info_array) const { +size_t NameToDIE::Find(ConstString name, DIEArray &info_array) const { return m_map.GetValues(name, info_array); } @@ -39,13 +35,16 @@ return m_map.GetValues(regex, info_array); } -size_t NameToDIE::FindAllEntriesForCompileUnit(dw_offset_t cu_offset, - DIEArray &info_array) const { +size_t NameToDIE::FindAllEntriesForUnit(const DWARFUnit &unit, + DIEArray &info_array) const { const size_t initial_size = info_array.size(); const uint32_t size = m_map.GetSize(); for (uint32_t i = 0; i < size; ++i) { const DIERef &die_ref = m_map.GetValueAtIndexUnchecked(i); - if (cu_offset == die_ref.cu_offset) + if (unit.GetSymbolFileDWARF().GetDwoNum() == die_ref.dwo_num() && + unit.GetDebugSection() == die_ref.section() && + unit.GetOffset() <= die_ref.die_offset() && + die_ref.die_offset() < unit.GetNextUnitOffset()) info_array.push_back(die_ref); } return info_array.size() - initial_size; @@ -54,10 +53,8 @@ void NameToDIE::Dump(Stream *s) { const uint32_t size = m_map.GetSize(); for (uint32_t i = 0; i < size; ++i) { - ConstString cstr = m_map.GetCStringAtIndex(i); - const DIERef &die_ref = m_map.GetValueAtIndexUnchecked(i); - s->Printf("%p: {0x%8.8x/0x%8.8x} \"%s\"\n", (const void *)cstr.GetCString(), - die_ref.cu_offset, die_ref.die_offset, cstr.GetCString()); + s->Format("{0} \"{1}\"\n", m_map.GetValueAtIndexUnchecked(i), + m_map.GetCStringAtIndexUnchecked(i)); } }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.h index bba44fd..b504f45 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.h
@@ -1,9 +1,8 @@ //===-- NameToDIE.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,7 +16,7 @@ #include "lldb/Core/dwarf.h" #include "lldb/lldb-defines.h" -class SymbolFileDWARF; +class DWARFUnit; class NameToDIE { public: @@ -27,20 +26,20 @@ void Dump(lldb_private::Stream *s); - void Insert(const lldb_private::ConstString &name, const DIERef &die_ref); + void Insert(lldb_private::ConstString name, const DIERef &die_ref); void Append(const NameToDIE &other); void Finalize(); - size_t Find(const lldb_private::ConstString &name, + size_t Find(lldb_private::ConstString name, DIEArray &info_array) const; size_t Find(const lldb_private::RegularExpression ®ex, DIEArray &info_array) const; - size_t FindAllEntriesForCompileUnit(dw_offset_t cu_offset, - DIEArray &info_array) const; + size_t FindAllEntriesForUnit(const DWARFUnit &unit, + DIEArray &info_array) const; void ForEach(std::function<bool(lldb_private::ConstString name,
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp index 2a0a89f..e2ddcfc 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,7 +29,6 @@ #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" -#include "lldb/Host/Symbols.h" #include "lldb/Interpreter/OptionValueFileSpecList.h" #include "lldb/Interpreter/OptionValueProperties.h" @@ -43,6 +41,7 @@ #include "lldb/Symbol/CompilerDeclContext.h" #include "lldb/Symbol/DebugMacros.h" #include "lldb/Symbol/LineTable.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolVendor.h" #include "lldb/Symbol/TypeMap.h" @@ -50,11 +49,12 @@ #include "lldb/Symbol/VariableList.h" #include "lldb/Target/Language.h" +#include "lldb/Target/Target.h" #include "AppleDWARFIndex.h" #include "DWARFASTParser.h" #include "DWARFASTParserClang.h" -#include "DWARFDIECollection.h" +#include "DWARFCompileUnit.h" #include "DWARFDebugAbbrev.h" #include "DWARFDebugAranges.h" #include "DWARFDebugInfo.h" @@ -63,6 +63,7 @@ #include "DWARFDebugRanges.h" #include "DWARFDeclContext.h" #include "DWARFFormValue.h" +#include "DWARFTypeUnit.h" #include "DWARFUnit.h" #include "DebugNamesDWARFIndex.h" #include "LogChannelDWARF.h" @@ -73,7 +74,9 @@ #include "llvm/Support/FileSystem.h" +#include <algorithm> #include <map> +#include <memory> #include <ctype.h> #include <string.h> @@ -131,12 +134,12 @@ } PluginProperties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); } - FileSpecList &GetSymLinkPaths() { - OptionValueFileSpecList *option_value = + FileSpecList GetSymLinkPaths() { + const OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList( nullptr, true, ePropertySymLinkPaths); assert(option_value); @@ -158,68 +161,8 @@ } // anonymous namespace end -static const char *removeHostnameFromPathname(const char *path_from_dwarf) { - if (!path_from_dwarf || !path_from_dwarf[0]) { - return path_from_dwarf; - } - - const char *colon_pos = strchr(path_from_dwarf, ':'); - if (nullptr == colon_pos) { - return path_from_dwarf; - } - - const char *slash_pos = strchr(path_from_dwarf, '/'); - if (slash_pos && (slash_pos < colon_pos)) { - return path_from_dwarf; - } - - // check whether we have a windows path, and so the first character is a - // drive-letter not a hostname. - if (colon_pos == path_from_dwarf + 1 && isalpha(*path_from_dwarf) && - strlen(path_from_dwarf) > 2 && '\\' == path_from_dwarf[2]) { - return path_from_dwarf; - } - - return colon_pos + 1; -} - -static FileSpec resolveCompDir(const char *path_from_dwarf) { - if (!path_from_dwarf) - return FileSpec(); - - // DWARF2/3 suggests the form hostname:pathname for compilation directory. - // Remove the host part if present. - const char *local_path = removeHostnameFromPathname(path_from_dwarf); - if (!local_path) - return FileSpec(); - - bool is_symlink = false; - // Always normalize our compile unit directory to get rid of redundant - // slashes and other path anomalies before we use it for path prepending - FileSpec local_spec(local_path); - const auto &file_specs = GetGlobalPluginProperties()->GetSymLinkPaths(); - for (size_t i = 0; i < file_specs.GetSize() && !is_symlink; ++i) - is_symlink = FileSpec::Equal(file_specs.GetFileSpecAtIndex(i), - local_spec, true); - - if (!is_symlink) - return local_spec; - - namespace fs = llvm::sys::fs; - if (fs::get_file_type(local_spec.GetPath(), false) != - fs::file_type::symlink_file) - return local_spec; - - FileSpec resolved_symlink; - const auto error = FileSystem::Instance().Readlink(local_spec, resolved_symlink); - if (error.Success()) - return resolved_symlink; - - return local_spec; -} - -DWARFUnit *SymbolFileDWARF::GetBaseCompileUnit() { - return nullptr; +FileSpecList SymbolFileDWARF::GetSymlinkPaths() { + return GetGlobalPluginProperties()->GetSymLinkPaths(); } void SymbolFileDWARF::Initialize() { @@ -255,7 +198,8 @@ } SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFile *obj_file) { - return new SymbolFileDWARF(obj_file); + return new SymbolFileDWARF(obj_file, + /*dwo_section_list*/ nullptr); } TypeList *SymbolFileDWARF::GetTypeList() { @@ -346,23 +290,23 @@ ASSERT_MODULE_LOCK(this); TypeSet type_set; - CompileUnit *comp_unit = NULL; - DWARFUnit *dwarf_cu = NULL; + CompileUnit *comp_unit = nullptr; + DWARFUnit *dwarf_cu = nullptr; if (sc_scope) comp_unit = sc_scope->CalculateSymbolContextCompileUnit(); if (comp_unit) { dwarf_cu = GetDWARFCompileUnit(comp_unit); - if (dwarf_cu == 0) + if (dwarf_cu == nullptr) return 0; GetTypes(dwarf_cu->DIE(), dwarf_cu->GetOffset(), - dwarf_cu->GetNextCompileUnitOffset(), type_mask, type_set); + dwarf_cu->GetNextUnitOffset(), type_mask, type_set); } else { DWARFDebugInfo *info = DebugInfo(); if (info) { - const size_t num_cus = info->GetNumCompileUnits(); + const size_t num_cus = info->GetNumUnits(); for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) { - dwarf_cu = info->GetCompileUnitAtIndex(cu_idx); + dwarf_cu = info->GetUnitAtIndex(cu_idx); if (dwarf_cu) { GetTypes(dwarf_cu->DIE(), 0, UINT32_MAX, type_mask, type_set); } @@ -383,10 +327,8 @@ return num_types_added; } -//---------------------------------------------------------------------- // Gets the first parent that is a lexical block, function or inlined // subroutine, or compile unit. -//---------------------------------------------------------------------- DWARFDIE SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) { DWARFDIE die; @@ -405,23 +347,21 @@ return DWARFDIE(); } -SymbolFileDWARF::SymbolFileDWARF(ObjectFile *objfile) - : SymbolFile(objfile), UserID(uint64_t(DW_INVALID_OFFSET) - << 32), // Used by SymbolFileDWARFDebugMap to - // when this class parses .o files to - // contain the .o file index/ID - m_debug_map_module_wp(), m_debug_map_symfile(NULL), m_data_debug_abbrev(), - m_data_debug_aranges(), m_data_debug_frame(), m_data_debug_info(), - m_data_debug_line(), m_data_debug_macro(), m_data_debug_loc(), - m_data_debug_ranges(), m_data_debug_rnglists(), m_data_debug_str(), - m_data_apple_names(), m_data_apple_types(), m_data_apple_namespaces(), - m_abbr(), m_info(), m_line(), m_fetched_external_modules(false), - m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate), m_ranges(), +SymbolFileDWARF::SymbolFileDWARF(ObjectFile *objfile, + SectionList *dwo_section_list) + : SymbolFile(objfile), + UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to + // when this class parses .o files to + // contain the .o file index/ID + m_debug_map_module_wp(), m_debug_map_symfile(nullptr), + m_context(objfile->GetModule()->GetSectionList(), dwo_section_list), + m_data_debug_loc(), m_abbr(), m_info(), m_fetched_external_modules(false), + m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate), m_unique_ast_type_map() {} SymbolFileDWARF::~SymbolFileDWARF() {} -static const ConstString &GetDWARFMachOSegmentName() { +static ConstString GetDWARFMachOSegmentName() { static ConstString g_dwarf_section_name("__DWARF"); return g_dwarf_section_name; } @@ -449,15 +389,6 @@ void SymbolFileDWARF::InitializeObject() { Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); - ModuleSP module_sp(m_obj_file->GetModule()); - if (module_sp) { - const SectionList *section_list = module_sp->GetSectionList(); - Section *section = - section_list->FindSectionByName(GetDWARFMachOSegmentName()).get(); - - if (section) - m_obj_file->ReadSectionData(section, m_dwarf_data); - } if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) { DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc; @@ -468,7 +399,7 @@ m_index = AppleDWARFIndex::Create( *GetObjectFile()->GetModule(), apple_names, apple_namespaces, - apple_types, apple_objc, get_debug_str_data()); + apple_types, apple_objc, m_context.getOrLoadStrData()); if (m_index) return; @@ -477,9 +408,9 @@ LoadSectionData(eSectionTypeDWARFDebugNames, debug_names); if (debug_names.GetByteSize() > 0) { llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or = - DebugNamesDWARFIndex::Create(*GetObjectFile()->GetModule(), - debug_names, get_debug_str_data(), - DebugInfo()); + DebugNamesDWARFIndex::Create( + *GetObjectFile()->GetModule(), debug_names, + m_context.getOrLoadStrData(), DebugInfo()); if (index_or) { m_index = std::move(*index_or); return; @@ -499,26 +430,12 @@ uint32_t SymbolFileDWARF::CalculateAbilities() { uint32_t abilities = 0; - if (m_obj_file != NULL) { - const Section *section = NULL; + if (m_obj_file != nullptr) { + const Section *section = nullptr; const SectionList *section_list = m_obj_file->GetSectionList(); - if (section_list == NULL) + if (section_list == nullptr) return 0; - // On non Apple platforms we might have .debug_types debug info that is - // created by using "-fdebug-types-section". LLDB currently will try to - // load this debug info, but it causes crashes during debugging when types - // are missing since it doesn't know how to parse the info in the - // .debug_types type units. This causes all complex debug info types to be - // unresolved. Because this causes LLDB to crash and since it really - // doesn't provide a solid debuggiung experience, we should disable trying - // to debug this kind of DWARF until support gets added or deprecated. - if (section_list->FindSectionByName(ConstString(".debug_types"))) { - m_obj_file->GetModule()->ReportWarning( - "lldb doesn’t support .debug_types debug info"); - return 0; - } - uint64_t debug_abbrev_file_size = 0; uint64_t debug_info_file_size = 0; uint64_t debug_line_file_size = 0; @@ -530,7 +447,7 @@ section = section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get(); - if (section != NULL) { + if (section != nullptr) { debug_info_file_size = section->GetFileSize(); section = @@ -604,53 +521,15 @@ DWARFDataExtractor &data) { ModuleSP module_sp(m_obj_file->GetModule()); const SectionList *section_list = module_sp->GetSectionList(); - if (section_list) { - SectionSP section_sp(section_list->FindSectionByType(sect_type, true)); - if (section_sp) { - // See if we memory mapped the DWARF segment? - if (m_dwarf_data.GetByteSize()) { - data.SetData(m_dwarf_data, section_sp->GetOffset(), - section_sp->GetFileSize()); - } else { - if (m_obj_file->ReadSectionData(section_sp.get(), data) == 0) - data.Clear(); - } - } - } -} + if (!section_list) + return; -const DWARFDataExtractor &SymbolFileDWARF::get_debug_abbrev_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugAbbrev, - m_data_debug_abbrev); -} + SectionSP section_sp(section_list->FindSectionByType(sect_type, true)); + if (!section_sp) + return; -const DWARFDataExtractor &SymbolFileDWARF::get_debug_addr_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugAddr, m_data_debug_addr); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_aranges_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugAranges, - m_data_debug_aranges); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_frame_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugFrame, m_data_debug_frame); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_info_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugInfo, m_data_debug_info); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_line_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugLine, m_data_debug_line); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_line_str_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugLineStr, m_data_debug_line_str); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_macro_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugMacro, m_data_debug_macro); + data.Clear(); + m_obj_file->ReadSectionData(section_sp.get(), data); } const DWARFDataExtractor &SymbolFileDWARF::DebugLocData() { @@ -669,60 +548,24 @@ m_data_debug_loclists); } -const DWARFDataExtractor &SymbolFileDWARF::get_debug_ranges_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugRanges, - m_data_debug_ranges); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_rnglists_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugRngLists, - m_data_debug_rnglists); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_str_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugStr, m_data_debug_str); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_str_offsets_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugStrOffsets, - m_data_debug_str_offsets); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_debug_types_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugTypes, m_data_debug_types); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_apple_names_data() { - return GetCachedSectionData(eSectionTypeDWARFAppleNames, m_data_apple_names); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_apple_types_data() { - return GetCachedSectionData(eSectionTypeDWARFAppleTypes, m_data_apple_types); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_apple_namespaces_data() { - return GetCachedSectionData(eSectionTypeDWARFAppleNamespaces, - m_data_apple_namespaces); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_apple_objc_data() { - return GetCachedSectionData(eSectionTypeDWARFAppleObjC, m_data_apple_objc); -} - -const DWARFDataExtractor &SymbolFileDWARF::get_gnu_debugaltlink() { - return GetCachedSectionData(eSectionTypeDWARFGNUDebugAltLink, - m_data_gnu_debugaltlink); -} - DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() { - if (m_abbr.get() == NULL) { - const DWARFDataExtractor &debug_abbrev_data = get_debug_abbrev_data(); - if (debug_abbrev_data.GetByteSize() > 0) { - m_abbr.reset(new DWARFDebugAbbrev()); - if (m_abbr.get()) - m_abbr->Parse(debug_abbrev_data); - } + if (m_abbr) + return m_abbr.get(); + + const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData(); + if (debug_abbrev_data.GetByteSize() == 0) + return nullptr; + + auto abbr = llvm::make_unique<DWARFDebugAbbrev>(); + llvm::Error error = abbr->parse(debug_abbrev_data); + if (error) { + Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); + LLDB_LOG_ERROR(log, std::move(error), + "Unable to read .debug_abbrev section: {0}"); + return nullptr; } + + m_abbr = std::move(abbr); return m_abbr.get(); } @@ -731,16 +574,12 @@ } DWARFDebugInfo *SymbolFileDWARF::DebugInfo() { - if (m_info.get() == NULL) { + if (m_info == nullptr) { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); - if (get_debug_info_data().GetByteSize() > 0) { - m_info.reset(new DWARFDebugInfo()); - if (m_info.get()) { - m_info->SetDwarfData(this); - } - } + if (m_context.getOrLoadDebugInfoData().GetByteSize() > 0) + m_info = llvm::make_unique<DWARFDebugInfo>(*this, m_context); } return m_info.get(); } @@ -756,109 +595,90 @@ DWARFDebugInfo *info = DebugInfo(); if (info) { - // Just a normal DWARF file whose user ID for the compile unit is the DWARF - // offset itself - - DWARFUnit *dwarf_cu = - info->GetCompileUnit((dw_offset_t)comp_unit->GetID()); - if (dwarf_cu && dwarf_cu->GetUserData() == NULL) + // The compile unit ID is the index of the DWARF unit. + DWARFUnit *dwarf_cu = info->GetUnitAtIndex(comp_unit->GetID()); + if (dwarf_cu && dwarf_cu->GetUserData() == nullptr) dwarf_cu->SetUserData(comp_unit); return dwarf_cu; } - return NULL; + return nullptr; } -DWARFDebugRangesBase *SymbolFileDWARF::DebugRanges() { - if (m_ranges.get() == NULL) { +DWARFDebugRangesBase *SymbolFileDWARF::GetDebugRanges() { + if (!m_ranges) { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); - if (get_debug_ranges_data().GetByteSize() > 0) + if (m_context.getOrLoadRangesData().GetByteSize() > 0) m_ranges.reset(new DWARFDebugRanges()); - else if (get_debug_rnglists_data().GetByteSize() > 0) - m_ranges.reset(new DWARFDebugRngLists()); - if (m_ranges.get()) - m_ranges->Extract(this); + if (m_ranges) + m_ranges->Extract(m_context); } return m_ranges.get(); } -const DWARFDebugRangesBase *SymbolFileDWARF::DebugRanges() const { - return m_ranges.get(); +DWARFDebugRangesBase *SymbolFileDWARF::GetDebugRngLists() { + if (!m_rnglists) { + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, + static_cast<void *>(this)); + + if (m_context.getOrLoadRngListsData().GetByteSize() > 0) + m_rnglists.reset(new DWARFDebugRngLists()); + + if (m_rnglists) + m_rnglists->Extract(m_context); + } + return m_rnglists.get(); } -lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFUnit *dwarf_cu, - uint32_t cu_idx) { +lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) { CompUnitSP cu_sp; - if (dwarf_cu) { - CompileUnit *comp_unit = (CompileUnit *)dwarf_cu->GetUserData(); - if (comp_unit) { - // We already parsed this compile unit, had out a shared pointer to it - cu_sp = comp_unit->shared_from_this(); + CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData(); + if (comp_unit) { + // We already parsed this compile unit, had out a shared pointer to it + cu_sp = comp_unit->shared_from_this(); + } else { + if (&dwarf_cu.GetSymbolFileDWARF() != this) { + return dwarf_cu.GetSymbolFileDWARF().ParseCompileUnit(dwarf_cu); + } else if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) { + // Let the debug map create the compile unit + cu_sp = m_debug_map_symfile->GetCompileUnit(this); + dwarf_cu.SetUserData(cu_sp.get()); } else { - if (dwarf_cu->GetSymbolFileDWARF() != this) { - return dwarf_cu->GetSymbolFileDWARF()->ParseCompileUnit(dwarf_cu, - cu_idx); - } else if (dwarf_cu->GetOffset() == 0 && GetDebugMapSymfile()) { - // Let the debug map create the compile unit - cu_sp = m_debug_map_symfile->GetCompileUnit(this); - dwarf_cu->SetUserData(cu_sp.get()); - } else { - ModuleSP module_sp(m_obj_file->GetModule()); - if (module_sp) { - const DWARFDIE cu_die = dwarf_cu->DIE(); - if (cu_die) { - FileSpec cu_file_spec(cu_die.GetName()); - if (cu_file_spec) { - // If we have a full path to the compile unit, we don't need to - // resolve the file. This can be expensive e.g. when the source - // files are - // NFS mounted. - if (cu_file_spec.IsRelative()) { - const char *cu_comp_dir{ - cu_die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr)}; - cu_file_spec.PrependPathComponent(resolveCompDir(cu_comp_dir)); - } + ModuleSP module_sp(m_obj_file->GetModule()); + if (module_sp) { + const DWARFDIE cu_die = dwarf_cu.DIE(); + if (cu_die) { + FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle()); + if (cu_file_spec) { + // If we have a full path to the compile unit, we don't need to + // resolve the file. This can be expensive e.g. when the source + // files are NFS mounted. + cu_file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory()); - std::string remapped_file; - if (module_sp->RemapSourceFile(cu_file_spec.GetPath(), - remapped_file)) - cu_file_spec.SetFile(remapped_file, FileSpec::Style::native); - } - - LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF( - cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0)); - - bool is_optimized = dwarf_cu->GetIsOptimized(); - cu_sp.reset(new CompileUnit( - module_sp, dwarf_cu, cu_file_spec, dwarf_cu->GetID(), - cu_language, is_optimized ? eLazyBoolYes : eLazyBoolNo)); - if (cu_sp) { - // If we just created a compile unit with an invalid file spec, - // try and get the first entry in the supports files from the - // line table as that should be the compile unit. - if (!cu_file_spec) { - cu_file_spec = cu_sp->GetSupportFiles().GetFileSpecAtIndex(1); - if (cu_file_spec) { - (FileSpec &)(*cu_sp) = cu_file_spec; - // Also fix the invalid file spec which was copied from the - // compile unit. - cu_sp->GetSupportFiles().Replace(0, cu_file_spec); - } - } - - dwarf_cu->SetUserData(cu_sp.get()); - - // Figure out the compile unit index if we weren't given one - if (cu_idx == UINT32_MAX) - DebugInfo()->GetCompileUnit(dwarf_cu->GetOffset(), &cu_idx); - - m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex( - cu_idx, cu_sp); - } + std::string remapped_file; + if (module_sp->RemapSourceFile(cu_file_spec.GetPath(), + remapped_file)) + cu_file_spec.SetFile(remapped_file, FileSpec::Style::native); } + + LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF( + cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0)); + + bool is_optimized = dwarf_cu.GetIsOptimized(); + BuildCuTranslationTable(); + cu_sp = std::make_shared<CompileUnit>( + module_sp, &dwarf_cu, cu_file_spec, + *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language, + is_optimized ? eLazyBoolYes : eLazyBoolNo); + + dwarf_cu.SetUserData(cu_sp.get()); + + m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex( + dwarf_cu.GetID(), cu_sp); } } } @@ -866,23 +686,56 @@ return cu_sp; } +void SymbolFileDWARF::BuildCuTranslationTable() { + if (!m_lldb_cu_to_dwarf_unit.empty()) + return; + + DWARFDebugInfo *info = DebugInfo(); + if (!info) + return; + + if (!info->ContainsTypeUnits()) { + // We can use a 1-to-1 mapping. No need to build a translation table. + return; + } + for (uint32_t i = 0, num = info->GetNumUnits(); i < num; ++i) { + if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info->GetUnitAtIndex(i))) { + cu->SetID(m_lldb_cu_to_dwarf_unit.size()); + m_lldb_cu_to_dwarf_unit.push_back(i); + } + } +} + +llvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) { + BuildCuTranslationTable(); + if (m_lldb_cu_to_dwarf_unit.empty()) + return cu_idx; + if (cu_idx >= m_lldb_cu_to_dwarf_unit.size()) + return llvm::None; + return m_lldb_cu_to_dwarf_unit[cu_idx]; +} + uint32_t SymbolFileDWARF::GetNumCompileUnits() { DWARFDebugInfo *info = DebugInfo(); - if (info) - return info->GetNumCompileUnits(); - return 0; + if (!info) + return 0; + BuildCuTranslationTable(); + return m_lldb_cu_to_dwarf_unit.empty() ? info->GetNumUnits() + : m_lldb_cu_to_dwarf_unit.size(); } CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) { ASSERT_MODULE_LOCK(this); - CompUnitSP cu_sp; DWARFDebugInfo *info = DebugInfo(); - if (info) { - DWARFUnit *dwarf_cu = info->GetCompileUnitAtIndex(cu_idx); - if (dwarf_cu) - cu_sp = ParseCompileUnit(dwarf_cu, cu_idx); + if (!info) + return {}; + + if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) { + if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>( + info->GetUnitAtIndex(*dwarf_idx))) + return ParseCompileUnit(*dwarf_cu); } - return cu_sp; + return {}; } Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit, @@ -920,50 +773,74 @@ size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) { ASSERT_MODULE_LOCK(this); - size_t functions_added = 0; DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); - if (dwarf_cu) { - DWARFDIECollection function_dies; - const size_t num_functions = - dwarf_cu->AppendDIEsWithTag(DW_TAG_subprogram, function_dies); - size_t func_idx; - for (func_idx = 0; func_idx < num_functions; ++func_idx) { - DWARFDIE die = function_dies.GetDIEAtIndex(func_idx); - if (comp_unit.FindFunctionByUID(die.GetID()).get() == NULL) { - if (ParseFunction(comp_unit, die)) - ++functions_added; - } - } - // FixupTypes(); + if (!dwarf_cu) + return 0; + + size_t functions_added = 0; + std::vector<DWARFDIE> function_dies; + dwarf_cu->AppendDIEsWithTag(DW_TAG_subprogram, function_dies); + for (const DWARFDIE &die : function_dies) { + if (comp_unit.FindFunctionByUID(die.GetID())) + continue; + if (ParseFunction(comp_unit, die)) + ++functions_added; } + // FixupTypes(); return functions_added; } bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit, FileSpecList &support_files) { ASSERT_MODULE_LOCK(this); - DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); - if (dwarf_cu) { - const DWARFBaseDIE cu_die = dwarf_cu->GetUnitDIEOnly(); - - if (cu_die) { - FileSpec cu_comp_dir = resolveCompDir( - cu_die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr)); - const dw_offset_t stmt_list = cu_die.GetAttributeValueAsUnsigned( - DW_AT_stmt_list, DW_INVALID_OFFSET); - if (stmt_list != DW_INVALID_OFFSET) { - // All file indexes in DWARF are one based and a file of index zero is - // supposed to be the compile unit itself. - support_files.Append(comp_unit); - return DWARFDebugLine::ParseSupportFiles( - comp_unit.GetModule(), get_debug_line_data(), cu_comp_dir, - stmt_list, support_files, dwarf_cu); - } + if (DWARFUnit *unit = GetDWARFCompileUnit(&comp_unit)) { + const dw_offset_t stmt_list = unit->GetLineTableOffset(); + if (stmt_list != DW_INVALID_OFFSET) { + // All file indexes in DWARF are one based and a file of index zero is + // supposed to be the compile unit itself. + support_files.Append(comp_unit); + return DWARFDebugLine::ParseSupportFiles(comp_unit.GetModule(), + m_context.getOrLoadLineData(), + stmt_list, support_files, unit); } } return false; } +FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) { + if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) { + if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu)) + return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx); + return FileSpec(); + } + + auto &tu = llvm::cast<DWARFTypeUnit>(unit); + return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx); +} + +const FileSpecList & +SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) { + static FileSpecList empty_list; + + dw_offset_t offset = tu.GetLineTableOffset(); + if (offset == DW_INVALID_OFFSET || + offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() || + offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey()) + return empty_list; + + // Many type units can share a line table, so parse the support file list + // once, and cache it based on the offset field. + auto iter_bool = m_type_unit_support_files.try_emplace(offset); + FileSpecList &list = iter_bool.first->second; + if (iter_bool.second) { + list.Append(FileSpec()); + DWARFDebugLine::ParseSupportFiles(GetObjectFile()->GetModule(), + m_context.getOrLoadLineData(), offset, + list, &tu); + } + return list; +} + bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) { ASSERT_MODULE_LOCK(this); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); @@ -974,54 +851,63 @@ bool SymbolFileDWARF::ParseImportedModules( const lldb_private::SymbolContext &sc, - std::vector<lldb_private::ConstString> &imported_modules) { + std::vector<SourceModule> &imported_modules) { ASSERT_MODULE_LOCK(this); assert(sc.comp_unit); DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit); - if (dwarf_cu) { - if (ClangModulesDeclVendor::LanguageSupportsClangModules( - sc.comp_unit->GetLanguage())) { - UpdateExternalModuleListIfNeeded(); + if (!dwarf_cu) + return false; + if (!ClangModulesDeclVendor::LanguageSupportsClangModules( + sc.comp_unit->GetLanguage())) + return false; + UpdateExternalModuleListIfNeeded(); - if (sc.comp_unit) { - const DWARFDIE die = dwarf_cu->DIE(); + const DWARFDIE die = dwarf_cu->DIE(); + if (!die) + return false; - if (die) { - for (DWARFDIE child_die = die.GetFirstChild(); child_die; - child_die = child_die.GetSibling()) { - if (child_die.Tag() == DW_TAG_imported_declaration) { - if (DWARFDIE module_die = - child_die.GetReferencedDIE(DW_AT_import)) { - if (module_die.Tag() == DW_TAG_module) { - if (const char *name = module_die.GetAttributeValueAsString( - DW_AT_name, nullptr)) { - ConstString const_name(name); - imported_modules.push_back(const_name); - } - } - } - } - } - } - } else { - for (const auto &pair : m_external_type_modules) { - imported_modules.push_back(pair.first); - } + for (DWARFDIE child_die = die.GetFirstChild(); child_die; + child_die = child_die.GetSibling()) { + if (child_die.Tag() != DW_TAG_imported_declaration) + continue; + + DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import); + if (module_die.Tag() != DW_TAG_module) + continue; + + if (const char *name = + module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) { + SourceModule module; + module.path.push_back(ConstString(name)); + + DWARFDIE parent_die = module_die; + while ((parent_die = parent_die.GetParent())) { + if (parent_die.Tag() != DW_TAG_module) + break; + if (const char *name = + parent_die.GetAttributeValueAsString(DW_AT_name, nullptr)) + module.path.push_back(ConstString(name)); } + std::reverse(module.path.begin(), module.path.end()); + if (const char *include_path = module_die.GetAttributeValueAsString( + DW_AT_LLVM_include_path, nullptr)) + module.search_path = ConstString(include_path); + if (const char *sysroot = module_die.GetAttributeValueAsString( + DW_AT_LLVM_isysroot, nullptr)) + module.sysroot = ConstString(sysroot); + imported_modules.push_back(module); } } - return false; + return true; } struct ParseDWARFLineTableCallbackInfo { LineTable *line_table; - std::unique_ptr<LineSequence> sequence_ap; + std::unique_ptr<LineSequence> sequence_up; lldb::addr_t addr_mask; }; -//---------------------------------------------------------------------- // ParseStatementTableCallback -//---------------------------------------------------------------------- static void ParseDWARFLineTableCallback(dw_offset_t offset, const DWARFDebugLine::State &state, void *userData) { @@ -1035,26 +921,26 @@ LineTable *line_table = info->line_table; // If this is our first time here, we need to create a sequence container. - if (!info->sequence_ap.get()) { - info->sequence_ap.reset(line_table->CreateLineSequenceContainer()); - assert(info->sequence_ap.get()); + if (!info->sequence_up) { + info->sequence_up.reset(line_table->CreateLineSequenceContainer()); + assert(info->sequence_up.get()); } line_table->AppendLineEntryToSequence( - info->sequence_ap.get(), state.address & info->addr_mask, state.line, + info->sequence_up.get(), state.address & info->addr_mask, state.line, state.column, state.file, state.is_stmt, state.basic_block, state.prologue_end, state.epilogue_begin, state.end_sequence); if (state.end_sequence) { // First, put the current sequence into the line table. - line_table->InsertSequence(info->sequence_ap.get()); + line_table->InsertSequence(info->sequence_up.get()); // Then, empty it to prepare for the next sequence. - info->sequence_ap->Clear(); + info->sequence_up->Clear(); } } } bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) { ASSERT_MODULE_LOCK(this); - if (comp_unit.GetLineTable() != NULL) + if (comp_unit.GetLineTable() != nullptr) return true; DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); @@ -1065,10 +951,10 @@ dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_stmt_list, DW_INVALID_OFFSET); if (cu_line_offset != DW_INVALID_OFFSET) { - std::unique_ptr<LineTable> line_table_ap(new LineTable(&comp_unit)); - if (line_table_ap.get()) { + std::unique_ptr<LineTable> line_table_up(new LineTable(&comp_unit)); + if (line_table_up) { ParseDWARFLineTableCallbackInfo info; - info.line_table = line_table_ap.get(); + info.line_table = line_table_up.get(); /* * MIPS: @@ -1091,9 +977,9 @@ } lldb::offset_t offset = cu_line_offset; - DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset, - ParseDWARFLineTableCallback, - &info, dwarf_cu); + DWARFDebugLine::ParseStatementTable( + m_context.getOrLoadLineData(), &offset, + ParseDWARFLineTableCallback, &info, dwarf_cu); SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); if (debug_map_symfile) { // We have an object file that has a line table with addresses that @@ -1101,9 +987,9 @@ // addresses that are relative to the .o file into addresses for // the main executable. comp_unit.SetLineTable( - debug_map_symfile->LinkOSOLineTable(this, line_table_ap.get())); + debug_map_symfile->LinkOSOLineTable(this, line_table_up.get())); } else { - comp_unit.SetLineTable(line_table_ap.release()); + comp_unit.SetLineTable(line_table_up.release()); return true; } } @@ -1119,7 +1005,7 @@ if (iter != m_debug_macros_map.end()) return iter->second; - const DWARFDataExtractor &debug_macro_data = get_debug_macro_data(); + const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData(); if (debug_macro_data.GetByteSize() == 0) return DebugMacrosSP(); @@ -1128,9 +1014,9 @@ const DWARFDebugMacroHeader &header = DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset); - DWARFDebugMacroEntry::ReadMacroEntries(debug_macro_data, get_debug_str_data(), - header.OffsetIs64Bit(), offset, this, - debug_macros_sp); + DWARFDebugMacroEntry::ReadMacroEntries( + debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(), + offset, this, debug_macros_sp); return debug_macros_sp; } @@ -1171,7 +1057,7 @@ case DW_TAG_inlined_subroutine: case DW_TAG_subprogram: case DW_TAG_lexical_block: { - Block *block = NULL; + Block *block = nullptr; if (tag == DW_TAG_subprogram) { // Skip any DW_TAG_subprogram DIEs that are inside of a normal or // inlined functions. These will be parsed on their own as separate @@ -1187,8 +1073,8 @@ block = block_sp.get(); } DWARFRangeList ranges; - const char *name = NULL; - const char *mangled_name = NULL; + const char *name = nullptr; + const char *mangled_name = nullptr; int decl_file = 0; int decl_line = 0; @@ -1236,21 +1122,21 @@ block->FinalizeRanges(); if (tag != DW_TAG_subprogram && - (name != NULL || mangled_name != NULL)) { - std::unique_ptr<Declaration> decl_ap; + (name != nullptr || mangled_name != nullptr)) { + std::unique_ptr<Declaration> decl_up; if (decl_file != 0 || decl_line != 0 || decl_column != 0) - decl_ap.reset(new Declaration( + decl_up.reset(new Declaration( comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file), decl_line, decl_column)); - std::unique_ptr<Declaration> call_ap; + std::unique_ptr<Declaration> call_up; if (call_file != 0 || call_line != 0 || call_column != 0) - call_ap.reset(new Declaration( + call_up.reset(new Declaration( comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file), call_line, call_column)); - block->SetInlinedFunctionInfo(name, mangled_name, decl_ap.get(), - call_ap.get()); + block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(), + call_up.get()); } ++blocks_added; @@ -1313,7 +1199,17 @@ ast_parser->GetDeclForUIDFromDWARF(decl); } -SymbolFileDWARF *SymbolFileDWARF::GetDWARFForUID(lldb::user_id_t uid) { +user_id_t SymbolFileDWARF::GetUID(DIERef ref) { + if (GetDebugMapSymfile()) + return GetID() | ref.die_offset(); + + return user_id_t(GetDwoNum().getValueOr(0x7fffffff)) << 32 | + ref.die_offset() | + (lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63); +} + +llvm::Optional<SymbolFileDWARF::DecodedUID> +SymbolFileDWARF::DecodeUID(lldb::user_id_t uid) { // This method can be called without going through the symbol vendor so we // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); @@ -1324,28 +1220,37 @@ // references to other DWARF objects and we must be ready to receive a // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF // instance. - SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile(); - if (debug_map) - return debug_map->GetSymbolFileByOSOIndex( + if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) { + SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex( debug_map->GetOSOIndexFromUserID(uid)); - return this; + return DecodedUID{ + *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}}; + } + dw_offset_t die_offset = uid; + if (die_offset == DW_INVALID_OFFSET) + return llvm::None; + + DIERef::Section section = + uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo; + + llvm::Optional<uint32_t> dwo_num = uid >> 32 & 0x7fffffff; + if (*dwo_num == 0x7fffffff) + dwo_num = llvm::None; + + return DecodedUID{*this, {dwo_num, section, die_offset}}; } DWARFDIE -SymbolFileDWARF::GetDIEFromUID(lldb::user_id_t uid) { +SymbolFileDWARF::GetDIE(lldb::user_id_t uid) { // This method can be called without going through the symbol vendor so we // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); - // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we - // must make sure we use the correct DWARF file when resolving things. On - // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple - // SymbolFileDWARF classes, one for each .o file. We can often end up with - // references to other DWARF objects and we must be ready to receive a - // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF - // instance. - SymbolFileDWARF *dwarf = GetDWARFForUID(uid); - if (dwarf) - return dwarf->GetDIE(DIERef(uid, dwarf)); + + llvm::Optional<DecodedUID> decoded = DecodeUID(uid); + + if (decoded) + return decoded->dwarf.GetDIE(decoded->ref); + return DWARFDIE(); } @@ -1354,10 +1259,9 @@ // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling - // SymbolFileDWARF::GetDIEFromUID(). See comments inside the - // SymbolFileDWARF::GetDIEFromUID() for details. - DWARFDIE die = GetDIEFromUID(type_uid); - if (die) + // SymbolFileDWARF::GetDIE(). See comments inside the + // SymbolFileDWARF::GetDIE() for details. + if (DWARFDIE die = GetDIE(type_uid)) return die.GetDecl(); return CompilerDecl(); } @@ -1368,10 +1272,9 @@ // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling - // SymbolFileDWARF::GetDIEFromUID(). See comments inside the - // SymbolFileDWARF::GetDIEFromUID() for details. - DWARFDIE die = GetDIEFromUID(type_uid); - if (die) + // SymbolFileDWARF::GetDIE(). See comments inside the + // SymbolFileDWARF::GetDIE() for details. + if (DWARFDIE die = GetDIE(type_uid)) return die.GetDeclContext(); return CompilerDeclContext(); } @@ -1382,10 +1285,9 @@ // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling - // SymbolFileDWARF::GetDIEFromUID(). See comments inside the - // SymbolFileDWARF::GetDIEFromUID() for details. - DWARFDIE die = GetDIEFromUID(type_uid); - if (die) + // SymbolFileDWARF::GetDIE(). See comments inside the + // SymbolFileDWARF::GetDIE() for details. + if (DWARFDIE die = GetDIE(type_uid)) return die.GetContainingDeclContext(); return CompilerDeclContext(); } @@ -1395,10 +1297,9 @@ // need to lock the module. std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); // Anytime we have a lldb::user_id_t, we must get the DIE by calling - // SymbolFileDWARF::GetDIEFromUID(). See comments inside the - // SymbolFileDWARF::GetDIEFromUID() for details. - DWARFDIE type_die = GetDIEFromUID(type_uid); - if (type_die) + // SymbolFileDWARF::GetDIE(). See comments inside the + // SymbolFileDWARF::GetDIE() for details. + if (DWARFDIE type_die = GetDIE(type_uid)) return type_die.ResolveType(); else return nullptr; @@ -1408,8 +1309,7 @@ SymbolFileDWARF::GetDynamicArrayInfoForUID( lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); - DWARFDIE type_die = GetDIEFromUID(type_uid); - if (type_die) + if (DWARFDIE type_die = GetDIE(type_uid)) return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx); else return llvm::None; @@ -1454,7 +1354,7 @@ } return ResolveType(die); } - return NULL; + return nullptr; } // This function is used when SymbolFileDWARFDebugMap owns a bunch of @@ -1548,15 +1448,14 @@ } CompileUnit * -SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFUnit *dwarf_cu, - uint32_t cu_idx) { +SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) { // Check if the symbol vendor already knows about this compile unit? - if (dwarf_cu->GetUserData() == NULL) { + if (dwarf_cu.GetUserData() == nullptr) { // The symbol vendor doesn't know about this compile unit, we need to parse // and add it to the symbol vendor object. - return ParseCompileUnit(dwarf_cu, cu_idx).get(); + return ParseCompileUnit(dwarf_cu).get(); } - return (CompileUnit *)dwarf_cu->GetUserData(); + return (CompileUnit *)dwarf_cu.GetUserData(); } size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name, @@ -1569,12 +1468,13 @@ bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) { sc.Clear(false); - if (die) { + if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) { // Check if the symbol vendor already knows about this compile unit? - sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX); + sc.comp_unit = + GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU())); sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get(); - if (sc.function == NULL) + if (sc.function == nullptr) sc.function = ParseFunction(*sc.comp_unit, die); if (sc.function) { @@ -1597,6 +1497,14 @@ DWARFDIE SymbolFileDWARF::GetDIE(const DIERef &die_ref) { + if (die_ref.dwo_num()) { + return DebugInfo() + ->GetUnitAtIndex(*die_ref.dwo_num()) + ->GetDwoSymbolFile() + ->GetDIE(die_ref); + } + + DWARFDebugInfo *debug_info = DebugInfo(); if (debug_info) return debug_info->GetDIE(die_ref); @@ -1606,24 +1514,29 @@ std::unique_ptr<SymbolFileDWARFDwo> SymbolFileDWARF::GetDwoSymbolFileForCompileUnit( - DWARFUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die) { + DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) { // If we are using a dSYM file, we never want the standard DWO files since // the -gmodules support uses the same DWO machanism to specify full debug // info files for modules. if (GetDebugMapSymfile()) return nullptr; - const char *dwo_name = cu_die.GetAttributeValueAsString( - this, &dwarf_cu, DW_AT_GNU_dwo_name, nullptr); + DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit); + // Only compile units can be split into two parts. + if (!dwarf_cu) + return nullptr; + + const char *dwo_name = + cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_GNU_dwo_name, nullptr); if (!dwo_name) return nullptr; SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile(); if (dwp_symfile) { - uint64_t dwo_id = cu_die.GetAttributeValueAsUnsigned(this, &dwarf_cu, - DW_AT_GNU_dwo_id, 0); + uint64_t dwo_id = + cu_die.GetAttributeValueAsUnsigned(dwarf_cu, DW_AT_GNU_dwo_id, 0); std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile = - dwp_symfile->GetSymbolFileForDwoId(&dwarf_cu, dwo_id); + dwp_symfile->GetSymbolFileForDwoId(*dwarf_cu, dwo_id); if (dwo_symfile) return dwo_symfile; } @@ -1631,8 +1544,8 @@ FileSpec dwo_file(dwo_name); FileSystem::Instance().Resolve(dwo_file); if (dwo_file.IsRelative()) { - const char *comp_dir = cu_die.GetAttributeValueAsString( - this, &dwarf_cu, DW_AT_comp_dir, nullptr); + const char *comp_dir = + cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr); if (!comp_dir) return nullptr; @@ -1654,7 +1567,7 @@ if (dwo_obj_file == nullptr) return nullptr; - return llvm::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, &dwarf_cu); + return llvm::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, *dwarf_cu); } void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() { @@ -1666,7 +1579,7 @@ const uint32_t num_compile_units = GetNumCompileUnits(); for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { - DWARFUnit *dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx); + DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx); const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly(); if (die && !die.HasChildren()) { @@ -1708,16 +1621,14 @@ // printed. However, as one can notice in this case we don't // actually need to try to load the already loaded module // (corresponding to .dwo) so we simply skip it. - if (m_obj_file->GetFileSpec() - .GetFileNameExtension() - .GetStringRef() == ".dwo" && + if (m_obj_file->GetFileSpec().GetFileNameExtension() == ".dwo" && llvm::StringRef(m_obj_file->GetFileSpec().GetPath()) .endswith(dwo_module_spec.GetFileSpec().GetPath())) { continue; } Status error = ModuleList::GetSharedModule( - dwo_module_spec, module_sp, NULL, NULL, NULL); + dwo_module_spec, module_sp, nullptr, nullptr, nullptr); if (!module_sp) { GetObjectFile()->GetModule()->ReportWarning( "0x%8.8x: unable to locate module needed for external types: " @@ -1737,8 +1648,8 @@ } SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() { - if (!m_global_aranges_ap) { - m_global_aranges_ap.reset(new GlobalVariableMap()); + if (!m_global_aranges_up) { + m_global_aranges_up.reset(new GlobalVariableMap()); ModuleSP module_sp = GetObjectFile()->GetModule(); if (module_sp) { @@ -1763,8 +1674,9 @@ location_result.GetScalar().ULongLong(); lldb::addr_t byte_size = 1; if (var_sp->GetType()) - byte_size = var_sp->GetType()->GetByteSize(); - m_global_aranges_ap->Append(GlobalVariableMap::Entry( + byte_size = + var_sp->GetType()->GetByteSize().getValueOr(0); + m_global_aranges_up->Append(GlobalVariableMap::Entry( file_addr, byte_size, var_sp.get())); } } @@ -1774,9 +1686,9 @@ } } } - m_global_aranges_ap->Sort(); + m_global_aranges_up->Sort(); } - return *m_global_aranges_ap; + return *m_global_aranges_up; } uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr, @@ -1798,8 +1710,17 @@ DWARFDebugInfo *debug_info = DebugInfo(); if (debug_info) { - const dw_offset_t cu_offset = - debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr); + llvm::Expected<DWARFDebugAranges &> aranges = + debug_info->GetCompileUnitAranges(); + if (!aranges) { + Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); + LLDB_LOG_ERROR(log, aranges.takeError(), + "SymbolFileDWARF::ResolveSymbolContext failed to get cu " + "aranges. {0}"); + return 0; + } + + const dw_offset_t cu_offset = aranges->FindAddress(file_vm_addr); if (cu_offset == DW_INVALID_OFFSET) { // Global variables are not in the compile unit address ranges. The // only way to currently find global variables is to iterate over the @@ -1822,10 +1743,10 @@ } } else { uint32_t cu_idx = DW_INVALID_INDEX; - DWARFUnit *dwarf_cu = - debug_info->GetCompileUnit(cu_offset, &cu_idx); - if (dwarf_cu) { - sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx); + if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>( + debug_info->GetUnitAtOffset(DIERef::Section::DebugInfo, + cu_offset, &cu_idx))) { + sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); if (sc.comp_unit) { resolved |= eSymbolContextCompUnit; @@ -1837,7 +1758,7 @@ if (function_die) { sc.function = sc.comp_unit->FindFunctionByUID(function_die.GetID()).get(); - if (sc.function == NULL) + if (sc.function == nullptr) sc.function = ParseFunction(*sc.comp_unit, function_die); if (sc.function && (resolve_scope & eSymbolContextBlock)) @@ -1852,7 +1773,7 @@ force_check_line_table = true; } - if (sc.function != NULL) { + if (sc.function != nullptr) { resolved |= eSymbolContextFunction; if (resolve_scope & eSymbolContextBlock) { @@ -1871,7 +1792,7 @@ if ((resolve_scope & eSymbolContextLineEntry) || force_check_line_table) { LineTable *line_table = sc.comp_unit->GetLineTable(); - if (line_table != NULL) { + if (line_table != nullptr) { // And address that makes it into this function should be in // terms of this debug file if there is no debug map, or it // will be an address in the .o file which needs to be fixed up @@ -1895,7 +1816,7 @@ // only happen when there aren't other functions from other // compile units in these gaps. This helps keep the size of the // aranges down. - sc.comp_unit = NULL; + sc.comp_unit = nullptr; resolved &= ~eSymbolContextCompUnit; } } else { @@ -1918,110 +1839,100 @@ SymbolContextList &sc_list) { const uint32_t prev_size = sc_list.GetSize(); if (resolve_scope & eSymbolContextCompUnit) { - DWARFDebugInfo *debug_info = DebugInfo(); - if (debug_info) { - uint32_t cu_idx; - DWARFUnit *dwarf_cu = NULL; + for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus; + ++cu_idx) { + CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get(); + if (!dc_cu) + continue; - for (cu_idx = 0; - (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL; - ++cu_idx) { - CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx); - const bool full_match = (bool)file_spec.GetDirectory(); - bool file_spec_matches_cu_file_spec = - dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match); - if (check_inlines || file_spec_matches_cu_file_spec) { - SymbolContext sc(m_obj_file->GetModule()); - sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx); - if (sc.comp_unit) { - uint32_t file_idx = UINT32_MAX; + const bool full_match = (bool)file_spec.GetDirectory(); + bool file_spec_matches_cu_file_spec = + FileSpec::Equal(file_spec, *dc_cu, full_match); + if (check_inlines || file_spec_matches_cu_file_spec) { + SymbolContext sc(m_obj_file->GetModule()); + sc.comp_unit = dc_cu; + uint32_t file_idx = UINT32_MAX; - // If we are looking for inline functions only and we don't find it - // in the support files, we are done. - if (check_inlines) { + // If we are looking for inline functions only and we don't find it + // in the support files, we are done. + if (check_inlines) { + file_idx = + sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true); + if (file_idx == UINT32_MAX) + continue; + } + + if (line != 0) { + LineTable *line_table = sc.comp_unit->GetLineTable(); + + if (line_table != nullptr && line != 0) { + // We will have already looked up the file index if we are + // searching for inline entries. + if (!check_inlines) file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex( 1, file_spec, true); - if (file_idx == UINT32_MAX) - continue; - } - if (line != 0) { - LineTable *line_table = sc.comp_unit->GetLineTable(); + if (file_idx != UINT32_MAX) { + uint32_t found_line; + uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex( + 0, file_idx, line, false, &sc.line_entry); + found_line = sc.line_entry.line; - if (line_table != NULL && line != 0) { - // We will have already looked up the file index if we are - // searching for inline entries. - if (!check_inlines) - file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex( - 1, file_spec, true); + while (line_idx != UINT32_MAX) { + sc.function = nullptr; + sc.block = nullptr; + if (resolve_scope & + (eSymbolContextFunction | eSymbolContextBlock)) { + const lldb::addr_t file_vm_addr = + sc.line_entry.range.GetBaseAddress().GetFileAddress(); + if (file_vm_addr != LLDB_INVALID_ADDRESS) { + DWARFDIE function_die = + GetDWARFCompileUnit(dc_cu)->LookupAddress(file_vm_addr); + DWARFDIE block_die; + if (function_die) { + sc.function = + sc.comp_unit->FindFunctionByUID(function_die.GetID()) + .get(); + if (sc.function == nullptr) + sc.function = + ParseFunction(*sc.comp_unit, function_die); - if (file_idx != UINT32_MAX) { - uint32_t found_line; - uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex( - 0, file_idx, line, false, &sc.line_entry); - found_line = sc.line_entry.line; - - while (line_idx != UINT32_MAX) { - sc.function = NULL; - sc.block = NULL; - if (resolve_scope & - (eSymbolContextFunction | eSymbolContextBlock)) { - const lldb::addr_t file_vm_addr = - sc.line_entry.range.GetBaseAddress().GetFileAddress(); - if (file_vm_addr != LLDB_INVALID_ADDRESS) { - DWARFDIE function_die = - dwarf_cu->LookupAddress(file_vm_addr); - DWARFDIE block_die; - if (function_die) { - sc.function = - sc.comp_unit - ->FindFunctionByUID(function_die.GetID()) - .get(); - if (sc.function == NULL) - sc.function = - ParseFunction(*sc.comp_unit, function_die); - - if (sc.function && - (resolve_scope & eSymbolContextBlock)) - block_die = - function_die.LookupDeepestBlock(file_vm_addr); - } - - if (sc.function != NULL) { - Block &block = sc.function->GetBlock(true); - - if (block_die) - sc.block = block.FindBlockByID(block_die.GetID()); - else if (function_die) - sc.block = - block.FindBlockByID(function_die.GetID()); - } - } + if (sc.function && (resolve_scope & eSymbolContextBlock)) + block_die = + function_die.LookupDeepestBlock(file_vm_addr); } - sc_list.Append(sc); - line_idx = line_table->FindLineEntryIndexByFileIndex( - line_idx + 1, file_idx, found_line, true, - &sc.line_entry); + if (sc.function != nullptr) { + Block &block = sc.function->GetBlock(true); + + if (block_die) + sc.block = block.FindBlockByID(block_die.GetID()); + else if (function_die) + sc.block = block.FindBlockByID(function_die.GetID()); + } } } - } else if (file_spec_matches_cu_file_spec && !check_inlines) { - // only append the context if we aren't looking for inline call - // sites by file and line and if the file spec matches that of - // the compile unit - sc_list.Append(sc); - } - } else if (file_spec_matches_cu_file_spec && !check_inlines) { - // only append the context if we aren't looking for inline call - // sites by file and line and if the file spec matches that of - // the compile unit - sc_list.Append(sc); - } - if (!check_inlines) - break; + sc_list.Append(sc); + line_idx = line_table->FindLineEntryIndexByFileIndex( + line_idx + 1, file_idx, found_line, true, &sc.line_entry); + } + } + } else if (file_spec_matches_cu_file_spec && !check_inlines) { + // only append the context if we aren't looking for inline call + // sites by file and line and if the file spec matches that of + // the compile unit + sc_list.Append(sc); } + } else if (file_spec_matches_cu_file_spec && !check_inlines) { + // only append the context if we aren't looking for inline call + // sites by file and line and if the file spec matches that of + // the compile unit + sc_list.Append(sc); } + + if (!check_inlines) + break; } } } @@ -2066,7 +1977,7 @@ } uint32_t SymbolFileDWARF::FindGlobalVariables( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, VariableList &variables) { Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); @@ -2082,7 +1993,7 @@ return 0; DWARFDebugInfo *info = DebugInfo(); - if (info == NULL) + if (info == nullptr) return 0; // Remember how many variables are in the list before we search. @@ -2090,6 +2001,7 @@ llvm::StringRef basename; llvm::StringRef context; + bool name_is_mangled = (bool)Mangled(name); if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(), context, basename)) @@ -2122,7 +2034,10 @@ break; case DW_TAG_variable: { - sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX); + auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); + if (!dwarf_cu) + continue; + sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); if (parent_decl_ctx) { DWARFASTParser *dwarf_ast = die.GetDWARFParser(); @@ -2139,7 +2054,8 @@ &variables); while (pruned_idx < variables.GetSize()) { VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx); - if (var_sp->GetName().GetStringRef().contains(name.GetStringRef())) + if (name_is_mangled || + var_sp->GetName().GetStringRef().contains(name.GetStringRef())) ++pruned_idx; else variables.RemoveVariableAtIndex(pruned_idx); @@ -2150,8 +2066,7 @@ } break; } } else { - m_index->ReportInvalidDIEOffset(die_ref.die_offset, - name.GetStringRef()); + m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); } } } @@ -2183,7 +2098,7 @@ } DWARFDebugInfo *info = DebugInfo(); - if (info == NULL) + if (info == nullptr) return 0; // Remember how many variables are in the list before we search. @@ -2203,14 +2118,18 @@ DWARFDIE die = GetDIE(die_ref); if (die) { - sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX); + DWARFCompileUnit *dwarf_cu = + llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); + if (!dwarf_cu) + continue; + sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables); if (variables.GetSize() - original_size >= max_matches) break; } else - m_index->ReportInvalidDIEOffset(die_ref.die_offset, regex.GetText()); + m_index->ReportInvalidDIERef(die_ref, regex.GetText()); } } @@ -2236,7 +2155,7 @@ if (die.Tag() == DW_TAG_inlined_subroutine) { inlined_die = die; - while (1) { + while (true) { die = die.GetParent(); if (die) { @@ -2253,12 +2172,12 @@ if (inlined_die) { Block &function_block = sc.function->GetBlock(true); sc.block = function_block.FindBlockByID(inlined_die.GetID()); - if (sc.block == NULL) + if (sc.block == nullptr) sc.block = function_block.FindBlockByID(inlined_die.GetOffset()); - if (sc.block == NULL || !sc.block->GetStartAddress(addr)) + if (sc.block == nullptr || !sc.block->GetStartAddress(addr)) addr.Clear(); } else { - sc.block = NULL; + sc.block = nullptr; addr = sc.function->GetAddressRange().GetBaseAddress(); } @@ -2285,14 +2204,14 @@ CompilerDeclContext actual_decl_ctx = dwarf_ast->GetDeclContextContainingUIDFromDWARF(die); if (actual_decl_ctx) - return actual_decl_ctx == *decl_ctx; + return decl_ctx->IsContainedInLookup(actual_decl_ctx); } } return false; } uint32_t SymbolFileDWARF::FindFunctions( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, FunctionNameType name_type_mask, bool include_inlines, bool append, SymbolContextList &sc_list) { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); @@ -2328,10 +2247,6 @@ const uint32_t original_size = sc_list.GetSize(); - DWARFDebugInfo *info = DebugInfo(); - if (info == NULL) - return 0; - llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies; DIEArray offsets; CompilerDeclContext empty_decl_ctx; @@ -2339,7 +2254,7 @@ parent_decl_ctx = &empty_decl_ctx; std::vector<DWARFDIE> dies; - m_index->GetFunctions(name, *info, *parent_decl_ctx, name_type_mask, dies); + m_index->GetFunctions(name, *this, *parent_decl_ctx, name_type_mask, dies); for (const DWARFDIE &die: dies) { if (resolved_dies.insert(die.GetDIE()).second) ResolveFunction(die, include_inlines, sc_list); @@ -2394,7 +2309,7 @@ for (DIERef ref : offsets) { DWARFDIE die = info->GetDIE(ref); if (!die) { - m_index->ReportInvalidDIEOffset(ref.die_offset, regex.GetText()); + m_index->ReportInvalidDIERef(ref, regex.GetText()); continue; } if (resolved_dies.insert(die.GetDIE()).second) @@ -2411,10 +2326,10 @@ DWARFDebugInfo *info = DebugInfo(); uint32_t num_comp_units = 0; if (info) - num_comp_units = info->GetNumCompileUnits(); + num_comp_units = info->GetNumUnits(); for (uint32_t i = 0; i < num_comp_units; i++) { - DWARFUnit *cu = info->GetCompileUnitAtIndex(i); + DWARFUnit *cu = info->GetUnitAtIndex(i); if (cu == nullptr) continue; @@ -2423,21 +2338,15 @@ dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names); } - NameToOffsetMap::iterator iter = - m_function_scope_qualified_name_map.find(scope_qualified_name); - if (iter == m_function_scope_qualified_name_map.end()) - return; - - DIERefSetSP set_sp = (*iter).second; - std::set<DIERef>::iterator set_iter; - for (set_iter = set_sp->begin(); set_iter != set_sp->end(); set_iter++) { - DWARFDIE die = DebugInfo()->GetDIE(*set_iter); + for (lldb::user_id_t uid : + m_function_scope_qualified_name_map.lookup(scope_qualified_name)) { + DWARFDIE die = GetDIE(uid); mangled_names.push_back(ConstString(die.GetMangledName())); } } uint32_t SymbolFileDWARF::FindTypes( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeMap &types) { @@ -2452,7 +2361,7 @@ searched_symbol_files.insert(this); DWARFDebugInfo *info = DebugInfo(); - if (info == NULL) + if (info == nullptr) return 0; Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); @@ -2497,8 +2406,7 @@ break; } } else { - m_index->ReportInvalidDIEOffset(die_ref.die_offset, - name.GetStringRef()); + m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); } } const uint32_t num_matches = types.GetSize() - initial_types_size; @@ -2576,8 +2484,7 @@ ++num_matches; } } else { - m_index->ReportInvalidDIEOffset(die_ref.die_offset, - name.GetStringRef()); + m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); } } return num_matches; @@ -2586,7 +2493,7 @@ } CompilerDeclContext -SymbolFileDWARF::FindNamespace(const ConstString &name, +SymbolFileDWARF::FindNamespace(ConstString name, const CompilerDeclContext *parent_decl_ctx) { Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); @@ -2622,8 +2529,7 @@ break; } } else { - m_index->ReportInvalidDIEOffset(die_ref.die_offset, - name.GetStringRef()); + m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); } } } @@ -2646,10 +2552,14 @@ TypeSP type_sp; if (die) { Type *type_ptr = GetDIEToType().lookup(die.GetDIE()); - if (type_ptr == NULL) { - CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(die.GetCU()); - assert(lldb_cu); - SymbolContext sc(lldb_cu); + if (type_ptr == nullptr) { + SymbolContextScope *scope; + if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU())) + scope = GetCompUnitForDWARFCompUnit(*dwarf_cu); + else + scope = GetObjectFile()->GetModule().get(); + assert(scope); + SymbolContext sc(scope); const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE(); while (parent_die != nullptr) { if (parent_die->Tag() == DW_TAG_subprogram) @@ -2661,7 +2571,7 @@ !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc)) sc = sc_backup; - type_sp = ParseType(sc, die, NULL); + type_sp = ParseType(sc, die, nullptr); } else if (type_ptr != DIE_IS_BEING_PARSED) { // Grab the existing type from the master types lists type_sp = type_ptr->shared_from_this(); @@ -2723,8 +2633,8 @@ } Symbol * -SymbolFileDWARF::GetObjCClassSymbol(const ConstString &objc_class_name) { - Symbol *objc_class_symbol = NULL; +SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) { + Symbol *objc_class_symbol = nullptr; if (m_obj_file) { Symtab *symtab = m_obj_file->GetSymtab(); if (symtab) { @@ -2753,7 +2663,7 @@ DWARFDebugInfo *debug_info = DebugInfo(); const uint32_t num_compile_units = GetNumCompileUnits(); for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { - DWARFUnit *dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx); + DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx); if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) { m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; @@ -2771,7 +2681,7 @@ // This function can be used when a DIE is found that is a forward declaration // DIE and we want to try and find a type that has the complete definition. TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE( - const DWARFDIE &die, const ConstString &type_name, + const DWARFDIE &die, ConstString type_name, bool must_be_implementation) { TypeSP type_sp; @@ -2829,15 +2739,13 @@ } } } else { - m_index->ReportInvalidDIEOffset(die_ref.die_offset, - type_name.GetStringRef()); + m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef()); } } } return type_sp; } -//---------------------------------------------------------------------- // This function helps to ensure that the declaration contexts match for two // different DIEs. Often times debug information will refer to a forward // declaration of a type (the equivalent of "struct my_struct;". There will @@ -2847,14 +2755,13 @@ // type was in the same declaration context as the original DIE. This function // can efficiently compare two DIEs and will return true when the declaration // context matches, and false when they don't. -//---------------------------------------------------------------------- bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1, const DWARFDIE &die2) { if (die1 == die2) return true; - DWARFDIECollection decl_ctx_1; - DWARFDIECollection decl_ctx_2; + std::vector<DWARFDIE> decl_ctx_1; + std::vector<DWARFDIE> decl_ctx_2; // The declaration DIE stack is a stack of the declaration context DIEs all // the way back to the compile unit. If a type "T" is declared inside a class // "B", and class "B" is declared inside a class "A" and class "A" is in a @@ -2870,11 +2777,11 @@ // back to the compiler unit. // First lets grab the decl contexts for both DIEs - die1.GetDeclContextDIEs(decl_ctx_1); - die2.GetDeclContextDIEs(decl_ctx_2); + decl_ctx_1 = die1.GetDeclContextDIEs(); + decl_ctx_2 = die2.GetDeclContextDIEs(); // Make sure the context arrays have the same size, otherwise we are done - const size_t count1 = decl_ctx_1.Size(); - const size_t count2 = decl_ctx_2.Size(); + const size_t count1 = decl_ctx_1.size(); + const size_t count2 = decl_ctx_2.size(); if (count1 != count2) return false; @@ -2884,18 +2791,18 @@ DWARFDIE decl_ctx_die2; size_t i; for (i = 0; i < count1; i++) { - decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i); - decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i); + decl_ctx_die1 = decl_ctx_1[i]; + decl_ctx_die2 = decl_ctx_2[i]; if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag()) return false; } -#if defined LLDB_CONFIGURATION_DEBUG +#ifndef NDEBUG // Make sure the top item in the decl context die array is always // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then // something went wrong in the DWARFDIE::GetDeclContextDIEs() // function. - dw_tag_t cu_tag = decl_ctx_1.GetDIEAtIndex(count1 - 1).Tag(); + dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag(); UNUSED_IF_ASSERT_DISABLED(cu_tag); assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit); @@ -2903,8 +2810,8 @@ // Always skip the compile unit when comparing by only iterating up to "count // - 1". Here we compare the names as we go. for (i = 0; i < count1 - 1; i++) { - decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i); - decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i); + decl_ctx_die1 = decl_ctx_1[i]; + decl_ctx_die2 = decl_ctx_2[i]; const char *name1 = decl_ctx_die1.GetName(); const char *name2 = decl_ctx_die2.GetName(); // If the string was from a DW_FORM_strp, then the pointer will often be @@ -3039,8 +2946,7 @@ } } } else { - m_index->ReportInvalidDIEOffset(die_ref.die_offset, - type_name.GetStringRef()); + m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef()); } } } @@ -3051,42 +2957,32 @@ TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die, bool *type_is_new_ptr) { - TypeSP type_sp; + if (!die) + return {}; - if (die) { - TypeSystem *type_system = - GetTypeSystemForLanguage(die.GetCU()->GetLanguageType()); + TypeSystem *type_system = + GetTypeSystemForLanguage(die.GetCU()->GetLanguageType()); + if (!type_system) + return {}; - if (type_system) { - DWARFASTParser *dwarf_ast = type_system->GetDWARFParser(); - if (dwarf_ast) { - Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); - type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, log, type_is_new_ptr); - if (type_sp) { - TypeList *type_list = GetTypeList(); - if (type_list) - type_list->Insert(type_sp); + DWARFASTParser *dwarf_ast = type_system->GetDWARFParser(); + if (!dwarf_ast) + return {}; - if (die.Tag() == DW_TAG_subprogram) { - DIERef die_ref = die.GetDIERef(); - std::string scope_qualified_name(GetDeclContextForUID(die.GetID()) - .GetScopeQualifiedName() - .AsCString("")); - if (scope_qualified_name.size()) { - NameToOffsetMap::iterator iter = - m_function_scope_qualified_name_map.find( - scope_qualified_name); - if (iter != m_function_scope_qualified_name_map.end()) - (*iter).second->insert(die_ref); - else { - DIERefSetSP new_set(new std::set<DIERef>); - new_set->insert(die_ref); - m_function_scope_qualified_name_map.emplace( - std::make_pair(scope_qualified_name, new_set)); - } - } - } - } + Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); + TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, log, type_is_new_ptr); + if (type_sp) { + TypeList *type_list = GetTypeList(); + if (type_list) + type_list->Insert(type_sp); + + if (die.Tag() == DW_TAG_subprogram) { + std::string scope_qualified_name(GetDeclContextForUID(die.GetID()) + .GetScopeQualifiedName() + .AsCString("")); + if (scope_qualified_name.size()) { + m_function_scope_qualified_name_map[scope_qualified_name].insert( + die.GetID()); } } } @@ -3161,13 +3057,13 @@ size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) { ASSERT_MODULE_LOCK(this); - if (sc.comp_unit != NULL) { + if (sc.comp_unit != nullptr) { DWARFDebugInfo *info = DebugInfo(); - if (info == NULL) + if (info == nullptr) return 0; if (sc.function) { - DWARFDIE function_die = info->GetDIE(DIERef(sc.function->GetID(), this)); + DWARFDIE function_die = GetDIE(sc.function->GetID()); const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress( DW_AT_low_pc, LLDB_INVALID_ADDRESS); @@ -3180,20 +3076,21 @@ return num_variables; } } else if (sc.comp_unit) { - DWARFUnit *dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID()); + DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID()); - if (dwarf_cu == NULL) + if (dwarf_cu == nullptr) return 0; uint32_t vars_added = 0; VariableListSP variables(sc.comp_unit->GetVariableList(false)); - if (variables.get() == NULL) { - variables.reset(new VariableList()); + if (variables.get() == nullptr) { + variables = std::make_shared<VariableList>(); sc.comp_unit->SetVariableList(variables); DIEArray die_offsets; - m_index->GetGlobalVariables(*dwarf_cu, die_offsets); + m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(), + die_offsets); const size_t num_matches = die_offsets.size(); if (num_matches) { for (size_t i = 0; i < num_matches; ++i) { @@ -3207,7 +3104,7 @@ ++vars_added; } } else - m_index->ReportInvalidDIEOffset(die_ref.die_offset, ""); + m_index->ReportInvalidDIERef(die_ref, ""); } } } @@ -3240,12 +3137,12 @@ const size_t num_attributes = die.GetAttributes(attributes); DWARFDIE spec_die; if (num_attributes > 0) { - const char *name = NULL; - const char *mangled = NULL; + const char *name = nullptr; + const char *mangled = nullptr; Declaration decl; uint32_t i; DWARFFormValue type_die_form; - DWARFExpression location(die.GetCU()); + DWARFExpression location; bool is_external = false; bool is_artificial = false; bool location_is_const_value_data = false; @@ -3296,18 +3193,16 @@ uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart(); uint32_t block_length = form_value.Unsigned(); - location.CopyOpcodeData(module, debug_info_data, block_offset, - block_length); + location = DWARFExpression(module, debug_info_data, die.GetCU(), + block_offset, block_length); } else if (DWARFFormValue::IsDataForm(form_value.Form())) { // Retrieve the value as a data expression. - DWARFFormValue::FixedFormSizes fixed_form_sizes = - DWARFFormValue::GetFixedFormSizesForAddressSize( - attributes.CompileUnitAtIndex(i)->GetAddressByteSize(), - attributes.CompileUnitAtIndex(i)->IsDWARF64()); uint32_t data_offset = attributes.DIEOffsetAtIndex(i); - uint32_t data_length = - fixed_form_sizes.GetSize(form_value.Form()); - if (data_length == 0) { + if (auto data_length = form_value.GetFixedSize()) + location = + DWARFExpression(module, debug_info_data, die.GetCU(), + data_offset, *data_length); + else { const uint8_t *data_pointer = form_value.BlockData(); if (data_pointer) { form_value.Unsigned(); @@ -3316,29 +3211,23 @@ // create the variable const_value = form_value; } - } else - location.CopyOpcodeData(module, debug_info_data, data_offset, - data_length); + } } else { // Retrieve the value as a string expression. if (form_value.Form() == DW_FORM_strp) { - DWARFFormValue::FixedFormSizes fixed_form_sizes = - DWARFFormValue::GetFixedFormSizesForAddressSize( - attributes.CompileUnitAtIndex(i) - ->GetAddressByteSize(), - attributes.CompileUnitAtIndex(i)->IsDWARF64()); uint32_t data_offset = attributes.DIEOffsetAtIndex(i); - uint32_t data_length = - fixed_form_sizes.GetSize(form_value.Form()); - location.CopyOpcodeData(module, debug_info_data, data_offset, - data_length); + if (auto data_length = form_value.GetFixedSize()) + location = + DWARFExpression(module, debug_info_data, die.GetCU(), + data_offset, *data_length); } else { const char *str = form_value.AsCString(); uint32_t string_offset = str - (const char *)debug_info_data.GetDataStart(); uint32_t string_length = strlen(str) + 1; - location.CopyOpcodeData(module, debug_info_data, - string_offset, string_length); + location = + DWARFExpression(module, debug_info_data, die.GetCU(), + string_offset, string_length); } } } @@ -3352,7 +3241,8 @@ uint32_t block_offset = form_value.BlockData() - data.GetDataStart(); uint32_t block_length = form_value.Unsigned(); - location.CopyOpcodeData(module, data, block_offset, block_length); + location = DWARFExpression(module, data, die.GetCU(), + block_offset, block_length); } else { const DWARFDataExtractor &debug_loc_data = DebugLocData(); const dw_offset_t debug_loc_offset = form_value.Unsigned(); @@ -3360,8 +3250,8 @@ size_t loc_list_length = DWARFExpression::LocationListSize( die.GetCU(), debug_loc_data, debug_loc_offset); if (loc_list_length > 0) { - location.CopyOpcodeData(module, debug_loc_data, - debug_loc_offset, loc_list_length); + location = DWARFExpression(module, debug_loc_data, die.GetCU(), + debug_loc_offset, loc_list_length); assert(func_low_pc != LLDB_INVALID_ADDRESS); location.SetLocationListSlide( func_low_pc - @@ -3370,31 +3260,11 @@ } } break; case DW_AT_specification: - spec_die = GetDIE(DIERef(form_value)); + spec_die = form_value.Reference(); break; - case DW_AT_start_scope: { - if (form_value.Form() == DW_FORM_sec_offset) { - DWARFRangeList dwarf_scope_ranges; - const DWARFDebugRangesBase *debug_ranges = DebugRanges(); - debug_ranges->FindRanges(die.GetCU(), - form_value.Unsigned(), - dwarf_scope_ranges); - } else { - // TODO: Handle the case when DW_AT_start_scope have form - // constant. The - // dwarf spec is a bit ambiguous about what is the expected - // behavior in case the enclosing block have a non coninious - // address range and the DW_AT_start_scope entry have a form - // constant. - GetObjectFile()->GetModule()->ReportWarning( - "0x%8.8" PRIx64 - ": DW_AT_start_scope has unsupported form type (0x%x)\n", - die.GetID(), form_value.Form()); - } - - scope_ranges.Sort(); - scope_ranges.CombineConsecutiveRanges(); - } break; + case DW_AT_start_scope: + // TODO: Implement this. + break; case DW_AT_artificial: is_artificial = form_value.Boolean(); break; @@ -3425,7 +3295,7 @@ ValueType scope = eValueTypeInvalid; const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die); - SymbolContextScope *symbol_context_scope = NULL; + SymbolContextScope *symbol_context_scope = nullptr; bool has_explicit_mangled = mangled != nullptr; if (!mangled) { @@ -3471,7 +3341,7 @@ if (op_error) { StreamString strm; location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0, - NULL); + nullptr); GetObjectFile()->GetModule()->ReportError( "0x%8.8x: %s has an invalid location: %s", die.GetOffset(), die.GetTagAsCString(), strm.GetData()); @@ -3574,7 +3444,7 @@ } } - if (symbol_context_scope == NULL) { + if (symbol_context_scope == nullptr) { switch (parent_tag) { case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: @@ -3582,7 +3452,7 @@ if (sc.function) { symbol_context_scope = sc.function->GetBlock(true).FindBlockByID( sc_parent_die.GetID()); - if (symbol_context_scope == NULL) + if (symbol_context_scope == nullptr) symbol_context_scope = sc.function; } break; @@ -3595,17 +3465,17 @@ if (symbol_context_scope) { SymbolFileTypeSP type_sp( - new SymbolFileType(*this, DIERef(type_die_form).GetUID(this))); + new SymbolFileType(*this, GetUID(type_die_form.Reference()))); if (const_value.Form() && type_sp && type_sp->GetType()) - location.CopyOpcodeData(const_value.Unsigned(), - type_sp->GetType()->GetByteSize(), - die.GetCU()->GetAddressByteSize()); + location.UpdateValue(const_value.Unsigned(), + type_sp->GetType()->GetByteSize().getValueOr(0), + die.GetCU()->GetAddressByteSize()); - var_sp.reset(new Variable(die.GetID(), name, mangled, type_sp, scope, - symbol_context_scope, scope_ranges, &decl, - location, is_external, is_artificial, - is_static_member)); + var_sp = std::make_shared<Variable>( + die.GetID(), name, mangled, type_sp, scope, symbol_context_scope, + scope_ranges, &decl, location, is_external, is_artificial, + is_static_member); var_sp->SetLocationIsConstantValueData(location_is_const_value_data); } else { @@ -3644,12 +3514,11 @@ case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: case DW_TAG_lexical_block: { - if (die.GetAttributeValueAsReference( - DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset) + if (die.GetReferencedDIE(DW_AT_specification).GetOffset() == + spec_block_die_offset) return die; - if (die.GetAttributeValueAsReference(DW_AT_abstract_origin, - DW_INVALID_OFFSET) == + if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() == spec_block_die_offset) return die; } break; @@ -3694,16 +3563,16 @@ // We haven't already parsed it, lets do that now. if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) || (tag == DW_TAG_formal_parameter && sc.function)) { - if (variable_list_sp.get() == NULL) { + if (variable_list_sp.get() == nullptr) { DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die); dw_tag_t parent_tag = sc_parent_die.Tag(); switch (parent_tag) { case DW_TAG_compile_unit: case DW_TAG_partial_unit: - if (sc.comp_unit != NULL) { + if (sc.comp_unit != nullptr) { variable_list_sp = sc.comp_unit->GetVariableList(false); - if (variable_list_sp.get() == NULL) { - variable_list_sp.reset(new VariableList()); + if (variable_list_sp.get() == nullptr) { + variable_list_sp = std::make_shared<VariableList>(); } } else { GetObjectFile()->GetModule()->ReportError( @@ -3718,31 +3587,31 @@ case DW_TAG_subprogram: case DW_TAG_inlined_subroutine: case DW_TAG_lexical_block: - if (sc.function != NULL) { + if (sc.function != nullptr) { // Check to see if we already have parsed the variables for the // given scope Block *block = sc.function->GetBlock(true).FindBlockByID( sc_parent_die.GetID()); - if (block == NULL) { + if (block == nullptr) { // This must be a specification or abstract origin with a // concrete block counterpart in the current function. We need // to find the concrete block so we can correctly add the // variable to it const DWARFDIE concrete_block_die = FindBlockContainingSpecification( - DIERef(sc.function->GetID(), this), + GetDIE(sc.function->GetID()), sc_parent_die.GetOffset()); if (concrete_block_die) block = sc.function->GetBlock(true).FindBlockByID( concrete_block_die.GetID()); } - if (block != NULL) { + if (block != nullptr) { const bool can_create = false; variable_list_sp = block->GetBlockVariableList(can_create); - if (variable_list_sp.get() == NULL) { - variable_list_sp.reset(new VariableList()); + if (variable_list_sp.get() == nullptr) { + variable_list_sp = std::make_shared<VariableList>(); block->SetVariableList(variable_list_sp); } } @@ -3770,7 +3639,7 @@ } } - bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram); + bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram); if (!skip_children && parse_children && die.HasChildren()) { vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true, @@ -3833,15 +3702,13 @@ std::vector<lldb_private::CallEdge> SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) { - DWARFDIE func_die = GetDIEFromUID(func_id.GetID()); + DWARFDIE func_die = GetDIE(func_id.GetID()); if (func_die.IsValid()) return CollectCallEdges(func_die); return {}; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); } uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; } @@ -3857,7 +3724,7 @@ } SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() { - if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired()) { + if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) { lldb::ModuleSP module_sp(m_debug_map_module_wp.lock()); if (module_sp) { SymbolVendor *sym_vendor = module_sp->GetSymbolVendor(); @@ -3882,7 +3749,10 @@ module_spec.GetFileSpec() = m_obj_file->GetFileSpec(); module_spec.GetSymbolFileSpec() = FileSpec(m_obj_file->GetFileSpec().GetPath() + ".dwp"); - FileSpec dwp_filespec = Symbols::LocateExecutableSymbolFile(module_spec); + + FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths(); + FileSpec dwp_filespec = + Symbols::LocateExecutableSymbolFile(module_spec, search_paths); if (FileSystem::Instance().Exists(dwp_filespec)) { m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(), dwp_filespec);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h index bfe9744..018af47 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARF.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,9 +19,6 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/Support/Threading.h" -#include "lldb/Utility/Flags.h" - -#include "lldb/Core/RangeMap.h" #include "lldb/Core/UniqueCStringMap.h" #include "lldb/Core/dwarf.h" #include "lldb/Expression/DWARFExpression.h" @@ -30,20 +26,21 @@ #include "lldb/Symbol/SymbolContext.h" #include "lldb/Symbol/SymbolFile.h" #include "lldb/Utility/ConstString.h" +#include "lldb/Utility/Flags.h" +#include "lldb/Utility/RangeMap.h" #include "lldb/lldb-private.h" +#include "DWARFContext.h" #include "DWARFDataExtractor.h" #include "DWARFDefines.h" #include "DWARFIndex.h" #include "UniqueDWARFASTType.h" -//---------------------------------------------------------------------- // Forward Declarations for this DWARF plugin -//---------------------------------------------------------------------- class DebugMapModule; class DWARFAbbreviationDeclaration; class DWARFAbbreviationDeclarationSet; -class DWARFileUnit; +class DWARFCompileUnit; class DWARFDebugAbbrev; class DWARFDebugAranges; class DWARFDebugInfo; @@ -51,8 +48,8 @@ class DWARFDebugLine; class DWARFDebugRangesBase; class DWARFDeclContext; -class DWARFDIECollection; class DWARFFormValue; +class DWARFTypeUnit; class SymbolFileDWARFDebugMap; class SymbolFileDWARFDwo; class SymbolFileDWARFDwp; @@ -65,15 +62,11 @@ friend class SymbolFileDWARFDebugMap; friend class SymbolFileDWARFDwo; friend class DebugMapModule; - friend struct DIERef; - friend class DWARFUnit; + friend class DWARFCompileUnit; friend class DWARFDIE; friend class DWARFASTParserClang; - friend class DWARFASTParserRust; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -87,11 +80,12 @@ static lldb_private::SymbolFile * CreateInstance(lldb_private::ObjectFile *obj_file); - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ + static lldb_private::FileSpecList GetSymlinkPaths(); - SymbolFileDWARF(lldb_private::ObjectFile *ofile); + // Constructors and Destructors + + SymbolFileDWARF(lldb_private::ObjectFile *ofile, + lldb_private::SectionList *dwo_section_list); ~SymbolFileDWARF() override; @@ -99,9 +93,7 @@ void InitializeObject() override; - //------------------------------------------------------------------ // Compile Unit function calls - //------------------------------------------------------------------ uint32_t GetNumCompileUnits() override; @@ -125,7 +117,7 @@ bool ParseImportedModules( const lldb_private::SymbolContext &sc, - std::vector<lldb_private::ConstString> &imported_modules) override; + std::vector<lldb_private::SourceModule> &imported_modules) override; size_t ParseBlocksRecursive(lldb_private::Function &func) override; @@ -143,11 +135,6 @@ bool assert_not_being_parsed = true, bool resolve_function_context = false); - SymbolFileDWARF *GetDWARFForUID(lldb::user_id_t uid); - - DWARFDIE - GetDIEFromUID(lldb::user_id_t uid); - lldb_private::CompilerDecl GetDeclForUID(lldb::user_id_t uid) override; lldb_private::CompilerDeclContext @@ -170,7 +157,7 @@ lldb_private::SymbolContextList &sc_list) override; uint32_t - FindGlobalVariables(const lldb_private::ConstString &name, + FindGlobalVariables(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, lldb_private::VariableList &variables) override; @@ -180,7 +167,7 @@ lldb_private::VariableList &variables) override; uint32_t - FindFunctions(const lldb_private::ConstString &name, + FindFunctions(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, lldb::FunctionNameType name_type_mask, bool include_inlines, bool append, lldb_private::SymbolContextList &sc_list) override; @@ -194,7 +181,7 @@ std::vector<lldb_private::ConstString> &mangled_names) override; uint32_t - FindTypes(const lldb_private::ConstString &name, + FindTypes(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, @@ -213,40 +200,20 @@ GetTypeSystemForLanguage(lldb::LanguageType language) override; lldb_private::CompilerDeclContext FindNamespace( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx) override; void PreloadSymbols() override; std::recursive_mutex &GetModuleMutex() const override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; - virtual const lldb_private::DWARFDataExtractor &get_debug_abbrev_data(); - virtual const lldb_private::DWARFDataExtractor &get_debug_addr_data(); - const lldb_private::DWARFDataExtractor &get_debug_aranges_data(); - const lldb_private::DWARFDataExtractor &get_debug_frame_data(); - virtual const lldb_private::DWARFDataExtractor &get_debug_info_data(); - const lldb_private::DWARFDataExtractor &get_debug_line_data(); - const lldb_private::DWARFDataExtractor &get_debug_line_str_data(); - const lldb_private::DWARFDataExtractor &get_debug_macro_data(); const lldb_private::DWARFDataExtractor &get_debug_loc_data(); const lldb_private::DWARFDataExtractor &get_debug_loclists_data(); - const lldb_private::DWARFDataExtractor &get_debug_ranges_data(); - const lldb_private::DWARFDataExtractor &get_debug_rnglists_data(); - virtual const lldb_private::DWARFDataExtractor &get_debug_str_data(); - virtual const lldb_private::DWARFDataExtractor &get_debug_str_offsets_data(); - const lldb_private::DWARFDataExtractor &get_debug_types_data(); - const lldb_private::DWARFDataExtractor &get_apple_names_data(); - const lldb_private::DWARFDataExtractor &get_apple_types_data(); - const lldb_private::DWARFDataExtractor &get_apple_namespaces_data(); - const lldb_private::DWARFDataExtractor &get_apple_objc_data(); - const lldb_private::DWARFDataExtractor &get_gnu_debugaltlink(); DWARFDebugAbbrev *DebugAbbrev(); @@ -256,9 +223,8 @@ const DWARFDebugInfo *DebugInfo() const; - DWARFDebugRangesBase *DebugRanges(); - - const DWARFDebugRangesBase *DebugRanges() const; + DWARFDebugRangesBase *GetDebugRanges(); + DWARFDebugRangesBase *GetDebugRngLists(); const lldb_private::DWARFDataExtractor &DebugLocData(); @@ -271,8 +237,7 @@ HasForwardDeclForClangType(const lldb_private::CompilerType &compiler_type); lldb_private::CompileUnit * - GetCompUnitForDWARFCompUnit(DWARFUnit *dwarf_cu, - uint32_t cu_idx = UINT32_MAX); + GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu); virtual size_t GetObjCMethodDIEOffsets(lldb_private::ConstString class_name, DIEArray &method_die_offsets); @@ -283,8 +248,7 @@ static DWARFDIE GetParentSymbolContextDIE(const DWARFDIE &die); - virtual lldb::CompUnitSP ParseCompileUnit(DWARFUnit *dwarf_cu, - uint32_t cu_idx); + virtual lldb::CompUnitSP ParseCompileUnit(DWARFCompileUnit &dwarf_cu); virtual lldb_private::DWARFExpression::LocationListFormat GetLocationListFormat() const; @@ -301,6 +265,18 @@ virtual DWARFDIE GetDIE(const DIERef &die_ref); + DWARFDIE GetDIE(lldb::user_id_t uid); + + lldb::user_id_t GetUID(const DWARFBaseDIE &die) { + return GetUID(die.GetDIERef()); + } + + lldb::user_id_t GetUID(const llvm::Optional<DIERef> &ref) { + return ref ? GetUID(*ref) : LLDB_INVALID_UID; + } + + lldb::user_id_t GetUID(DIERef ref); + virtual std::unique_ptr<SymbolFileDWARFDwo> GetDwoSymbolFileForCompileUnit(DWARFUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die); @@ -308,7 +284,9 @@ // For regular SymbolFileDWARF instances the method returns nullptr, // for the instances of the subclass SymbolFileDWARFDwo // the method returns a pointer to the base compile unit. - virtual DWARFUnit *GetBaseCompileUnit(); + virtual DWARFCompileUnit *GetBaseCompileUnit() { return nullptr; } + + virtual llvm::Optional<uint32_t> GetDwoNum() { return llvm::None; } static bool DIEInDeclContext(const lldb_private::CompilerDeclContext *parent_decl_ctx, @@ -321,6 +299,10 @@ void DumpClangAST(lldb_private::Stream &s) override; + lldb_private::DWARFContext &GetDWARFContext() { return m_context; } + + lldb_private::FileSpec GetFile(DWARFUnit &unit, size_t file_idx); + protected: typedef llvm::DenseMap<const DWARFDebugInfoEntry *, lldb_private::Type *> DIEToTypePtr; @@ -329,7 +311,8 @@ typedef llvm::DenseMap<const DWARFDebugInfoEntry *, lldb::opaque_compiler_type_t> DIEToClangType; - typedef llvm::DenseMap<lldb::opaque_compiler_type_t, DIERef> ClangTypeToDIE; + typedef llvm::DenseMap<lldb::opaque_compiler_type_t, lldb::user_id_t> + ClangTypeToDIE; struct DWARFDataSegment { llvm::once_flag m_flag; @@ -382,7 +365,7 @@ const DWARFDIE &orig_die, const lldb::addr_t func_low_pc, bool parse_siblings, bool parse_children, - lldb_private::VariableList *cc_variable_list = NULL); + lldb_private::VariableList *cc_variable_list = nullptr); bool ClassOrStructIsVirtual(const DWARFDIE &die); @@ -394,11 +377,11 @@ FindDefinitionTypeForDWARFDeclContext(const DWARFDeclContext &die_decl_ctx); virtual lldb::TypeSP FindCompleteObjCDefinitionTypeForDIE( - const DWARFDIE &die, const lldb_private::ConstString &type_name, + const DWARFDIE &die, lldb_private::ConstString type_name, bool must_be_implementation); lldb_private::Symbol * - GetObjCClassSymbol(const lldb_private::ConstString &objc_class_name); + GetObjCClassSymbol(lldb_private::ConstString objc_class_name); lldb::TypeSP GetTypeForDIE(const DWARFDIE &die, bool resolve_function_context = false); @@ -422,7 +405,7 @@ bool DIEDeclContextsMatch(const DWARFDIE &die1, const DWARFDIE &die2); bool ClassContainsSelector(const DWARFDIE &class_die, - const lldb_private::ConstString &selector); + lldb_private::ConstString selector); bool FixupAddress(lldb_private::Address &addr); @@ -452,44 +435,35 @@ return m_forward_decl_clang_type_to_die; } + void BuildCuTranslationTable(); + llvm::Optional<uint32_t> GetDWARFUnitIndex(uint32_t cu_idx); + + struct DecodedUID { + SymbolFileDWARF &dwarf; + DIERef ref; + }; + llvm::Optional<DecodedUID> DecodeUID(lldb::user_id_t uid); + SymbolFileDWARFDwp *GetDwpSymbolFile(); + const lldb_private::FileSpecList &GetTypeUnitSupportFiles(DWARFTypeUnit &tu); + lldb::ModuleWP m_debug_map_module_wp; SymbolFileDWARFDebugMap *m_debug_map_symfile; llvm::once_flag m_dwp_symfile_once_flag; std::unique_ptr<SymbolFileDWARFDwp> m_dwp_symfile; - lldb_private::DWARFDataExtractor m_dwarf_data; + lldb_private::DWARFContext m_context; - DWARFDataSegment m_data_debug_abbrev; - DWARFDataSegment m_data_debug_addr; - DWARFDataSegment m_data_debug_aranges; - DWARFDataSegment m_data_debug_frame; - DWARFDataSegment m_data_debug_info; - DWARFDataSegment m_data_debug_line; - DWARFDataSegment m_data_debug_line_str; - DWARFDataSegment m_data_debug_macro; DWARFDataSegment m_data_debug_loc; DWARFDataSegment m_data_debug_loclists; - DWARFDataSegment m_data_debug_ranges; - DWARFDataSegment m_data_debug_rnglists; - DWARFDataSegment m_data_debug_str; - DWARFDataSegment m_data_debug_str_offsets; - DWARFDataSegment m_data_debug_types; - DWARFDataSegment m_data_apple_names; - DWARFDataSegment m_data_apple_types; - DWARFDataSegment m_data_apple_namespaces; - DWARFDataSegment m_data_apple_objc; - DWARFDataSegment m_data_gnu_debugaltlink; // The unique pointer items below are generated on demand if and when someone - // accesses - // them through a non const version of this class. + // accesses them through a non const version of this class. std::unique_ptr<DWARFDebugAbbrev> m_abbr; std::unique_ptr<DWARFDebugInfo> m_info; - std::unique_ptr<DWARFDebugLine> m_line; - std::unique_ptr<GlobalVariableMap> m_global_aranges_ap; + std::unique_ptr<GlobalVariableMap> m_global_aranges_up; typedef std::unordered_map<lldb::offset_t, lldb_private::DebugMacrosSP> DebugMacrosMap; @@ -500,15 +474,19 @@ bool m_fetched_external_modules : 1; lldb_private::LazyBool m_supports_DW_AT_APPLE_objc_complete_type; - typedef std::shared_ptr<std::set<DIERef>> DIERefSetSP; - typedef std::unordered_map<std::string, DIERefSetSP> NameToOffsetMap; + typedef std::set<lldb::user_id_t> DIERefSet; + typedef llvm::StringMap<DIERefSet> NameToOffsetMap; NameToOffsetMap m_function_scope_qualified_name_map; std::unique_ptr<DWARFDebugRangesBase> m_ranges; + std::unique_ptr<DWARFDebugRangesBase> m_rnglists; UniqueDWARFASTTypeMap m_unique_ast_type_map; DIEToTypePtr m_die_to_type; DIEToVariableSP m_die_to_variable_sp; DIEToClangType m_forward_decl_die_to_clang_type; ClangTypeToDIE m_forward_decl_clang_type_to_die; + llvm::DenseMap<dw_offset_t, lldb_private::FileSpecList> + m_type_unit_support_files; + std::vector<uint32_t> m_lldb_cu_to_dwarf_unit; }; #endif // SymbolFileDWARF_SymbolFileDWARF_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp index 2c1e641..8ec64db 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp
@@ -1,22 +1,20 @@ //===-- SymbolFileDWARFDebugMap.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SymbolFileDWARFDebugMap.h" - #include "DWARFDebugAranges.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleList.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/RangeMap.h" #include "lldb/Core/Section.h" #include "lldb/Host/FileSystem.h" +#include "lldb/Utility/RangeMap.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Timer.h" @@ -36,6 +34,8 @@ #include "LogChannelDWARF.h" #include "SymbolFileDWARF.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -60,13 +60,11 @@ return file_range_map; Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_MAP)); - if (log) { - ConstString object_name(oso_module->GetObjectName()); + if (log) log->Printf( "%p: SymbolFileDWARFDebugMap::CompileUnitInfo::GetFileRangeMap ('%s')", static_cast<void *>(this), oso_module->GetSpecificationDescription().c_str()); - } std::vector<SymbolFileDWARFDebugMap::CompileUnitInfo *> cu_infos; if (exe_symfile->GetCompUnitInfosForModule(oso_module, cu_infos)) { @@ -177,10 +175,10 @@ SymbolVendor * GetSymbolVendor(bool can_create = true, - lldb_private::Stream *feedback_strm = NULL) override { + lldb_private::Stream *feedback_strm = nullptr) override { // Scope for locker - if (m_symfile_ap.get() || !can_create) - return m_symfile_ap.get(); + if (m_symfile_up.get() || !can_create) + return m_symfile_up.get(); ModuleSP exe_module_sp(m_exe_module_wp.lock()); if (exe_module_sp) { @@ -199,7 +197,7 @@ symbol_vendor->GetSymbolFile()); if (!oso_symfile) - return NULL; + return nullptr; ObjectFile *exe_objfile = exe_module_sp->GetObjectFile(); SymbolVendor *exe_sym_vendor = exe_module_sp->GetSymbolVendor(); @@ -215,7 +213,7 @@ } } } - return NULL; + return nullptr; } protected: @@ -370,12 +368,12 @@ oso_symbol->GetName().GetCString()); } } else { - if (oso_symbol == NULL) + if (oso_symbol == nullptr) m_obj_file->GetModule()->ReportError( "N_OSO symbol[%u] can't be found, please file a bug and attach " "the binary listed in this error", oso_idx); - else if (so_symbol == NULL) + else if (so_symbol == nullptr) m_obj_file->GetModule()->ReportError( "N_SO not found for N_OSO symbol[%u], please file a bug and " "attach the binary listed in this error", @@ -400,7 +398,7 @@ const uint32_t cu_count = GetNumCompileUnits(); if (oso_idx < cu_count) return GetModuleByCompUnitInfo(&m_compile_unit_infos[oso_idx]); - return NULL; + return nullptr; } Module *SymbolFileDWARFDebugMap::GetModuleByCompUnitInfo( @@ -412,7 +410,7 @@ comp_unit_info->oso_sp = pos->second; } else { ObjectFile *obj_file = GetObjectFile(); - comp_unit_info->oso_sp.reset(new OSOInfo()); + comp_unit_info->oso_sp = std::make_shared<OSOInfo>(); m_oso_map[{comp_unit_info->oso_path, comp_unit_info->oso_mod_time}] = comp_unit_info->oso_sp; const char *oso_path = comp_unit_info->oso_path.GetCString(); @@ -430,7 +428,7 @@ ") since this executable was linked, file will be ignored", oso_file.GetPath().c_str(), llvm::to_string(oso_mod_time).c_str(), llvm::to_string(comp_unit_info->oso_mod_time).c_str()); - return NULL; + return nullptr; } } else { @@ -438,7 +436,7 @@ if (!ObjectFile::SplitArchivePathWithObject(oso_path, oso_file, oso_object, must_exist)) { - return NULL; + return nullptr; } } // Always create a new module for .o files. Why? Because we use the debug @@ -456,16 +454,15 @@ .getArchName() .str() .c_str()); - comp_unit_info->oso_sp->module_sp.reset(new DebugMapModule( + comp_unit_info->oso_sp->module_sp = std::make_shared<DebugMapModule>( obj_file->GetModule(), GetCompUnitInfoIndex(comp_unit_info), oso_file, - oso_arch, oso_object ? &oso_object : NULL, 0, - oso_object ? comp_unit_info->oso_mod_time - : llvm::sys::TimePoint<>())); + oso_arch, oso_object ? &oso_object : nullptr, 0, + oso_object ? comp_unit_info->oso_mod_time : llvm::sys::TimePoint<>()); } } if (comp_unit_info->oso_sp) return comp_unit_info->oso_sp->module_sp.get(); - return NULL; + return nullptr; } bool SymbolFileDWARFDebugMap::GetFileSpecForSO(uint32_t oso_idx, @@ -483,7 +480,7 @@ Module *oso_module = GetModuleByOSOIndex(oso_idx); if (oso_module) return oso_module->GetObjectFile(); - return NULL; + return nullptr; } SymbolFileDWARF * @@ -496,7 +493,7 @@ CompileUnitInfo *comp_unit_info = GetCompUnitInfo(comp_unit); if (comp_unit_info) return GetSymbolFileByCompUnitInfo(comp_unit_info); - return NULL; + return nullptr; } ObjectFile *SymbolFileDWARFDebugMap::GetObjectFileByCompUnitInfo( @@ -504,7 +501,7 @@ Module *oso_module = GetModuleByCompUnitInfo(comp_unit_info); if (oso_module) return oso_module->GetObjectFile(); - return NULL; + return nullptr; } uint32_t SymbolFileDWARFDebugMap::GetCompUnitInfoIndex( @@ -524,7 +521,7 @@ unsigned size = m_compile_unit_infos.size(); if (oso_idx < size) return GetSymbolFileByCompUnitInfo(&m_compile_unit_infos[oso_idx]); - return NULL; + return nullptr; } SymbolFileDWARF * @@ -532,7 +529,7 @@ if (sym_file && sym_file->GetPluginName() == SymbolFileDWARF::GetPluginNameStatic()) return (SymbolFileDWARF *)sym_file; - return NULL; + return nullptr; } SymbolFileDWARF *SymbolFileDWARFDebugMap::GetSymbolFileByCompUnitInfo( @@ -543,7 +540,7 @@ if (sym_vendor) return GetSymbolFileAsSymbolFileDWARF(sym_vendor->GetSymbolFile()); } - return NULL; + return nullptr; } uint32_t SymbolFileDWARFDebugMap::CalculateAbilities() { @@ -582,9 +579,10 @@ // User zero as the ID to match the compile unit at offset zero in each // .o file since each .o file can only have one compile unit for now. lldb::user_id_t cu_id = 0; - m_compile_unit_infos[cu_idx].compile_unit_sp.reset( - new CompileUnit(m_obj_file->GetModule(), NULL, so_file_spec, cu_id, - eLanguageTypeUnknown, eLazyBoolCalculate)); + m_compile_unit_infos[cu_idx].compile_unit_sp = + std::make_shared<CompileUnit>( + m_obj_file->GetModule(), nullptr, so_file_spec, cu_id, + eLanguageTypeUnknown, eLazyBoolCalculate); if (m_compile_unit_infos[cu_idx].compile_unit_sp) { // Let our symbol vendor know about this compile unit @@ -611,7 +609,7 @@ if (comp_unit == m_compile_unit_infos[i].compile_unit_sp.get()) return &m_compile_unit_infos[i]; } - return NULL; + return nullptr; } size_t SymbolFileDWARFDebugMap::GetCompUnitInfosForModule( @@ -670,7 +668,7 @@ } bool SymbolFileDWARFDebugMap::ParseImportedModules( - const SymbolContext &sc, std::vector<ConstString> &imported_modules) { + const SymbolContext &sc, std::vector<SourceModule> &imported_modules) { SymbolFileDWARF *oso_dwarf = GetSymbolFile(sc); if (oso_dwarf) return oso_dwarf->ParseImportedModules(sc, imported_modules); @@ -708,7 +706,7 @@ SymbolFileDWARF *oso_dwarf = GetSymbolFileByOSOIndex(oso_idx); if (oso_dwarf) return oso_dwarf->ResolveTypeUID(type_uid); - return NULL; + return nullptr; } llvm::Optional<SymbolFile::ArrayInfo> @@ -752,7 +750,7 @@ sc.symbol = symtab->SymbolAtIndex(debug_map_entry->data.GetExeSymbolIndex()); - if (sc.symbol != NULL) { + if (sc.symbol != nullptr) { resolved_flags |= eSymbolContextSymbol; uint32_t oso_idx = 0; @@ -810,7 +808,7 @@ } uint32_t SymbolFileDWARFDebugMap::PrivateFindGlobalVariables( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, const std::vector<uint32_t> &indexes, // Indexes into the symbol table that match "name" uint32_t max_matches, VariableList &variables) { @@ -834,7 +832,7 @@ } uint32_t SymbolFileDWARFDebugMap::FindGlobalVariables( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, VariableList &variables) { // Remember how many variables are in the list before we search. @@ -932,7 +930,7 @@ SymbolFileDWARFDebugMap::GetCompileUnitInfoForSymbolWithIndex( uint32_t symbol_idx, uint32_t *oso_idx_ptr) { const uint32_t oso_index_count = m_compile_unit_infos.size(); - CompileUnitInfo *comp_unit_info = NULL; + CompileUnitInfo *comp_unit_info = nullptr; if (oso_index_count) { comp_unit_info = (CompileUnitInfo *)bsearch( &symbol_idx, &m_compile_unit_infos[0], m_compile_unit_infos.size(), @@ -941,7 +939,7 @@ } if (oso_idx_ptr) { - if (comp_unit_info != NULL) + if (comp_unit_info != nullptr) *oso_idx_ptr = comp_unit_info - &m_compile_unit_infos[0]; else *oso_idx_ptr = UINT32_MAX; @@ -953,7 +951,7 @@ SymbolFileDWARFDebugMap::GetCompileUnitInfoForSymbolWithID( user_id_t symbol_id, uint32_t *oso_idx_ptr) { const uint32_t oso_index_count = m_compile_unit_infos.size(); - CompileUnitInfo *comp_unit_info = NULL; + CompileUnitInfo *comp_unit_info = nullptr; if (oso_index_count) { comp_unit_info = (CompileUnitInfo *)::bsearch( &symbol_id, &m_compile_unit_infos[0], m_compile_unit_infos.size(), @@ -962,7 +960,7 @@ } if (oso_idx_ptr) { - if (comp_unit_info != NULL) + if (comp_unit_info != nullptr) *oso_idx_ptr = comp_unit_info - &m_compile_unit_infos[0]; else *oso_idx_ptr = UINT32_MAX; @@ -996,7 +994,7 @@ } uint32_t SymbolFileDWARFDebugMap::FindFunctions( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, FunctionNameType name_type_mask, bool include_inlines, bool append, SymbolContextList &sc_list) { static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); @@ -1060,7 +1058,7 @@ type_mask); uint32_t initial_size = type_list.GetSize(); - SymbolFileDWARF *oso_dwarf = NULL; + SymbolFileDWARF *oso_dwarf = nullptr; if (sc_scope) { SymbolContext sc; sc_scope->CalculateSymbolContext(&sc); @@ -1105,7 +1103,7 @@ m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo; ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool { if (skip_dwarf_oso != oso_dwarf && - oso_dwarf->Supports_DW_AT_APPLE_objc_complete_type(NULL)) { + oso_dwarf->Supports_DW_AT_APPLE_objc_complete_type(nullptr)) { m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; return true; } @@ -1116,7 +1114,7 @@ } TypeSP SymbolFileDWARFDebugMap::FindCompleteObjCDefinitionTypeForDIE( - const DWARFDIE &die, const ConstString &type_name, + const DWARFDIE &die, ConstString type_name, bool must_be_implementation) { // If we have a debug map, we will have an Objective-C symbol whose name is // the type name and whose type is eSymbolTypeObjCClass. If we can find that @@ -1124,7 +1122,7 @@ // contain the implementation definition since it will be scoped inside the // N_SO and we can then locate the SymbolFileDWARF that corresponds to that // N_SO. - SymbolFileDWARF *oso_dwarf = NULL; + SymbolFileDWARF *oso_dwarf = nullptr; TypeSP type_sp; ObjectFile *module_objfile = m_obj_file->GetModule()->GetObjectFile(); if (module_objfile) { @@ -1145,7 +1143,7 @@ if (source_file_symbol_idx != UINT32_MAX) { CompileUnitInfo *compile_unit_info = GetCompileUnitInfoForSymbolWithIndex(source_file_symbol_idx, - NULL); + nullptr); if (compile_unit_info) { oso_dwarf = GetSymbolFileByCompUnitInfo(compile_unit_info); if (oso_dwarf) { @@ -1180,7 +1178,7 @@ } uint32_t SymbolFileDWARFDebugMap::FindTypes( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeMap &types) { @@ -1212,7 +1210,7 @@ //} CompilerDeclContext SymbolFileDWARFDebugMap::FindNamespace( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const CompilerDeclContext *parent_decl_ctx) { CompilerDeclContext matching_namespace; @@ -1232,9 +1230,7 @@ }); } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString SymbolFileDWARFDebugMap::GetPluginName() { return GetPluginNameStatic(); } @@ -1272,7 +1268,7 @@ } } } - return NULL; + return nullptr; } void SymbolFileDWARFDebugMap::SetCompileUnit(SymbolFileDWARF *oso_dwarf, @@ -1418,7 +1414,7 @@ CompileUnitInfo *cu_info = GetCompileUnitInfo(oso_dwarf); if (cu_info) return line_table->LinkLineTable(cu_info->GetFileRangeMap(this)); - return NULL; + return nullptr; } size_t
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h index 176eade..afc6142 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h
@@ -1,23 +1,21 @@ //===-- SymbolFileDWARFDebugMap.h ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 SymbolFileDWARF_SymbolFileDWARFDebugMap_h_ #define SymbolFileDWARF_SymbolFileDWARFDebugMap_h_ +#include "lldb/Symbol/SymbolFile.h" +#include "lldb/Utility/RangeMap.h" +#include "llvm/Support/Chrono.h" #include <bitset> #include <map> #include <vector> -#include "lldb/Core/RangeMap.h" -#include "lldb/Symbol/SymbolFile.h" -#include "llvm/Support/Chrono.h" - #include "UniqueDWARFASTType.h" class SymbolFileDWARF; @@ -26,9 +24,7 @@ class SymbolFileDWARFDebugMap : public lldb_private::SymbolFile { public: - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -40,18 +36,14 @@ static lldb_private::SymbolFile * CreateInstance(lldb_private::ObjectFile *obj_file); - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ SymbolFileDWARFDebugMap(lldb_private::ObjectFile *ofile); ~SymbolFileDWARFDebugMap() override; uint32_t CalculateAbilities() override; void InitializeObject() override; - //------------------------------------------------------------------ // Compile Unit function calls - //------------------------------------------------------------------ uint32_t GetNumCompileUnits() override; lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override; @@ -73,7 +65,7 @@ bool ParseImportedModules( const lldb_private::SymbolContext &sc, - std::vector<lldb_private::ConstString> &imported_modules) override; + std::vector<lldb_private::SourceModule> &imported_modules) override; size_t ParseBlocksRecursive(lldb_private::Function &func) override; size_t ParseVariablesForContext(const lldb_private::SymbolContext &sc) override; @@ -100,7 +92,7 @@ lldb::SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) override; uint32_t - FindGlobalVariables(const lldb_private::ConstString &name, + FindGlobalVariables(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, lldb_private::VariableList &variables) override; @@ -108,7 +100,7 @@ uint32_t max_matches, lldb_private::VariableList &variables) override; uint32_t - FindFunctions(const lldb_private::ConstString &name, + FindFunctions(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, lldb::FunctionNameType name_type_mask, bool include_inlines, bool append, lldb_private::SymbolContextList &sc_list) override; @@ -116,13 +108,13 @@ bool include_inlines, bool append, lldb_private::SymbolContextList &sc_list) override; uint32_t - FindTypes(const lldb_private::ConstString &name, + FindTypes(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, lldb_private::TypeMap &types) override; lldb_private::CompilerDeclContext FindNamespace( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx) override; size_t GetTypes(lldb_private::SymbolContextScope *sc_scope, lldb::TypeClass type_mask, @@ -132,9 +124,7 @@ void DumpClangAST(lldb_private::Stream &s) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; @@ -143,9 +133,8 @@ enum { kHaveInitializedOSOs = (1 << 0), kNumFlags }; friend class DebugMapModule; - friend struct DIERef; friend class DWARFASTParserClang; - friend class DWARFUnit; + friend class DWARFCompileUnit; friend class SymbolFileDWARF; struct OSOInfo { lldb::ModuleSP module_sp; @@ -159,9 +148,7 @@ lldb::addr_t> FileRangeMap; - //------------------------------------------------------------------ // Class specific types - //------------------------------------------------------------------ struct CompileUnitInfo { lldb_private::FileSpec so_file; lldb_private::ConstString oso_path; @@ -184,9 +171,7 @@ const FileRangeMap &GetFileRangeMap(SymbolFileDWARFDebugMap *exe_symfile); }; - //------------------------------------------------------------------ // Protected Member Functions - //------------------------------------------------------------------ void InitOSO(); static uint32_t GetOSOIndexFromUserID(lldb::user_id_t uid) { @@ -248,7 +233,7 @@ const CompileUnitInfo *comp_unit_info); uint32_t PrivateFindGlobalVariables( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, const std::vector<uint32_t> &name_symbol_indexes, uint32_t max_matches, lldb_private::VariableList &variables); @@ -266,16 +251,14 @@ bool Supports_DW_AT_APPLE_objc_complete_type(SymbolFileDWARF *skip_dwarf_oso); lldb::TypeSP FindCompleteObjCDefinitionTypeForDIE( - const DWARFDIE &die, const lldb_private::ConstString &type_name, + const DWARFDIE &die, lldb_private::ConstString type_name, bool must_be_implementation); UniqueDWARFASTTypeMap &GetUniqueDWARFASTTypeMap() { return m_unique_ast_type_map; } - //------------------------------------------------------------------ // OSOEntry - //------------------------------------------------------------------ class OSOEntry { public: OSOEntry() @@ -304,9 +287,7 @@ typedef lldb_private::RangeDataVector<lldb::addr_t, lldb::addr_t, OSOEntry> DebugMap; - //------------------------------------------------------------------ // Member Variables - //------------------------------------------------------------------ std::bitset<kNumFlags> m_flags; std::vector<CompileUnitInfo> m_compile_unit_infos; std::vector<uint32_t> m_func_indexes; // Sorted by address @@ -318,68 +299,58 @@ lldb_private::LazyBool m_supports_DW_AT_APPLE_objc_complete_type; DebugMap m_debug_map; - //------------------------------------------------------------------ // When an object file from the debug map gets parsed in // SymbolFileDWARF, it needs to tell the debug map about the object // files addresses by calling this function once for each N_FUN, // N_GSYM and N_STSYM and after all entries in the debug map have // been matched up, FinalizeOSOFileRanges() should be called. - //------------------------------------------------------------------ bool AddOSOFileRange(CompileUnitInfo *cu_info, lldb::addr_t exe_file_addr, lldb::addr_t exe_byte_size, lldb::addr_t oso_file_addr, lldb::addr_t oso_byte_size); - //------------------------------------------------------------------ // Called after calling AddOSOFileRange() for each object file debug // map entry to finalize the info for the unlinked compile unit. - //------------------------------------------------------------------ void FinalizeOSOFileRanges(CompileUnitInfo *cu_info); - //------------------------------------------------------------------ /// Convert \a addr from a .o file address, to an executable address. /// - /// @param[in] addr + /// \param[in] addr /// A section offset address from a .o file /// - /// @return + /// \return /// Returns true if \a addr was converted to be an executable /// section/offset address, false otherwise. - //------------------------------------------------------------------ bool LinkOSOAddress(lldb_private::Address &addr); - //------------------------------------------------------------------ /// Convert a .o file "file address" to an executable "file address". /// - /// @param[in] oso_symfile + /// \param[in] oso_symfile /// The DWARF symbol file that contains \a oso_file_addr /// - /// @param[in] oso_file_addr + /// \param[in] oso_file_addr /// A .o file "file address" to convert. /// - /// @return + /// \return /// LLDB_INVALID_ADDRESS if \a oso_file_addr is not in the /// linked executable, otherwise a valid "file address" from the /// linked executable that contains the debug map. - //------------------------------------------------------------------ lldb::addr_t LinkOSOFileAddress(SymbolFileDWARF *oso_symfile, lldb::addr_t oso_file_addr); - //------------------------------------------------------------------ /// Given a line table full of lines with "file addresses" that are /// for a .o file represented by \a oso_symfile, link a new line table /// and return it. /// - /// @param[in] oso_symfile + /// \param[in] oso_symfile /// The DWARF symbol file that produced the \a line_table /// - /// @param[in] addr + /// \param[in] addr /// A section offset address from a .o file /// - /// @return + /// \return /// Returns a valid line table full of linked addresses, or NULL /// if none of the line table addresses exist in the main /// executable. - //------------------------------------------------------------------ lldb_private::LineTable * LinkOSOLineTable(SymbolFileDWARF *oso_symfile, lldb_private::LineTable *line_table);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.cpp index 7881448..c5b54b6 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.cpp
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARFDwo.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,18 +12,21 @@ #include "lldb/Expression/DWARFExpression.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/LLDBAssert.h" +#include "llvm/Support/Casting.h" -#include "DWARFUnit.h" +#include "DWARFCompileUnit.h" #include "DWARFDebugInfo.h" +#include "DWARFUnit.h" using namespace lldb; using namespace lldb_private; SymbolFileDWARFDwo::SymbolFileDWARFDwo(ObjectFileSP objfile, - DWARFUnit *dwarf_cu) - : SymbolFileDWARF(objfile.get()), m_obj_file_sp(objfile), - m_base_dwarf_cu(dwarf_cu) { - SetID(((lldb::user_id_t)dwarf_cu->GetOffset()) << 32); + DWARFCompileUnit &dwarf_cu) + : SymbolFileDWARF(objfile.get(), objfile->GetSectionList( + /*update_module_section_list*/ false)), + m_obj_file_sp(objfile), m_base_dwarf_cu(dwarf_cu) { + SetID(((lldb::user_id_t)dwarf_cu.GetID()) << 32); } void SymbolFileDWARFDwo::LoadSectionData(lldb::SectionType sect_type, @@ -34,12 +36,6 @@ if (section_list) { SectionSP section_sp(section_list->FindSectionByType(sect_type, true)); if (section_sp) { - // See if we memory mapped the DWARF segment? - if (m_dwarf_data.GetByteSize()) { - data.SetData(m_dwarf_data, section_sp->GetOffset(), - section_sp->GetFileSize()); - return; - } if (m_obj_file->ReadSectionData(section_sp.get(), data) != 0) return; @@ -52,20 +48,41 @@ } lldb::CompUnitSP -SymbolFileDWARFDwo::ParseCompileUnit(DWARFUnit *dwarf_cu, - uint32_t cu_idx) { - assert(GetCompileUnit() == dwarf_cu && "SymbolFileDWARFDwo::ParseCompileUnit " - "called with incompatible compile " - "unit"); - return GetBaseSymbolFile()->ParseCompileUnit(m_base_dwarf_cu, UINT32_MAX); +SymbolFileDWARFDwo::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) { + assert(GetCompileUnit() == &dwarf_cu && + "SymbolFileDWARFDwo::ParseCompileUnit called with incompatible " + "compile unit"); + return GetBaseSymbolFile().ParseCompileUnit(m_base_dwarf_cu); } -DWARFUnit *SymbolFileDWARFDwo::GetCompileUnit() { - // Only dwo files with 1 compile unit is supported - if (GetNumCompileUnits() == 1) - return DebugInfo()->GetCompileUnitAtIndex(0); - else +DWARFCompileUnit *SymbolFileDWARFDwo::GetCompileUnit() { + if (!m_cu) + m_cu = ComputeCompileUnit(); + return m_cu; +} + +DWARFCompileUnit *SymbolFileDWARFDwo::ComputeCompileUnit() { + DWARFDebugInfo *debug_info = DebugInfo(); + if (!debug_info) return nullptr; + + // Right now we only support dwo files with one compile unit. If we don't have + // type units, we can just check for the unit count. + if (!debug_info->ContainsTypeUnits() && debug_info->GetNumUnits() == 1) + return llvm::cast<DWARFCompileUnit>(debug_info->GetUnitAtIndex(0)); + + // Otherwise, we have to run through all units, and find the compile unit that + // way. + DWARFCompileUnit *cu = nullptr; + for (size_t i = 0; i < debug_info->GetNumUnits(); ++i) { + if (auto *candidate = + llvm::dyn_cast<DWARFCompileUnit>(debug_info->GetUnitAtIndex(i))) { + if (cu) + return nullptr; // More that one CU found. + cu = candidate; + } + } + return cu; } DWARFUnit * @@ -74,83 +91,48 @@ } SymbolFileDWARF::DIEToTypePtr &SymbolFileDWARFDwo::GetDIEToType() { - return GetBaseSymbolFile()->GetDIEToType(); + return GetBaseSymbolFile().GetDIEToType(); } SymbolFileDWARF::DIEToVariableSP &SymbolFileDWARFDwo::GetDIEToVariable() { - return GetBaseSymbolFile()->GetDIEToVariable(); + return GetBaseSymbolFile().GetDIEToVariable(); } SymbolFileDWARF::DIEToClangType & SymbolFileDWARFDwo::GetForwardDeclDieToClangType() { - return GetBaseSymbolFile()->GetForwardDeclDieToClangType(); + return GetBaseSymbolFile().GetForwardDeclDieToClangType(); } SymbolFileDWARF::ClangTypeToDIE & SymbolFileDWARFDwo::GetForwardDeclClangTypeToDie() { - return GetBaseSymbolFile()->GetForwardDeclClangTypeToDie(); + return GetBaseSymbolFile().GetForwardDeclClangTypeToDie(); } size_t SymbolFileDWARFDwo::GetObjCMethodDIEOffsets( lldb_private::ConstString class_name, DIEArray &method_die_offsets) { - return GetBaseSymbolFile()->GetObjCMethodDIEOffsets( - class_name, method_die_offsets); + return GetBaseSymbolFile().GetObjCMethodDIEOffsets(class_name, + method_die_offsets); } UniqueDWARFASTTypeMap &SymbolFileDWARFDwo::GetUniqueDWARFASTTypeMap() { - return GetBaseSymbolFile()->GetUniqueDWARFASTTypeMap(); + return GetBaseSymbolFile().GetUniqueDWARFASTTypeMap(); } lldb::TypeSP SymbolFileDWARFDwo::FindDefinitionTypeForDWARFDeclContext( const DWARFDeclContext &die_decl_ctx) { - return GetBaseSymbolFile()->FindDefinitionTypeForDWARFDeclContext( + return GetBaseSymbolFile().FindDefinitionTypeForDWARFDeclContext( die_decl_ctx); } lldb::TypeSP SymbolFileDWARFDwo::FindCompleteObjCDefinitionTypeForDIE( - const DWARFDIE &die, const lldb_private::ConstString &type_name, + const DWARFDIE &die, lldb_private::ConstString type_name, bool must_be_implementation) { - return GetBaseSymbolFile()->FindCompleteObjCDefinitionTypeForDIE( + return GetBaseSymbolFile().FindCompleteObjCDefinitionTypeForDIE( die, type_name, must_be_implementation); } -DWARFUnit *SymbolFileDWARFDwo::GetBaseCompileUnit() { - return m_base_dwarf_cu; -} - -const DWARFDataExtractor &SymbolFileDWARFDwo::get_debug_abbrev_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugAbbrevDwo, - m_data_debug_abbrev); -} - -const DWARFDataExtractor &SymbolFileDWARFDwo::get_debug_addr_data() { - // For single file split dwarf case (when we have .dwo sections in a .o), - // we do not want to use the .debug_addr section from .o file, - // but want to get one from the final executable. - // For regular split debug case, .dwo file does not contain the - // .debug_addr, so we would always fall back to such lookup anyways. - llvm::call_once(m_data_debug_addr.m_flag, [this] { - SymbolFileDWARF::LoadSectionData(eSectionTypeDWARFDebugAddr, - std::ref(m_data_debug_addr.m_data)); - }); - return m_data_debug_addr.m_data; -} - -const DWARFDataExtractor &SymbolFileDWARFDwo::get_debug_info_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugInfoDwo, m_data_debug_info); -} - -const DWARFDataExtractor &SymbolFileDWARFDwo::get_debug_str_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugStrDwo, m_data_debug_str); -} - -const DWARFDataExtractor &SymbolFileDWARFDwo::get_debug_str_offsets_data() { - return GetCachedSectionData(eSectionTypeDWARFDebugStrOffsetsDwo, - m_data_debug_str_offsets); -} - -SymbolFileDWARF *SymbolFileDWARFDwo::GetBaseSymbolFile() { - return m_base_dwarf_cu->GetSymbolFileDWARF(); +SymbolFileDWARF &SymbolFileDWARFDwo::GetBaseSymbolFile() { + return m_base_dwarf_cu.GetSymbolFileDWARF(); } DWARFExpression::LocationListFormat @@ -160,11 +142,12 @@ TypeSystem * SymbolFileDWARFDwo::GetTypeSystemForLanguage(LanguageType language) { - return GetBaseSymbolFile()->GetTypeSystemForLanguage(language); + return GetBaseSymbolFile().GetTypeSystemForLanguage(language); } DWARFDIE SymbolFileDWARFDwo::GetDIE(const DIERef &die_ref) { - lldbassert(m_base_dwarf_cu->GetOffset() == die_ref.cu_offset); - return DebugInfo()->GetDIEForDIEOffset(die_ref.die_offset); + if (*die_ref.dwo_num() == GetDwoNum()) + return DebugInfo()->GetDIE(die_ref); + return GetBaseSymbolFile().GetDIE(die_ref); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h index b9ed375..9b2f3bb 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARFDwo.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,14 +13,13 @@ class SymbolFileDWARFDwo : public SymbolFileDWARF { public: - SymbolFileDWARFDwo(lldb::ObjectFileSP objfile, DWARFUnit *dwarf_cu); + SymbolFileDWARFDwo(lldb::ObjectFileSP objfile, DWARFCompileUnit &dwarf_cu); ~SymbolFileDWARFDwo() override = default; - lldb::CompUnitSP ParseCompileUnit(DWARFUnit *dwarf_cu, - uint32_t cu_idx) override; + lldb::CompUnitSP ParseCompileUnit(DWARFCompileUnit &dwarf_cu) override; - DWARFUnit *GetCompileUnit(); + DWARFCompileUnit *GetCompileUnit(); DWARFUnit * GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) override; @@ -44,13 +42,9 @@ return nullptr; } - DWARFUnit *GetBaseCompileUnit() override; + DWARFCompileUnit *GetBaseCompileUnit() override { return &m_base_dwarf_cu; } - const lldb_private::DWARFDataExtractor &get_debug_abbrev_data() override; - const lldb_private::DWARFDataExtractor &get_debug_addr_data() override; - const lldb_private::DWARFDataExtractor &get_debug_info_data() override; - const lldb_private::DWARFDataExtractor &get_debug_str_data() override; - const lldb_private::DWARFDataExtractor &get_debug_str_offsets_data() override; + llvm::Optional<uint32_t> GetDwoNum() override { return GetID() >> 32; } protected: void LoadSectionData(lldb::SectionType sect_type, @@ -70,13 +64,16 @@ const DWARFDeclContext &die_decl_ctx) override; lldb::TypeSP FindCompleteObjCDefinitionTypeForDIE( - const DWARFDIE &die, const lldb_private::ConstString &type_name, + const DWARFDIE &die, lldb_private::ConstString type_name, bool must_be_implementation) override; - SymbolFileDWARF *GetBaseSymbolFile(); + SymbolFileDWARF &GetBaseSymbolFile(); + + DWARFCompileUnit *ComputeCompileUnit(); lldb::ObjectFileSP m_obj_file_sp; - DWARFUnit *m_base_dwarf_cu; + DWARFCompileUnit &m_base_dwarf_cu; + DWARFCompileUnit *m_cu = nullptr; }; #endif // SymbolFileDWARFDwo_SymbolFileDWARFDwo_h_
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.cpp index 403c10f..efea192 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.cpp
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARFDwoDwp.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,7 +21,7 @@ SymbolFileDWARFDwoDwp::SymbolFileDWARFDwoDwp(SymbolFileDWARFDwp *dwp_symfile, ObjectFileSP objfile, - DWARFUnit *dwarf_cu, + DWARFCompileUnit &dwarf_cu, uint64_t dwo_id) : SymbolFileDWARFDwo(objfile, dwarf_cu), m_dwp_symfile(dwp_symfile), m_dwo_id(dwo_id) {}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.h index 905ba0a..2105e1a 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwoDwp.h
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARFDwoDwp.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,7 +15,7 @@ class SymbolFileDWARFDwoDwp : public SymbolFileDWARFDwo { public: SymbolFileDWARFDwoDwp(SymbolFileDWARFDwp *dwp_symfile, - lldb::ObjectFileSP objfile, DWARFUnit *dwarf_cu, + lldb::ObjectFileSP objfile, DWARFCompileUnit &dwarf_cu, uint64_t dwo_id); protected:
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.cpp index 73226df..08e6e1c 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.cpp
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARFDwp.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -82,7 +81,7 @@ {} std::unique_ptr<SymbolFileDWARFDwo> -SymbolFileDWARFDwp::GetSymbolFileForDwoId(DWARFUnit *dwarf_cu, +SymbolFileDWARFDwp::GetSymbolFileForDwoId(DWARFCompileUnit &dwarf_cu, uint64_t dwo_id) { return std::unique_ptr<SymbolFileDWARFDwo>( new SymbolFileDWARFDwoDwp(this, m_obj_file, dwarf_cu, dwo_id));
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.h index 87f4d940..ef06b9d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwp.h
@@ -1,9 +1,8 @@ //===-- SymbolFileDWARFDwp.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,7 +24,7 @@ Create(lldb::ModuleSP module_sp, const lldb_private::FileSpec &file_spec); std::unique_ptr<SymbolFileDWARFDwo> - GetSymbolFileForDwoId(DWARFUnit *dwarf_cu, uint64_t dwo_id); + GetSymbolFileForDwoId(DWARFCompileUnit &dwarf_cu, uint64_t dwo_id); bool LoadSectionData(uint64_t dwo_id, lldb::SectionType sect_type, lldb_private::DWARFDataExtractor &data);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.cpp index dd912ae..8da7e22 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.cpp
@@ -1,9 +1,8 @@ //===-- UniqueDWARFASTType.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -40,12 +39,12 @@ case DW_TAG_namespace: { const char *parent_arg_die_name = parent_arg_die.GetName(); if (parent_arg_die_name == - NULL) // Anonymous (i.e. no-name) struct + nullptr) // Anonymous (i.e. no-name) struct { match = false; } else { const char *parent_pos_die_name = parent_pos_die.GetName(); - if (parent_pos_die_name == NULL || + if (parent_pos_die_name == nullptr || ((parent_arg_die_name != parent_pos_die_name) && strcmp(parent_arg_die_name, parent_pos_die_name))) match = false;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.h index 1e6b164..1269dba 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/UniqueDWARFASTType.h
@@ -1,9 +1,8 @@ //===-- UniqueDWARFASTType.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ class UniqueDWARFASTType { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ UniqueDWARFASTType() : m_type_sp(), m_die(), m_declaration(), m_byte_size( @@ -81,12 +78,12 @@ ~UniqueDWARFASTTypeMap() {} - void Insert(const lldb_private::ConstString &name, + void Insert(lldb_private::ConstString name, const UniqueDWARFASTType &entry) { m_collection[name.GetCString()].Append(entry); } - bool Find(const lldb_private::ConstString &name, const DWARFDIE &die, + bool Find(lldb_private::ConstString name, const DWARFDIE &die, const lldb_private::Declaration &decl, const int32_t byte_size, UniqueDWARFASTType &entry) const { const char *unique_name_cstr = name.GetCString();
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CMakeLists.txt index da2d7fe..52b431d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CMakeLists.txt
@@ -1,7 +1,9 @@ add_lldb_library(lldbPluginSymbolFileNativePDB PLUGIN + CodeViewRegisterMapping.cpp CompileUnitIndex.cpp DWARFLocationExpression.cpp PdbAstBuilder.cpp + PdbFPOProgramToDWARFExpression.cpp PdbIndex.cpp PdbSymUid.cpp PdbUtil.cpp @@ -13,7 +15,7 @@ clangLex lldbCore lldbSymbol - lldbUtility + lldbUtility LINK_COMPONENTS DebugInfoCodeView DebugInfoPDB
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.cpp new file mode 100644 index 0000000..3834165 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.cpp
@@ -0,0 +1,457 @@ +//===-- CodeViewRegisterMapping.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 "CodeViewRegisterMapping.h" + +#include "lldb/lldb-defines.h" + +#include "Plugins/Process/Utility/lldb-x86-register-enums.h" + +using namespace lldb_private; + +static const uint32_t g_code_view_to_lldb_registers_x86[] = { + LLDB_INVALID_REGNUM, // NONE + lldb_al_i386, // AL + lldb_cl_i386, // CL + lldb_dl_i386, // DL + lldb_bl_i386, // BL + lldb_ah_i386, // AH + lldb_ch_i386, // CH + lldb_dh_i386, // DH + lldb_bh_i386, // BH + lldb_ax_i386, // AX + lldb_cx_i386, // CX + lldb_dx_i386, // DX + lldb_bx_i386, // BX + lldb_sp_i386, // SP + lldb_bp_i386, // BP + lldb_si_i386, // SI + lldb_di_i386, // DI + lldb_eax_i386, // EAX + lldb_ecx_i386, // ECX + lldb_edx_i386, // EDX + lldb_ebx_i386, // EBX + lldb_esp_i386, // ESP + lldb_ebp_i386, // EBP + lldb_esi_i386, // ESI + lldb_edi_i386, // EDI + lldb_es_i386, // ES + lldb_cs_i386, // CS + lldb_ss_i386, // SS + lldb_ds_i386, // DS + lldb_fs_i386, // FS + lldb_gs_i386, // GS + LLDB_INVALID_REGNUM, // IP + LLDB_INVALID_REGNUM, // FLAGS + lldb_eip_i386, // EIP + lldb_eflags_i386, // EFLAGS + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, // TEMP + LLDB_INVALID_REGNUM, // TEMPH + LLDB_INVALID_REGNUM, // QUOTE + LLDB_INVALID_REGNUM, // PCDR3 + LLDB_INVALID_REGNUM, // PCDR4 + LLDB_INVALID_REGNUM, // PCDR5 + LLDB_INVALID_REGNUM, // PCDR6 + LLDB_INVALID_REGNUM, // PCDR7 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, // CR0 + LLDB_INVALID_REGNUM, // CR1 + LLDB_INVALID_REGNUM, // CR2 + LLDB_INVALID_REGNUM, // CR3 + LLDB_INVALID_REGNUM, // CR4 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + lldb_dr0_i386, // DR0 + lldb_dr1_i386, // DR1 + lldb_dr2_i386, // DR2 + lldb_dr3_i386, // DR3 + lldb_dr4_i386, // DR4 + lldb_dr5_i386, // DR5 + lldb_dr6_i386, // DR6 + lldb_dr7_i386, // DR7 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, // GDTR + LLDB_INVALID_REGNUM, // GDTL + LLDB_INVALID_REGNUM, // IDTR + LLDB_INVALID_REGNUM, // IDTL + LLDB_INVALID_REGNUM, // LDTR + LLDB_INVALID_REGNUM, // TR + LLDB_INVALID_REGNUM, // PSEUDO1 + LLDB_INVALID_REGNUM, // PSEUDO2 + LLDB_INVALID_REGNUM, // PSEUDO3 + LLDB_INVALID_REGNUM, // PSEUDO4 + LLDB_INVALID_REGNUM, // PSEUDO5 + LLDB_INVALID_REGNUM, // PSEUDO6 + LLDB_INVALID_REGNUM, // PSEUDO7 + LLDB_INVALID_REGNUM, // PSEUDO8 + LLDB_INVALID_REGNUM, // PSEUDO9 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + lldb_st0_i386, // ST0 + lldb_st1_i386, // ST1 + lldb_st2_i386, // ST2 + lldb_st3_i386, // ST3 + lldb_st4_i386, // ST4 + lldb_st5_i386, // ST5 + lldb_st6_i386, // ST6 + lldb_st7_i386, // ST7 + LLDB_INVALID_REGNUM, // CTRL + LLDB_INVALID_REGNUM, // STAT + LLDB_INVALID_REGNUM, // TAG + LLDB_INVALID_REGNUM, // FPIP + LLDB_INVALID_REGNUM, // FPCS + LLDB_INVALID_REGNUM, // FPDO + LLDB_INVALID_REGNUM, // FPDS + LLDB_INVALID_REGNUM, // ISEM + LLDB_INVALID_REGNUM, // FPEIP + LLDB_INVALID_REGNUM, // FPEDO + lldb_mm0_i386, // MM0 + lldb_mm1_i386, // MM1 + lldb_mm2_i386, // MM2 + lldb_mm3_i386, // MM3 + lldb_mm4_i386, // MM4 + lldb_mm5_i386, // MM5 + lldb_mm6_i386, // MM6 + lldb_mm7_i386, // MM7 + lldb_xmm0_i386, // XMM0 + lldb_xmm1_i386, // XMM1 + lldb_xmm2_i386, // XMM2 + lldb_xmm3_i386, // XMM3 + lldb_xmm4_i386, // XMM4 + lldb_xmm5_i386, // XMM5 + lldb_xmm6_i386, // XMM6 + lldb_xmm7_i386 // XMM7 +}; + +static const uint32_t g_code_view_to_lldb_registers_x86_64[] = { + LLDB_INVALID_REGNUM, // NONE + lldb_al_x86_64, // AL + lldb_cl_x86_64, // CL + lldb_dl_x86_64, // DL + lldb_bl_x86_64, // BL + lldb_ah_x86_64, // AH + lldb_ch_x86_64, // CH + lldb_dh_x86_64, // DH + lldb_bh_x86_64, // BH + lldb_ax_x86_64, // AX + lldb_cx_x86_64, // CX + lldb_dx_x86_64, // DX + lldb_bx_x86_64, // BX + lldb_sp_x86_64, // SP + lldb_bp_x86_64, // BP + lldb_si_x86_64, // SI + lldb_di_x86_64, // DI + lldb_eax_x86_64, // EAX + lldb_ecx_x86_64, // ECX + lldb_edx_x86_64, // EDX + lldb_ebx_x86_64, // EBX + lldb_esp_x86_64, // ESP + lldb_ebp_x86_64, // EBP + lldb_esi_x86_64, // ESI + lldb_edi_x86_64, // EDI + lldb_es_x86_64, // ES + lldb_cs_x86_64, // CS + lldb_ss_x86_64, // SS + lldb_ds_x86_64, // DS + lldb_fs_x86_64, // FS + lldb_gs_x86_64, // GS + LLDB_INVALID_REGNUM, // IP + LLDB_INVALID_REGNUM, // FLAGS + LLDB_INVALID_REGNUM, // EIP + LLDB_INVALID_REGNUM, // EFLAGS + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, // TEMP + LLDB_INVALID_REGNUM, // TEMPH + LLDB_INVALID_REGNUM, // QUOTE + LLDB_INVALID_REGNUM, // PCDR3 + LLDB_INVALID_REGNUM, // PCDR4 + LLDB_INVALID_REGNUM, // PCDR5 + LLDB_INVALID_REGNUM, // PCDR6 + LLDB_INVALID_REGNUM, // PCDR7 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, // CR0 + LLDB_INVALID_REGNUM, // CR1 + LLDB_INVALID_REGNUM, // CR2 + LLDB_INVALID_REGNUM, // CR3 + LLDB_INVALID_REGNUM, // CR4 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + lldb_dr0_x86_64, // DR0 + lldb_dr1_x86_64, // DR1 + lldb_dr2_x86_64, // DR2 + lldb_dr3_x86_64, // DR3 + lldb_dr4_x86_64, // DR4 + lldb_dr5_x86_64, // DR5 + lldb_dr6_x86_64, // DR6 + lldb_dr7_x86_64, // DR7 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, // GDTR + LLDB_INVALID_REGNUM, // GDTL + LLDB_INVALID_REGNUM, // IDTR + LLDB_INVALID_REGNUM, // IDTL + LLDB_INVALID_REGNUM, // LDTR + LLDB_INVALID_REGNUM, // TR + LLDB_INVALID_REGNUM, // PSEUDO1 + LLDB_INVALID_REGNUM, // PSEUDO2 + LLDB_INVALID_REGNUM, // PSEUDO3 + LLDB_INVALID_REGNUM, // PSEUDO4 + LLDB_INVALID_REGNUM, // PSEUDO5 + LLDB_INVALID_REGNUM, // PSEUDO6 + LLDB_INVALID_REGNUM, // PSEUDO7 + LLDB_INVALID_REGNUM, // PSEUDO8 + LLDB_INVALID_REGNUM, // PSEUDO9 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + lldb_st0_x86_64, // ST0 + lldb_st1_x86_64, // ST1 + lldb_st2_x86_64, // ST2 + lldb_st3_x86_64, // ST3 + lldb_st4_x86_64, // ST4 + lldb_st5_x86_64, // ST5 + lldb_st6_x86_64, // ST6 + lldb_st7_x86_64, // ST7 + LLDB_INVALID_REGNUM, // CTRL + LLDB_INVALID_REGNUM, // STAT + LLDB_INVALID_REGNUM, // TAG + LLDB_INVALID_REGNUM, // FPIP + LLDB_INVALID_REGNUM, // FPCS + LLDB_INVALID_REGNUM, // FPDO + LLDB_INVALID_REGNUM, // FPDS + LLDB_INVALID_REGNUM, // ISEM + LLDB_INVALID_REGNUM, // FPEIP + LLDB_INVALID_REGNUM, // FPEDO + lldb_mm0_x86_64, // MM0 + lldb_mm1_x86_64, // MM1 + lldb_mm2_x86_64, // MM2 + lldb_mm3_x86_64, // MM3 + lldb_mm4_x86_64, // MM4 + lldb_mm5_x86_64, // MM5 + lldb_mm6_x86_64, // MM6 + lldb_mm7_x86_64, // MM7 + lldb_xmm0_x86_64, // XMM0 + lldb_xmm1_x86_64, // XMM1 + lldb_xmm2_x86_64, // XMM2 + lldb_xmm3_x86_64, // XMM3 + lldb_xmm4_x86_64, // XMM4 + lldb_xmm5_x86_64, // XMM5 + lldb_xmm6_x86_64, // XMM6 + lldb_xmm7_x86_64, // XMM7 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, + lldb_mxcsr_x86_64, // MXCSR + LLDB_INVALID_REGNUM, // EDXEAX + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, // EMM0L + LLDB_INVALID_REGNUM, // EMM1L + LLDB_INVALID_REGNUM, // EMM2L + LLDB_INVALID_REGNUM, // EMM3L + LLDB_INVALID_REGNUM, // EMM4L + LLDB_INVALID_REGNUM, // EMM5L + LLDB_INVALID_REGNUM, // EMM6L + LLDB_INVALID_REGNUM, // EMM7L + LLDB_INVALID_REGNUM, // EMM0H + LLDB_INVALID_REGNUM, // EMM1H + LLDB_INVALID_REGNUM, // EMM2H + LLDB_INVALID_REGNUM, // EMM3H + LLDB_INVALID_REGNUM, // EMM4H + LLDB_INVALID_REGNUM, // EMM5H + LLDB_INVALID_REGNUM, // EMM6H + LLDB_INVALID_REGNUM, // EMM7H + LLDB_INVALID_REGNUM, // MM00 + LLDB_INVALID_REGNUM, // MM01 + LLDB_INVALID_REGNUM, // MM10 + LLDB_INVALID_REGNUM, // MM11 + LLDB_INVALID_REGNUM, // MM20 + LLDB_INVALID_REGNUM, // MM21 + LLDB_INVALID_REGNUM, // MM30 + LLDB_INVALID_REGNUM, // MM31 + LLDB_INVALID_REGNUM, // MM40 + LLDB_INVALID_REGNUM, // MM41 + LLDB_INVALID_REGNUM, // MM50 + LLDB_INVALID_REGNUM, // MM51 + LLDB_INVALID_REGNUM, // MM60 + LLDB_INVALID_REGNUM, // MM61 + LLDB_INVALID_REGNUM, // MM70 + LLDB_INVALID_REGNUM, // MM71 + lldb_xmm8_x86_64, // XMM8 + lldb_xmm9_x86_64, // XMM9 + lldb_xmm10_x86_64, // XMM10 + lldb_xmm11_x86_64, // XMM11 + lldb_xmm12_x86_64, // XMM12 + lldb_xmm13_x86_64, // XMM13 + lldb_xmm14_x86_64, // XMM14 + lldb_xmm15_x86_64, // XMM15 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, + lldb_sil_x86_64, // SIL + lldb_dil_x86_64, // DIL + lldb_bpl_x86_64, // BPL + lldb_spl_x86_64, // SPL + lldb_rax_x86_64, // RAX + lldb_rbx_x86_64, // RBX + lldb_rcx_x86_64, // RCX + lldb_rdx_x86_64, // RDX + lldb_rsi_x86_64, // RSI + lldb_rdi_x86_64, // RDI + lldb_rbp_x86_64, // RBP + lldb_rsp_x86_64, // RSP + lldb_r8_x86_64, // R8 + lldb_r9_x86_64, // R9 + lldb_r10_x86_64, // R10 + lldb_r11_x86_64, // R11 + lldb_r12_x86_64, // R12 + lldb_r13_x86_64, // R13 + lldb_r14_x86_64, // R14 + lldb_r15_x86_64, // R15 + lldb_r8l_x86_64, // R8B + lldb_r9l_x86_64, // R9B + lldb_r10l_x86_64, // R10B + lldb_r11l_x86_64, // R11B + lldb_r12l_x86_64, // R12B + lldb_r13l_x86_64, // R13B + lldb_r14l_x86_64, // R14B + lldb_r15l_x86_64, // R15B + lldb_r8w_x86_64, // R8W + lldb_r9w_x86_64, // R9W + lldb_r10w_x86_64, // R10W + lldb_r11w_x86_64, // R11W + lldb_r12w_x86_64, // R12W + lldb_r13w_x86_64, // R13W + lldb_r14w_x86_64, // R14W + lldb_r15w_x86_64, // R15W + lldb_r8d_x86_64, // R8D + lldb_r9d_x86_64, // R9D + lldb_r10d_x86_64, // R10D + lldb_r11d_x86_64, // R11D + lldb_r12d_x86_64, // R12D + lldb_r13d_x86_64, // R13D + lldb_r14d_x86_64, // R14D + lldb_r15d_x86_64, // R15D + lldb_ymm0_x86_64, // AMD64_YMM0 + lldb_ymm1_x86_64, // AMD64_YMM1 + lldb_ymm2_x86_64, // AMD64_YMM2 + lldb_ymm3_x86_64, // AMD64_YMM3 + lldb_ymm4_x86_64, // AMD64_YMM4 + lldb_ymm5_x86_64, // AMD64_YMM5 + lldb_ymm6_x86_64, // AMD64_YMM6 + lldb_ymm7_x86_64, // AMD64_YMM7 + lldb_ymm8_x86_64, // AMD64_YMM8 + lldb_ymm9_x86_64, // AMD64_YMM9 + lldb_ymm10_x86_64, // AMD64_YMM10 + lldb_ymm11_x86_64, // AMD64_YMM11 + lldb_ymm12_x86_64, // AMD64_YMM12 + lldb_ymm13_x86_64, // AMD64_YMM13 + lldb_ymm14_x86_64, // AMD64_YMM14 + lldb_ymm15_x86_64, // AMD64_YMM15 + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, + lldb_bnd0_x86_64, // BND0 + lldb_bnd1_x86_64, // BND1 + lldb_bnd2_x86_64 // BND2 +}; + +uint32_t lldb_private::npdb::GetLLDBRegisterNumber( + llvm::Triple::ArchType arch_type, llvm::codeview::RegisterId register_id) { + switch (arch_type) { + case llvm::Triple::x86: + if (static_cast<uint16_t>(register_id) < + sizeof(g_code_view_to_lldb_registers_x86) / + sizeof(g_code_view_to_lldb_registers_x86[0])) + return g_code_view_to_lldb_registers_x86[static_cast<uint16_t>( + register_id)]; + + switch (register_id) { + case llvm::codeview::RegisterId::MXCSR: + return lldb_mxcsr_i386; + case llvm::codeview::RegisterId::BND0: + return lldb_bnd0_i386; + case llvm::codeview::RegisterId::BND1: + return lldb_bnd1_i386; + case llvm::codeview::RegisterId::BND2: + return lldb_bnd2_i386; + default: + return LLDB_INVALID_REGNUM; + } + case llvm::Triple::x86_64: + if (static_cast<uint16_t>(register_id) < + sizeof(g_code_view_to_lldb_registers_x86_64) / + sizeof(g_code_view_to_lldb_registers_x86_64[0])) + return g_code_view_to_lldb_registers_x86_64[static_cast<uint16_t>( + register_id)]; + + return LLDB_INVALID_REGNUM; + default: + return LLDB_INVALID_REGNUM; + } +}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.h new file mode 100644 index 0000000..b1c31e0 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.h
@@ -0,0 +1,24 @@ +//===-- CodeViewRegisterMapping.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_Plugins_SymbolFile_PDB_CodeViewRegisterMapping_h_ +#define lldb_Plugins_SymbolFile_PDB_CodeViewRegisterMapping_h_ + +#include "llvm/ADT/Triple.h" +#include "llvm/DebugInfo/CodeView/CodeView.h" + +namespace lldb_private { +namespace npdb { + +uint32_t GetLLDBRegisterNumber(llvm::Triple::ArchType arch_type, + llvm::codeview::RegisterId register_id); + +} // namespace npdb +} // namespace lldb_private + +#endif
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.cpp index 67ea057..1838204 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.cpp
@@ -1,9 +1,8 @@ //===-- CompileUnitIndex.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -125,11 +124,20 @@ uint16_t stream = descriptor.getModuleStreamIndex(); std::unique_ptr<llvm::msf::MappedBlockStream> stream_data = m_index.pdb().createIndexedStream(stream); + + + std::unique_ptr<CompilandIndexItem>& cci = result.first->second; + + if (!stream_data) { + llvm::pdb::ModuleDebugStreamRef debug_stream(descriptor, nullptr); + cci = llvm::make_unique<CompilandIndexItem>(PdbCompilandId{ modi }, debug_stream, std::move(descriptor)); + return *cci; + } + llvm::pdb::ModuleDebugStreamRef debug_stream(descriptor, std::move(stream_data)); - cantFail(debug_stream.reload()); - std::unique_ptr<CompilandIndexItem> &cci = result.first->second; + cantFail(debug_stream.reload()); cci = llvm::make_unique<CompilandIndexItem>( PdbCompilandId{modi}, std::move(debug_stream), std::move(descriptor));
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.h index c965870..44a1c8c 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/CompileUnitIndex.h
@@ -1,9 +1,8 @@ //===-- CompileUnitIndex.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.cpp index 7b62530..3d8bfb0 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.cpp
@@ -1,15 +1,13 @@ //===-- DWARFLocationExpression.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "DWARFLocationExpression.h" -#include "Plugins/Process/Utility/lldb-x86-register-enums.h" #include "lldb/Core/Module.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamBuffer.h" @@ -24,6 +22,8 @@ #include "llvm/Support/Endian.h" #include "PdbUtil.h" +#include "CodeViewRegisterMapping.h" +#include "PdbFPOProgramToDWARFExpression.h" using namespace lldb; using namespace lldb_private; @@ -31,448 +31,6 @@ using namespace llvm::codeview; using namespace llvm::pdb; -static const uint32_t g_code_view_to_lldb_registers_x86[] = { - LLDB_INVALID_REGNUM, // NONE - lldb_al_i386, // AL - lldb_cl_i386, // CL - lldb_dl_i386, // DL - lldb_bl_i386, // BL - lldb_ah_i386, // AH - lldb_ch_i386, // CH - lldb_dh_i386, // DH - lldb_bh_i386, // BH - lldb_ax_i386, // AX - lldb_cx_i386, // CX - lldb_dx_i386, // DX - lldb_bx_i386, // BX - lldb_sp_i386, // SP - lldb_bp_i386, // BP - lldb_si_i386, // SI - lldb_di_i386, // DI - lldb_eax_i386, // EAX - lldb_ecx_i386, // ECX - lldb_edx_i386, // EDX - lldb_ebx_i386, // EBX - lldb_esp_i386, // ESP - lldb_ebp_i386, // EBP - lldb_esi_i386, // ESI - lldb_edi_i386, // EDI - lldb_es_i386, // ES - lldb_cs_i386, // CS - lldb_ss_i386, // SS - lldb_ds_i386, // DS - lldb_fs_i386, // FS - lldb_gs_i386, // GS - LLDB_INVALID_REGNUM, // IP - LLDB_INVALID_REGNUM, // FLAGS - lldb_eip_i386, // EIP - lldb_eflags_i386, // EFLAGS - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // TEMP - LLDB_INVALID_REGNUM, // TEMPH - LLDB_INVALID_REGNUM, // QUOTE - LLDB_INVALID_REGNUM, // PCDR3 - LLDB_INVALID_REGNUM, // PCDR4 - LLDB_INVALID_REGNUM, // PCDR5 - LLDB_INVALID_REGNUM, // PCDR6 - LLDB_INVALID_REGNUM, // PCDR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // CR0 - LLDB_INVALID_REGNUM, // CR1 - LLDB_INVALID_REGNUM, // CR2 - LLDB_INVALID_REGNUM, // CR3 - LLDB_INVALID_REGNUM, // CR4 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_dr0_i386, // DR0 - lldb_dr1_i386, // DR1 - lldb_dr2_i386, // DR2 - lldb_dr3_i386, // DR3 - lldb_dr4_i386, // DR4 - lldb_dr5_i386, // DR5 - lldb_dr6_i386, // DR6 - lldb_dr7_i386, // DR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // GDTR - LLDB_INVALID_REGNUM, // GDTL - LLDB_INVALID_REGNUM, // IDTR - LLDB_INVALID_REGNUM, // IDTL - LLDB_INVALID_REGNUM, // LDTR - LLDB_INVALID_REGNUM, // TR - LLDB_INVALID_REGNUM, // PSEUDO1 - LLDB_INVALID_REGNUM, // PSEUDO2 - LLDB_INVALID_REGNUM, // PSEUDO3 - LLDB_INVALID_REGNUM, // PSEUDO4 - LLDB_INVALID_REGNUM, // PSEUDO5 - LLDB_INVALID_REGNUM, // PSEUDO6 - LLDB_INVALID_REGNUM, // PSEUDO7 - LLDB_INVALID_REGNUM, // PSEUDO8 - LLDB_INVALID_REGNUM, // PSEUDO9 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_st0_i386, // ST0 - lldb_st1_i386, // ST1 - lldb_st2_i386, // ST2 - lldb_st3_i386, // ST3 - lldb_st4_i386, // ST4 - lldb_st5_i386, // ST5 - lldb_st6_i386, // ST6 - lldb_st7_i386, // ST7 - LLDB_INVALID_REGNUM, // CTRL - LLDB_INVALID_REGNUM, // STAT - LLDB_INVALID_REGNUM, // TAG - LLDB_INVALID_REGNUM, // FPIP - LLDB_INVALID_REGNUM, // FPCS - LLDB_INVALID_REGNUM, // FPDO - LLDB_INVALID_REGNUM, // FPDS - LLDB_INVALID_REGNUM, // ISEM - LLDB_INVALID_REGNUM, // FPEIP - LLDB_INVALID_REGNUM, // FPEDO - lldb_mm0_i386, // MM0 - lldb_mm1_i386, // MM1 - lldb_mm2_i386, // MM2 - lldb_mm3_i386, // MM3 - lldb_mm4_i386, // MM4 - lldb_mm5_i386, // MM5 - lldb_mm6_i386, // MM6 - lldb_mm7_i386, // MM7 - lldb_xmm0_i386, // XMM0 - lldb_xmm1_i386, // XMM1 - lldb_xmm2_i386, // XMM2 - lldb_xmm3_i386, // XMM3 - lldb_xmm4_i386, // XMM4 - lldb_xmm5_i386, // XMM5 - lldb_xmm6_i386, // XMM6 - lldb_xmm7_i386 // XMM7 -}; - -static const uint32_t g_code_view_to_lldb_registers_x86_64[] = { - LLDB_INVALID_REGNUM, // NONE - lldb_al_x86_64, // AL - lldb_cl_x86_64, // CL - lldb_dl_x86_64, // DL - lldb_bl_x86_64, // BL - lldb_ah_x86_64, // AH - lldb_ch_x86_64, // CH - lldb_dh_x86_64, // DH - lldb_bh_x86_64, // BH - lldb_ax_x86_64, // AX - lldb_cx_x86_64, // CX - lldb_dx_x86_64, // DX - lldb_bx_x86_64, // BX - lldb_sp_x86_64, // SP - lldb_bp_x86_64, // BP - lldb_si_x86_64, // SI - lldb_di_x86_64, // DI - lldb_eax_x86_64, // EAX - lldb_ecx_x86_64, // ECX - lldb_edx_x86_64, // EDX - lldb_ebx_x86_64, // EBX - lldb_esp_x86_64, // ESP - lldb_ebp_x86_64, // EBP - lldb_esi_x86_64, // ESI - lldb_edi_x86_64, // EDI - lldb_es_x86_64, // ES - lldb_cs_x86_64, // CS - lldb_ss_x86_64, // SS - lldb_ds_x86_64, // DS - lldb_fs_x86_64, // FS - lldb_gs_x86_64, // GS - LLDB_INVALID_REGNUM, // IP - LLDB_INVALID_REGNUM, // FLAGS - LLDB_INVALID_REGNUM, // EIP - LLDB_INVALID_REGNUM, // EFLAGS - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // TEMP - LLDB_INVALID_REGNUM, // TEMPH - LLDB_INVALID_REGNUM, // QUOTE - LLDB_INVALID_REGNUM, // PCDR3 - LLDB_INVALID_REGNUM, // PCDR4 - LLDB_INVALID_REGNUM, // PCDR5 - LLDB_INVALID_REGNUM, // PCDR6 - LLDB_INVALID_REGNUM, // PCDR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // CR0 - LLDB_INVALID_REGNUM, // CR1 - LLDB_INVALID_REGNUM, // CR2 - LLDB_INVALID_REGNUM, // CR3 - LLDB_INVALID_REGNUM, // CR4 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_dr0_x86_64, // DR0 - lldb_dr1_x86_64, // DR1 - lldb_dr2_x86_64, // DR2 - lldb_dr3_x86_64, // DR3 - lldb_dr4_x86_64, // DR4 - lldb_dr5_x86_64, // DR5 - lldb_dr6_x86_64, // DR6 - lldb_dr7_x86_64, // DR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // GDTR - LLDB_INVALID_REGNUM, // GDTL - LLDB_INVALID_REGNUM, // IDTR - LLDB_INVALID_REGNUM, // IDTL - LLDB_INVALID_REGNUM, // LDTR - LLDB_INVALID_REGNUM, // TR - LLDB_INVALID_REGNUM, // PSEUDO1 - LLDB_INVALID_REGNUM, // PSEUDO2 - LLDB_INVALID_REGNUM, // PSEUDO3 - LLDB_INVALID_REGNUM, // PSEUDO4 - LLDB_INVALID_REGNUM, // PSEUDO5 - LLDB_INVALID_REGNUM, // PSEUDO6 - LLDB_INVALID_REGNUM, // PSEUDO7 - LLDB_INVALID_REGNUM, // PSEUDO8 - LLDB_INVALID_REGNUM, // PSEUDO9 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_st0_x86_64, // ST0 - lldb_st1_x86_64, // ST1 - lldb_st2_x86_64, // ST2 - lldb_st3_x86_64, // ST3 - lldb_st4_x86_64, // ST4 - lldb_st5_x86_64, // ST5 - lldb_st6_x86_64, // ST6 - lldb_st7_x86_64, // ST7 - LLDB_INVALID_REGNUM, // CTRL - LLDB_INVALID_REGNUM, // STAT - LLDB_INVALID_REGNUM, // TAG - LLDB_INVALID_REGNUM, // FPIP - LLDB_INVALID_REGNUM, // FPCS - LLDB_INVALID_REGNUM, // FPDO - LLDB_INVALID_REGNUM, // FPDS - LLDB_INVALID_REGNUM, // ISEM - LLDB_INVALID_REGNUM, // FPEIP - LLDB_INVALID_REGNUM, // FPEDO - lldb_mm0_x86_64, // MM0 - lldb_mm1_x86_64, // MM1 - lldb_mm2_x86_64, // MM2 - lldb_mm3_x86_64, // MM3 - lldb_mm4_x86_64, // MM4 - lldb_mm5_x86_64, // MM5 - lldb_mm6_x86_64, // MM6 - lldb_mm7_x86_64, // MM7 - lldb_xmm0_x86_64, // XMM0 - lldb_xmm1_x86_64, // XMM1 - lldb_xmm2_x86_64, // XMM2 - lldb_xmm3_x86_64, // XMM3 - lldb_xmm4_x86_64, // XMM4 - lldb_xmm5_x86_64, // XMM5 - lldb_xmm6_x86_64, // XMM6 - lldb_xmm7_x86_64, // XMM7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, - lldb_mxcsr_x86_64, // MXCSR - LLDB_INVALID_REGNUM, // EDXEAX - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // EMM0L - LLDB_INVALID_REGNUM, // EMM1L - LLDB_INVALID_REGNUM, // EMM2L - LLDB_INVALID_REGNUM, // EMM3L - LLDB_INVALID_REGNUM, // EMM4L - LLDB_INVALID_REGNUM, // EMM5L - LLDB_INVALID_REGNUM, // EMM6L - LLDB_INVALID_REGNUM, // EMM7L - LLDB_INVALID_REGNUM, // EMM0H - LLDB_INVALID_REGNUM, // EMM1H - LLDB_INVALID_REGNUM, // EMM2H - LLDB_INVALID_REGNUM, // EMM3H - LLDB_INVALID_REGNUM, // EMM4H - LLDB_INVALID_REGNUM, // EMM5H - LLDB_INVALID_REGNUM, // EMM6H - LLDB_INVALID_REGNUM, // EMM7H - LLDB_INVALID_REGNUM, // MM00 - LLDB_INVALID_REGNUM, // MM01 - LLDB_INVALID_REGNUM, // MM10 - LLDB_INVALID_REGNUM, // MM11 - LLDB_INVALID_REGNUM, // MM20 - LLDB_INVALID_REGNUM, // MM21 - LLDB_INVALID_REGNUM, // MM30 - LLDB_INVALID_REGNUM, // MM31 - LLDB_INVALID_REGNUM, // MM40 - LLDB_INVALID_REGNUM, // MM41 - LLDB_INVALID_REGNUM, // MM50 - LLDB_INVALID_REGNUM, // MM51 - LLDB_INVALID_REGNUM, // MM60 - LLDB_INVALID_REGNUM, // MM61 - LLDB_INVALID_REGNUM, // MM70 - LLDB_INVALID_REGNUM, // MM71 - lldb_xmm8_x86_64, // XMM8 - lldb_xmm9_x86_64, // XMM9 - lldb_xmm10_x86_64, // XMM10 - lldb_xmm11_x86_64, // XMM11 - lldb_xmm12_x86_64, // XMM12 - lldb_xmm13_x86_64, // XMM13 - lldb_xmm14_x86_64, // XMM14 - lldb_xmm15_x86_64, // XMM15 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, - lldb_sil_x86_64, // SIL - lldb_dil_x86_64, // DIL - lldb_bpl_x86_64, // BPL - lldb_spl_x86_64, // SPL - lldb_rax_x86_64, // RAX - lldb_rbx_x86_64, // RBX - lldb_rcx_x86_64, // RCX - lldb_rdx_x86_64, // RDX - lldb_rsi_x86_64, // RSI - lldb_rdi_x86_64, // RDI - lldb_rbp_x86_64, // RBP - lldb_rsp_x86_64, // RSP - lldb_r8_x86_64, // R8 - lldb_r9_x86_64, // R9 - lldb_r10_x86_64, // R10 - lldb_r11_x86_64, // R11 - lldb_r12_x86_64, // R12 - lldb_r13_x86_64, // R13 - lldb_r14_x86_64, // R14 - lldb_r15_x86_64, // R15 - lldb_r8l_x86_64, // R8B - lldb_r9l_x86_64, // R9B - lldb_r10l_x86_64, // R10B - lldb_r11l_x86_64, // R11B - lldb_r12l_x86_64, // R12B - lldb_r13l_x86_64, // R13B - lldb_r14l_x86_64, // R14B - lldb_r15l_x86_64, // R15B - lldb_r8w_x86_64, // R8W - lldb_r9w_x86_64, // R9W - lldb_r10w_x86_64, // R10W - lldb_r11w_x86_64, // R11W - lldb_r12w_x86_64, // R12W - lldb_r13w_x86_64, // R13W - lldb_r14w_x86_64, // R14W - lldb_r15w_x86_64, // R15W - lldb_r8d_x86_64, // R8D - lldb_r9d_x86_64, // R9D - lldb_r10d_x86_64, // R10D - lldb_r11d_x86_64, // R11D - lldb_r12d_x86_64, // R12D - lldb_r13d_x86_64, // R13D - lldb_r14d_x86_64, // R14D - lldb_r15d_x86_64, // R15D - lldb_ymm0_x86_64, // AMD64_YMM0 - lldb_ymm1_x86_64, // AMD64_YMM1 - lldb_ymm2_x86_64, // AMD64_YMM2 - lldb_ymm3_x86_64, // AMD64_YMM3 - lldb_ymm4_x86_64, // AMD64_YMM4 - lldb_ymm5_x86_64, // AMD64_YMM5 - lldb_ymm6_x86_64, // AMD64_YMM6 - lldb_ymm7_x86_64, // AMD64_YMM7 - lldb_ymm8_x86_64, // AMD64_YMM8 - lldb_ymm9_x86_64, // AMD64_YMM9 - lldb_ymm10_x86_64, // AMD64_YMM10 - lldb_ymm11_x86_64, // AMD64_YMM11 - lldb_ymm12_x86_64, // AMD64_YMM12 - lldb_ymm13_x86_64, // AMD64_YMM13 - lldb_ymm14_x86_64, // AMD64_YMM14 - lldb_ymm15_x86_64, // AMD64_YMM15 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_bnd0_x86_64, // BND0 - lldb_bnd1_x86_64, // BND1 - lldb_bnd2_x86_64 // BND2 -}; - -uint32_t GetLLDBRegisterNumber(llvm::Triple::ArchType arch_type, - llvm::codeview::RegisterId register_id) { - switch (arch_type) { - case llvm::Triple::x86: - if (static_cast<uint16_t>(register_id) < - sizeof(g_code_view_to_lldb_registers_x86) / - sizeof(g_code_view_to_lldb_registers_x86[0])) - return g_code_view_to_lldb_registers_x86[static_cast<uint16_t>( - register_id)]; - - switch (register_id) { - case llvm::codeview::RegisterId::MXCSR: - return lldb_mxcsr_i386; - case llvm::codeview::RegisterId::BND0: - return lldb_bnd0_i386; - case llvm::codeview::RegisterId::BND1: - return lldb_bnd1_i386; - case llvm::codeview::RegisterId::BND2: - return lldb_bnd2_i386; - default: - return LLDB_INVALID_REGNUM; - } - case llvm::Triple::x86_64: - if (static_cast<uint16_t>(register_id) < - sizeof(g_code_view_to_lldb_registers_x86_64) / - sizeof(g_code_view_to_lldb_registers_x86_64[0])) - return g_code_view_to_lldb_registers_x86_64[static_cast<uint16_t>( - register_id)]; - - return LLDB_INVALID_REGNUM; - default: - return LLDB_INVALID_REGNUM; - } -} - uint32_t GetGenericRegisterNumber(llvm::codeview::RegisterId register_id) { if (register_id == llvm::codeview::RegisterId::VFRAME) return LLDB_REGNUM_GENERIC_FP; @@ -553,13 +111,13 @@ uint32_t address_size = architecture.GetAddressByteSize(); uint32_t byte_size = architecture.GetDataByteSize(); if (byte_order == eByteOrderInvalid || address_size == 0) - return DWARFExpression(nullptr); + return DWARFExpression(); RegisterKind register_kind = eRegisterKindDWARF; StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order); if (!writer(stream, register_kind)) - return DWARFExpression(nullptr); + return DWARFExpression(); DataBufferSP buffer = std::make_shared<DataBufferHeap>(stream.GetData(), stream.GetSize()); @@ -610,6 +168,33 @@ return MakeRegisterBasedLocationExpressionInternal(reg, offset, module); } +static bool EmitVFrameEvaluationDWARFExpression( + llvm::StringRef program, llvm::Triple::ArchType arch_type, Stream &stream) { + // VFrame value always stored in $TO pseudo-register + return TranslateFPOProgramToDWARFExpression(program, "$T0", arch_type, + stream); +} + +DWARFExpression lldb_private::npdb::MakeVFrameRelLocationExpression( + llvm::StringRef fpo_program, int32_t offset, lldb::ModuleSP module) { + return MakeLocationExpressionInternal( + module, [&](Stream &stream, RegisterKind ®ister_kind) -> bool { + const ArchSpec &architecture = module->GetArchitecture(); + + if (!EmitVFrameEvaluationDWARFExpression(fpo_program, architecture.GetMachine(), + stream)) + return false; + + stream.PutHex8(llvm::dwarf::DW_OP_consts); + stream.PutSLEB128(offset); + stream.PutHex8(llvm::dwarf::DW_OP_plus); + + register_kind = eRegisterKindLLDB; + + return true; + }); +} + DWARFExpression lldb_private::npdb::MakeGlobalLocationExpression( uint16_t section, uint32_t offset, ModuleSP module) { assert(section > 0); @@ -622,13 +207,7 @@ SectionList *section_list = module->GetSectionList(); assert(section_list); - // Section indices in PDB are 1-based, but in DWARF they are 0-based, so - // we need to subtract 1. - uint32_t section_idx = section - 1; - if (section_idx >= section_list->GetSize()) - return false; - - auto section_ptr = section_list->GetSectionAtIndex(section_idx); + auto section_ptr = section_list->FindSectionByID(section); if (!section_ptr) return false;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.h index 670e95e..c37d715 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/DWARFLocationExpression.h
@@ -1,9 +1,8 @@ //===-- DWARFLocationExpression.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,6 +30,9 @@ DWARFExpression MakeRegRelLocationExpression(llvm::codeview::RegisterId reg, int32_t offset, lldb::ModuleSP module); +DWARFExpression MakeVFrameRelLocationExpression(llvm::StringRef fpo_program, + int32_t offset, + lldb::ModuleSP module); DWARFExpression MakeGlobalLocationExpression(uint16_t section, uint32_t offset, lldb::ModuleSP module); DWARFExpression MakeConstantLocationExpression(
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp index 8917fd0..4991be8 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp
@@ -205,13 +205,17 @@ return std::move(child); } +static bool IsAnonymousNamespaceName(llvm::StringRef name) { + return name == "`anonymous namespace'" || name == "`anonymous-namespace'"; +} + PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index) : m_index(index), m_clang(GetClangASTContext(obj)) { BuildParentMap(); } -clang::DeclContext &PdbAstBuilder::GetTranslationUnitDecl() { - return *m_clang.GetTranslationUnitDecl(); +lldb_private::CompilerDeclContext PdbAstBuilder::GetTranslationUnitDecl() { + return ToCompilerDeclContext(*m_clang.GetTranslationUnitDecl()); } std::pair<clang::DeclContext *, std::string> @@ -256,7 +260,7 @@ for (llvm::ms_demangle::Node *scope : scopes) { auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope); std::string str = nii->toString(); - context = m_clang.GetUniqueNamespaceDeclaration(str.c_str(), context); + context = GetOrCreateNamespaceDecl(str.c_str(), *context); } return {context, uname}; } @@ -488,7 +492,7 @@ clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) { if (uid.kind() == PdbSymUidKind::CompilandSym) { if (uid.asCompilandSym().offset == 0) - return &GetTranslationUnitDecl(); + return FromCompilerDeclContext(GetTranslationUnitDecl()); } clang::Decl *decl = GetOrCreateDeclForUid(uid); @@ -503,7 +507,7 @@ MSVCUndecoratedNameParser parser(name); llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); - clang::DeclContext *context = &GetTranslationUnitDecl(); + auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); llvm::StringRef uname = specs.back().GetBaseName(); specs = specs.drop_back(); @@ -525,7 +529,7 @@ // If that fails, treat it as a series of namespaces. for (const MSVCUndecoratedNameSpecifier &spec : specs) { std::string ns_name = spec.GetBaseName().str(); - context = m_clang.GetUniqueNamespaceDeclaration(ns_name.c_str(), context); + context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context); } return {context, uname}; } @@ -544,7 +548,7 @@ StringView name{pub->Name.begin(), pub->Name.size()}; llvm::ms_demangle::SymbolNode *node = demangler.parse(name); if (!node) - return &GetTranslationUnitDecl(); + return FromCompilerDeclContext(GetTranslationUnitDecl()); llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{ node->Name->Components->Nodes, node->Name->Components->Count - 1}; @@ -565,10 +569,10 @@ } // It's not a type. It must be a series of namespaces. - clang::DeclContext *context = &GetTranslationUnitDecl(); + auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); while (!name_components.empty()) { std::string ns = name_components.front()->toString(); - context = m_clang.GetUniqueNamespaceDeclaration(ns.c_str(), context); + context = GetOrCreateNamespaceDecl(ns.c_str(), *context); name_components = name_components.drop_front(); } return context; @@ -593,7 +597,7 @@ PdbTypeSymId type_id = uid.asTypeSym(); auto iter = m_parent_types.find(type_id.index); if (iter == m_parent_types.end()) - return &GetTranslationUnitDecl(); + return FromCompilerDeclContext(GetTranslationUnitDecl()); return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second)); } case PdbSymUidKind::FieldListMember: @@ -631,7 +635,7 @@ default: break; } - return &GetTranslationUnitDecl(); + return FromCompilerDeclContext(GetTranslationUnitDecl()); } bool PdbAstBuilder::CompleteType(clang::QualType qt) { @@ -805,9 +809,10 @@ } clang::NamespaceDecl * -PdbAstBuilder::GetOrCreateNamespaceDecl(llvm::StringRef name, +PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name, clang::DeclContext &context) { - return m_clang.GetUniqueNamespaceDeclaration(name.str().c_str(), &context); + return m_clang.GetUniqueNamespaceDeclaration( + IsAnonymousNamespaceName(name) ? nullptr : name, &context); } clang::BlockDecl * @@ -861,7 +866,8 @@ return llvm::dyn_cast<clang::VarDecl>(decl); CVSymbol sym = m_index.ReadSymbolRecord(var_id); - return CreateVariableDecl(PdbSymUid(var_id), sym, GetTranslationUnitDecl()); + auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); + return CreateVariableDecl(PdbSymUid(var_id), sym, *context); } clang::TypedefNameDecl * @@ -933,7 +939,14 @@ if (cvt.kind() == LF_PROCEDURE) { ProcedureRecord pr; llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); - return CreateProcedureType(pr); + return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv); + } + + if (cvt.kind() == LF_MFUNCTION) { + MemberFunctionRecord mfr; + llvm::cantFail( + TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); + return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv); } return {}; @@ -1117,10 +1130,11 @@ return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType()); } -clang::QualType -PdbAstBuilder::CreateProcedureType(const ProcedureRecord &proc) { +clang::QualType PdbAstBuilder::CreateFunctionType( + TypeIndex args_type_idx, TypeIndex return_type_idx, + llvm::codeview::CallingConvention calling_convention) { TpiStream &stream = m_index.tpi(); - CVType args_cvt = stream.getType(proc.ArgumentList); + CVType args_cvt = stream.getType(args_type_idx); ArgListRecord args; llvm::cantFail( TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args)); @@ -1138,10 +1152,10 @@ arg_types.push_back(ToCompilerType(arg_type)); } - clang::QualType return_type = GetOrCreateType(proc.ReturnType); + clang::QualType return_type = GetOrCreateType(return_type_idx); llvm::Optional<clang::CallingConv> cc = - TranslateCallingConvention(proc.CallConv); + TranslateCallingConvention(calling_convention); if (!cc) return {}; @@ -1340,6 +1354,10 @@ return {&m_clang, &context}; } +clang::Decl * PdbAstBuilder::FromCompilerDecl(CompilerDecl decl) { + return static_cast<clang::Decl *>(decl.GetOpaqueDecl()); +} + clang::DeclContext * PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) { return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.h index e3c0346..67d0247 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.h
@@ -1,9 +1,8 @@ //===-- PdbAstBuilder.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -51,19 +50,15 @@ class PdbAstBuilder { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ PdbAstBuilder(ObjectFile &obj, PdbIndex &index); - clang::DeclContext &GetTranslationUnitDecl(); + lldb_private::CompilerDeclContext GetTranslationUnitDecl(); clang::Decl *GetOrCreateDeclForUid(PdbSymUid uid); clang::DeclContext *GetOrCreateDeclContextForUid(PdbSymUid uid); clang::DeclContext *GetParentDeclContext(PdbSymUid uid); - clang::NamespaceDecl *GetOrCreateNamespaceDecl(llvm::StringRef name, - clang::DeclContext &context); clang::FunctionDecl *GetOrCreateFunctionDecl(PdbCompilandSymId func_id); clang::BlockDecl *GetOrCreateBlockDecl(PdbCompilandSymId block_id); clang::VarDecl *GetOrCreateVariableDecl(PdbCompilandSymId scope_id, @@ -81,6 +76,7 @@ CompilerDecl ToCompilerDecl(clang::Decl &decl); CompilerType ToCompilerType(clang::QualType qt); CompilerDeclContext ToCompilerDeclContext(clang::DeclContext &context); + clang::Decl * FromCompilerDecl(CompilerDecl decl); clang::DeclContext *FromCompilerDeclContext(CompilerDeclContext context); ClangASTContext &clang() { return m_clang; } @@ -103,7 +99,8 @@ clang::QualType CreateEnumType(PdbTypeSymId id, const llvm::codeview::EnumRecord &record); clang::QualType - CreateProcedureType(const llvm::codeview::ProcedureRecord &proc); + CreateFunctionType(TypeIndex args_type_idx, TypeIndex return_type_idx, + llvm::codeview::CallingConvention calling_convention); clang::QualType CreateType(PdbTypeSymId type); void CreateFunctionParameters(PdbCompilandSymId func_id, @@ -116,6 +113,9 @@ clang::DeclContext * GetParentDeclContextForSymbol(const llvm::codeview::CVSymbol &sym); + clang::NamespaceDecl *GetOrCreateNamespaceDecl(const char *name, + clang::DeclContext &context); + void ParseAllNamespacesPlusChildrenOf(llvm::Optional<llvm::StringRef> parent); void ParseDeclsForSimpleContext(clang::DeclContext &context); void ParseBlockChildren(PdbCompilandSymId block_id);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.cpp new file mode 100644 index 0000000..79dd010 --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.cpp
@@ -0,0 +1,137 @@ +//===-- PdbFPOProgramToDWARFExpression.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 "PdbFPOProgramToDWARFExpression.h" +#include "CodeViewRegisterMapping.h" + +#include "lldb/Core/StreamBuffer.h" +#include "lldb/Symbol/PostfixExpression.h" +#include "lldb/Utility/LLDBAssert.h" +#include "lldb/Utility/Stream.h" +#include "llvm/ADT/DenseMap.h" + +#include "llvm/ADT/StringExtras.h" +#include "llvm/DebugInfo/CodeView/CodeView.h" +#include "llvm/DebugInfo/CodeView/EnumTables.h" + +using namespace lldb; +using namespace lldb_private; +using namespace lldb_private::postfix; + +static uint32_t ResolveLLDBRegisterNum(llvm::StringRef reg_name, llvm::Triple::ArchType arch_type) { + // lookup register name to get lldb register number + llvm::codeview::CPUType cpu_type; + switch (arch_type) { + case llvm::Triple::ArchType::aarch64: + cpu_type = llvm::codeview::CPUType::ARM64; + break; + + default: + cpu_type = llvm::codeview::CPUType::X64; + break; + } + + llvm::ArrayRef<llvm::EnumEntry<uint16_t>> register_names = + llvm::codeview::getRegisterNames(cpu_type); + auto it = llvm::find_if( + register_names, + [®_name](const llvm::EnumEntry<uint16_t> ®ister_entry) { + return reg_name.compare_lower(register_entry.Name) == 0; + }); + + if (it == register_names.end()) + return LLDB_INVALID_REGNUM; + + auto reg_id = static_cast<llvm::codeview::RegisterId>(it->Value); + return npdb::GetLLDBRegisterNumber(arch_type, reg_id); +} + +static bool ParseFPOSingleAssignmentProgram(llvm::StringRef program, + llvm::BumpPtrAllocator &alloc, + llvm::StringRef ®ister_name, + Node *&ast) { + // lvalue of assignment is always first token + // rvalue program goes next + std::tie(register_name, program) = getToken(program); + if (register_name.empty()) + return false; + + ast = Parse(program, alloc); + return ast != nullptr; +} + +static Node *ParseFPOProgram(llvm::StringRef program, + llvm::StringRef register_name, + llvm::Triple::ArchType arch_type, + llvm::BumpPtrAllocator &alloc) { + llvm::DenseMap<llvm::StringRef, Node *> dependent_programs; + + size_t cur = 0; + while (true) { + size_t assign_index = program.find('=', cur); + if (assign_index == llvm::StringRef::npos) { + llvm::StringRef tail = program.slice(cur, llvm::StringRef::npos); + if (!tail.trim().empty()) { + // missing assign operator + return nullptr; + } + break; + } + llvm::StringRef assignment_program = program.slice(cur, assign_index); + + llvm::StringRef lvalue_name; + Node *rvalue_ast = nullptr; + if (!ParseFPOSingleAssignmentProgram(assignment_program, alloc, lvalue_name, + rvalue_ast)) { + return nullptr; + } + + lldbassert(rvalue_ast); + + // Emplace valid dependent subtrees to make target assignment independent + // from predecessors. Resolve all other SymbolNodes as registers. + bool success = + ResolveSymbols(rvalue_ast, [&](SymbolNode &symbol) -> Node * { + if (Node *node = dependent_programs.lookup(symbol.GetName())) + return node; + uint32_t reg_num = + ResolveLLDBRegisterNum(symbol.GetName().drop_front(1), arch_type); + + if (reg_num == LLDB_INVALID_REGNUM) + return nullptr; + + return MakeNode<RegisterNode>(alloc, reg_num); + }); + if (!success) + return nullptr; + + if (lvalue_name == register_name) { + // found target assignment program - no need to parse further + return rvalue_ast; + } + + dependent_programs[lvalue_name] = rvalue_ast; + cur = assign_index + 1; + } + + return nullptr; +} + +bool lldb_private::npdb::TranslateFPOProgramToDWARFExpression( + llvm::StringRef program, llvm::StringRef register_name, + llvm::Triple::ArchType arch_type, Stream &stream) { + llvm::BumpPtrAllocator node_alloc; + Node *target_program = + ParseFPOProgram(program, register_name, arch_type, node_alloc); + if (target_program == nullptr) { + return false; + } + + ToDWARF(*target_program, stream); + return true; +}
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.h new file mode 100644 index 0000000..107e26f --- /dev/null +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.h
@@ -0,0 +1,28 @@ +//===-- PdbFPOProgramToDWARFExpression.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_Plugins_SymbolFile_PDB_PDBFPOProgramToDWARFExpression_h_ +#define lldb_Plugins_SymbolFile_PDB_PDBFPOProgramToDWARFExpression_h_ + +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Triple.h" + +namespace lldb_private { +class Stream; + +namespace npdb { + +bool TranslateFPOProgramToDWARFExpression(llvm::StringRef program, + llvm::StringRef register_name, + llvm::Triple::ArchType arch_type, + lldb_private::Stream &stream); + +} // namespace npdb +} // namespace lldb_private + +#endif
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.cpp index 9f5dab6..ba9a95b 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.cpp
@@ -1,9 +1,8 @@ //===-- PdbIndex.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -133,9 +132,8 @@ PdbCompilandSymId cu_sym_id(modi, iter.offset()); - // If the debug info is incorrect, we could have multiple symbols with the - // same address. So use try_emplace instead of insert, and the first one - // will win. + // It's rare, but we could have multiple symbols with the same address + // because of identical comdat folding. Right now, the first one will win. cci.m_symbols_by_va.insert(std::make_pair(va, PdbSymUid(cu_sym_id))); } } @@ -187,8 +185,6 @@ } CVSymbol PdbIndex::ReadSymbolRecord(PdbCompilandSymId cu_sym) const { - // We need to subtract 4 here to adjust for the codeview debug magic - // at the beginning of the debug info stream. const CompilandIndexItem *cci = compilands().GetCompiland(cu_sym.modi); auto iter = cci->m_debug_stream.getSymbolArray().at(cu_sym.offset); lldbassert(iter != cci->m_debug_stream.getSymbolArray().end());
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.h index 839d4e6..b30e787 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbIndex.h
@@ -1,9 +1,8 @@ //===-- PdbIndex.h ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -115,6 +114,7 @@ create(std::unique_ptr<llvm::pdb::PDBFile>); void SetLoadAddress(lldb::addr_t addr) { m_load_address = addr; } + lldb::addr_t GetLoadAddress() const { return m_load_address; } void ParseSectionContribs(); llvm::pdb::PDBFile &pdb() { return *m_file; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.cpp index e542456..e5ad23f 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.cpp
@@ -1,9 +1,8 @@ //===-- PdbSymUid.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.h index 1166bee..7252d63 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbSymUid.h
@@ -1,9 +1,8 @@ //===-- PdbSymUid.h ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// // A unique identification scheme for Pdb records.
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.cpp index 317725d..1f5c97d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.cpp
@@ -1,9 +1,8 @@ //===-- PdbUtil.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,11 @@ #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" #include "llvm/DebugInfo/CodeView/TypeDeserializer.h" +#include "llvm/DebugInfo/PDB/Native/DbiStream.h" #include "llvm/DebugInfo/PDB/Native/TpiStream.h" #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" +#include "lldb/Symbol/Block.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/lldb-enumerations.h" @@ -43,7 +44,7 @@ gaps = gaps.drop_front(); } - result.Append(start, end); + result.Append(start, end - start); return result; } @@ -507,8 +508,78 @@ return {}; } +static llvm::FixedStreamArray<FrameData>::Iterator +GetCorrespondingFrameData(lldb::addr_t load_addr, + const DebugFrameDataSubsectionRef &fpo_data, + const Variable::RangeList &ranges) { + lldbassert(!ranges.IsEmpty()); + + // assume that all variable ranges correspond to one frame data + using RangeListEntry = Variable::RangeList::Entry; + const RangeListEntry &range = ranges.GetEntryRef(0); + + auto it = fpo_data.begin(); + + // start by searching first frame data range containing variable range + for (; it != fpo_data.end(); ++it) { + RangeListEntry fd_range(load_addr + it->RvaStart, it->CodeSize); + + if (fd_range.Contains(range)) { + break; + } + } + + // then first most nested entry that still contains variable range + auto found = it; + for (; it != fpo_data.end(); ++it) { + RangeListEntry fd_range(load_addr + it->RvaStart, it->CodeSize); + + if (!fd_range.Contains(range)) { + break; + } + found = it; + } + + return found; +} + +static bool GetFrameDataProgram(PdbIndex &index, + const Variable::RangeList &ranges, + llvm::StringRef &out_program) { + const DebugFrameDataSubsectionRef &new_fpo_data = + index.dbi().getNewFpoRecords(); + + auto frame_data_it = + GetCorrespondingFrameData(index.GetLoadAddress(), new_fpo_data, ranges); + if (frame_data_it == new_fpo_data.end()) + return false; + + PDBStringTable &strings = cantFail(index.pdb().getStringTable()); + out_program = cantFail(strings.getStringForID(frame_data_it->FrameFunc)); + return true; +} + +static RegisterId GetBaseFrameRegister(PdbIndex &index, + PdbCompilandSymId frame_proc_id, + bool is_parameter) { + CVSymbol frame_proc_cvs = index.ReadSymbolRecord(frame_proc_id); + lldbassert(frame_proc_cvs.kind() == S_FRAMEPROC); + + FrameProcSym frame_proc(SymbolRecordKind::FrameProcSym); + cantFail(SymbolDeserializer::deserializeAs<FrameProcSym>(frame_proc_cvs, + frame_proc)); + + CPUType cpu_type = index.compilands() + .GetCompiland(frame_proc_id.modi) + ->m_compile_opts->Machine; + + return is_parameter ? frame_proc.getParamFramePtrReg(cpu_type) + : frame_proc.getLocalFramePtrReg(cpu_type); +} + VariableInfo lldb_private::npdb::GetVariableLocationInfo( - PdbIndex &index, PdbCompilandSymId var_id, lldb::ModuleSP module) { + PdbIndex &index, PdbCompilandSymId var_id, Block &block, + lldb::ModuleSP module) { CVSymbol sym = index.ReadSymbolRecord(var_id); @@ -543,13 +614,69 @@ SymbolRecordKind::DefRangeFramePointerRelSym); cantFail(SymbolDeserializer::deserializeAs<DefRangeFramePointerRelSym>( loc_specifier_cvs, loc)); - // FIXME: The register needs to come from the S_FRAMEPROC symbol. - result.location = - MakeRegRelLocationExpression(RegisterId::RSP, loc.Offset, module); - result.ranges = MakeRangeList(index, loc.Range, loc.Gaps); - } else { - // FIXME: Handle other kinds + + Variable::RangeList ranges = MakeRangeList(index, loc.Range, loc.Gaps); + + // TODO: may be better to pass function scope and not lookup it every + // time? find nearest parent function block + Block *cur = █ + while (cur->GetParent()) { + cur = cur->GetParent(); + } + PdbCompilandSymId func_scope_id = + PdbSymUid(cur->GetID()).asCompilandSym(); + CVSymbol func_block_cvs = index.ReadSymbolRecord(func_scope_id); + lldbassert(func_block_cvs.kind() == S_GPROC32 || + func_block_cvs.kind() == S_LPROC32); + + PdbCompilandSymId frame_proc_id( + func_scope_id.modi, func_scope_id.offset + func_block_cvs.length()); + + bool is_parameter = + ((local.Flags & LocalSymFlags::IsParameter) != LocalSymFlags::None); + RegisterId base_reg = + GetBaseFrameRegister(index, frame_proc_id, is_parameter); + + if (base_reg == RegisterId::VFRAME) { + llvm::StringRef program; + if (GetFrameDataProgram(index, ranges, program)) { + result.location = + MakeVFrameRelLocationExpression(program, loc.Offset, module); + result.ranges = std::move(ranges); + } else { + // invalid variable + } + } else { + result.location = + MakeRegRelLocationExpression(base_reg, loc.Offset, module); + result.ranges = std::move(ranges); + } + } else if (loc_specifier_cvs.kind() == S_DEFRANGE_REGISTER_REL) { + DefRangeRegisterRelSym loc(SymbolRecordKind::DefRangeRegisterRelSym); + cantFail(SymbolDeserializer::deserializeAs<DefRangeRegisterRelSym>( + loc_specifier_cvs, loc)); + + Variable::RangeList ranges = MakeRangeList(index, loc.Range, loc.Gaps); + + RegisterId base_reg = (RegisterId)(uint16_t)loc.Hdr.Register; + + if (base_reg == RegisterId::VFRAME) { + llvm::StringRef program; + if (GetFrameDataProgram(index, ranges, program)) { + result.location = MakeVFrameRelLocationExpression( + program, loc.Hdr.BasePointerOffset, module); + result.ranges = std::move(ranges); + } else { + // invalid variable + } + } else { + result.location = MakeRegRelLocationExpression( + base_reg, loc.Hdr.BasePointerOffset, module); + result.ranges = std::move(ranges); + } } + + // FIXME: Handle other kinds return result; } llvm_unreachable("Symbol is not a local variable!");
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.h index 570c300..6f675b5 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/PdbUtil.h
@@ -1,9 +1,8 @@ //===-- PdbUtil.h -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -142,7 +141,7 @@ llvm::StringRef DropNameScope(llvm::StringRef name); VariableInfo GetVariableNameInfo(llvm::codeview::CVSymbol symbol); -VariableInfo GetVariableLocationInfo(PdbIndex &index, PdbCompilandSymId var_id, +VariableInfo GetVariableLocationInfo(PdbIndex &index, PdbCompilandSymId var_id, Block& block, lldb::ModuleSP module); size_t GetTypeSizeForSimpleKind(llvm::codeview::SimpleTypeKind kind);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp index 7e97e2b..e27d469 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp
@@ -1,9 +1,8 @@ //===-- SymbolFileNativePDB.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -74,6 +73,8 @@ return lldb::LanguageType::eLanguageTypeC_plus_plus; case PDB_Lang::C: return lldb::LanguageType::eLanguageTypeC; + case PDB_Lang::Swift: + return lldb::LanguageType::eLanguageTypeSwift; default: return lldb::LanguageType::eLanguageTypeUnknown; } @@ -316,7 +317,7 @@ } void SymbolFileNativePDB::InitializeObject() { - m_obj_load_address = m_obj_file->GetFileOffset(); + m_obj_load_address = m_obj_file->GetBaseAddress().GetFileAddress(); m_index->SetLoadAddress(m_obj_load_address); m_index->ParseSectionContribs(); @@ -594,6 +595,17 @@ return array_sp; } + +TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id, + const MemberFunctionRecord &mfr, + CompilerType ct) { + Declaration decl; + return std::make_shared<lldb_private::Type>( + toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID, + lldb_private::Type::eEncodingIsUID, decl, ct, + lldb_private::Type::eResolveStateFull); +} + TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id, const ProcedureRecord &pr, CompilerType ct) { @@ -654,6 +666,11 @@ llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); return CreateProcedureType(type_id, pr, ct); } + if (cvt.kind() == LF_MFUNCTION) { + MemberFunctionRecord mfr; + llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); + return CreateFunctionType(type_id, mfr, ct); + } return nullptr; } @@ -1137,7 +1154,7 @@ } bool SymbolFileNativePDB::ParseImportedModules( - const SymbolContext &sc, std::vector<ConstString> &imported_modules) { + const SymbolContext &sc, std::vector<SourceModule> &imported_modules) { // PDB does not yet support module debug info return false; } @@ -1151,7 +1168,7 @@ void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); } uint32_t SymbolFileNativePDB::FindGlobalVariables( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, VariableList &variables) { using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; @@ -1178,7 +1195,7 @@ } uint32_t SymbolFileNativePDB::FindFunctions( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, FunctionNameType name_type_mask, bool include_inlines, bool append, SymbolContextList &sc_list) { // For now we only support lookup by method name. @@ -1219,7 +1236,7 @@ } uint32_t SymbolFileNativePDB::FindTypes( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) { if (!append) @@ -1316,7 +1333,9 @@ PdbCompilandSymId var_id, bool is_param) { ModuleSP module = GetObjectFile()->GetModule(); - VariableInfo var_info = GetVariableLocationInfo(*m_index, var_id, module); + Block &block = GetOrCreateBlock(scope_id); + VariableInfo var_info = + GetVariableLocationInfo(*m_index, var_id, block, module); if (!var_info.location || !var_info.ranges) return nullptr; @@ -1549,7 +1568,7 @@ } CompilerDeclContext -SymbolFileNativePDB::FindNamespace(const ConstString &name, +SymbolFileNativePDB::FindNamespace(ConstString name, const CompilerDeclContext *parent_decl_ctx) { return {}; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h index dcf3fe3..20daff2 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h
@@ -1,9 +1,8 @@ //===-- SymbolFileNativePDB.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -45,9 +44,7 @@ friend class UdtRecordCompleter; public: - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -60,9 +57,7 @@ static SymbolFile *CreateInstance(ObjectFile *obj_file); - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ SymbolFileNativePDB(ObjectFile *ofile); ~SymbolFileNativePDB() override; @@ -71,9 +66,7 @@ void InitializeObject() override; - //------------------------------------------------------------------ // Compile Unit function calls - //------------------------------------------------------------------ uint32_t GetNumCompileUnits() override; @@ -95,13 +88,13 @@ FileSpecList &support_files) override; size_t ParseTypes(lldb_private::CompileUnit &comp_unit) override; - bool - ParseImportedModules(const SymbolContext &sc, - std::vector<ConstString> &imported_modules) override; + bool ParseImportedModules( + const SymbolContext &sc, + std::vector<lldb_private::SourceModule> &imported_modules) override; size_t ParseBlocksRecursive(Function &func) override; - uint32_t FindGlobalVariables(const ConstString &name, + uint32_t FindGlobalVariables(ConstString name, const CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, VariableList &variables) override; @@ -130,7 +123,7 @@ size_t GetTypes(SymbolContextScope *sc_scope, lldb::TypeClass type_mask, TypeList &type_list) override; - uint32_t FindFunctions(const ConstString &name, + uint32_t FindFunctions(ConstString name, const CompilerDeclContext *parent_decl_ctx, lldb::FunctionNameType name_type_mask, bool include_inlines, bool append, @@ -139,7 +132,7 @@ uint32_t FindFunctions(const RegularExpression ®ex, bool include_inlines, bool append, SymbolContextList &sc_list) override; - uint32_t FindTypes(const ConstString &name, + uint32_t FindTypes(ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, @@ -151,7 +144,7 @@ TypeSystem *GetTypeSystemForLanguage(lldb::LanguageType language) override; CompilerDeclContext - FindNamespace(const ConstString &name, + FindNamespace(ConstString name, const CompilerDeclContext *parent_decl_ctx) override; ConstString GetPluginName() override; @@ -187,6 +180,9 @@ lldb::TypeSP CreateArrayType(PdbTypeSymId type_id, const llvm::codeview::ArrayRecord &ar, CompilerType ct); + lldb::TypeSP CreateFunctionType(PdbTypeSymId type_id, + const llvm::codeview::MemberFunctionRecord &pr, + CompilerType ct); lldb::TypeSP CreateProcedureType(PdbTypeSymId type_id, const llvm::codeview::ProcedureRecord &pr, CompilerType ct);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.cpp index 239dfbe..3c494dc 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.cpp
@@ -50,7 +50,8 @@ } clang::QualType UdtRecordCompleter::AddBaseClassForTypeIndex( - llvm::codeview::TypeIndex ti, llvm::codeview::MemberAccess access) { + llvm::codeview::TypeIndex ti, llvm::codeview::MemberAccess access, + llvm::Optional<uint64_t> vtable_idx) { PdbTypeSymId type_id(ti); clang::QualType qt = m_ast_builder.GetOrCreateType(type_id); @@ -58,13 +59,32 @@ std::unique_ptr<clang::CXXBaseSpecifier> base_spec = m_ast_builder.clang().CreateBaseClassSpecifier( - qt.getAsOpaquePtr(), TranslateMemberAccess(access), false, - udt_cvt.kind() == LF_CLASS); + qt.getAsOpaquePtr(), TranslateMemberAccess(access), + vtable_idx.hasValue(), udt_cvt.kind() == LF_CLASS); lldbassert(base_spec); - m_bases.push_back(std::move(base_spec)); + + m_bases.push_back( + std::make_pair(vtable_idx.getValueOr(0), std::move(base_spec))); + return qt; } +void UdtRecordCompleter::AddMethod(llvm::StringRef name, TypeIndex type_idx, + MemberAccess access, MethodOptions options, + MemberAttributes attrs) { + clang::QualType method_qt = + m_ast_builder.GetOrCreateType(PdbTypeSymId(type_idx)); + m_ast_builder.CompleteType(method_qt); + + lldb::AccessType access_type = TranslateMemberAccess(access); + bool is_artificial = (options & MethodOptions::CompilerGenerated) == + MethodOptions::CompilerGenerated; + m_ast_builder.clang().AddMethodToCXXRecordType( + m_derived_ct.GetOpaqueQualType(), name.data(), nullptr, + m_ast_builder.ToCompilerType(method_qt), access_type, attrs.isVirtual(), + attrs.isStatic(), false, false, false, is_artificial); +} + Error UdtRecordCompleter::visitKnownMember(CVMemberRecord &cvr, BaseClassRecord &base) { clang::QualType base_qt = @@ -82,9 +102,8 @@ Error UdtRecordCompleter::visitKnownMember(CVMemberRecord &cvr, VirtualBaseClassRecord &base) { - AddBaseClassForTypeIndex(base.BaseType, base.getAccess()); + AddBaseClassForTypeIndex(base.BaseType, base.getAccess(), base.VTableIndex); - // FIXME: Handle virtual base offsets. return Error::success(); } @@ -158,11 +177,27 @@ Error UdtRecordCompleter::visitKnownMember(CVMemberRecord &cvr, OneMethodRecord &one_method) { + AddMethod(one_method.Name, one_method.Type, one_method.getAccess(), + one_method.getOptions(), one_method.Attrs); + return Error::success(); } Error UdtRecordCompleter::visitKnownMember(CVMemberRecord &cvr, OverloadedMethodRecord &overloaded) { + TypeIndex method_list_idx = overloaded.MethodList; + + CVType method_list_type = m_tpi.getType(method_list_idx); + assert(method_list_type.kind() == LF_METHODLIST); + + MethodOverloadListRecord method_list; + llvm::cantFail(TypeDeserializer::deserializeAs<MethodOverloadListRecord>( + method_list_type, method_list)); + + for (const OneMethodRecord &method : method_list.Methods) + AddMethod(overloaded.Name, method.Type, method.getAccess(), + method.getOptions(), method.Attrs); + return Error::success(); } @@ -177,9 +212,19 @@ } void UdtRecordCompleter::complete() { + // Ensure the correct order for virtual bases. + std::stable_sort(m_bases.begin(), m_bases.end(), + [](const IndexedBase &lhs, const IndexedBase &rhs) { + return lhs.first < rhs.first; + }); + + std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases; + bases.reserve(m_bases.size()); + for (auto &ib : m_bases) + bases.push_back(std::move(ib.second)); + ClangASTContext &clang = m_ast_builder.clang(); - clang.TransferBaseClasses(m_derived_ct.GetOpaqueQualType(), - std::move(m_bases)); + clang.TransferBaseClasses(m_derived_ct.GetOpaqueQualType(), std::move(bases)); clang.AddMethodOverridesForCXXRecordType(m_derived_ct.GetOpaqueQualType()); ClangASTContext::BuildIndirectFields(m_derived_ct);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.h index 4696851..5539758 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.h
@@ -1,9 +1,8 @@ -//===-- SymbolFileNativePDB.h -----------------------------------*- C++ -*-===// +//===-- UdtRecordCompleter.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,6 +35,9 @@ class PdbAstBuilder; class UdtRecordCompleter : public llvm::codeview::TypeVisitorCallbacks { + using IndexedBase = + std::pair<uint64_t, std::unique_ptr<clang::CXXBaseSpecifier>>; + union UdtTagRecord { UdtTagRecord() {} llvm::codeview::UnionRecord ur; @@ -48,7 +50,7 @@ clang::TagDecl &m_tag_decl; PdbAstBuilder &m_ast_builder; llvm::pdb::TpiStream &m_tpi; - std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> m_bases; + std::vector<IndexedBase> m_bases; ClangASTImporter::LayoutInfo m_layout; public: @@ -65,8 +67,13 @@ void complete(); private: - clang::QualType AddBaseClassForTypeIndex(llvm::codeview::TypeIndex ti, - llvm::codeview::MemberAccess access); + clang::QualType AddBaseClassForTypeIndex( + llvm::codeview::TypeIndex ti, llvm::codeview::MemberAccess access, + llvm::Optional<uint64_t> vtable_idx = llvm::Optional<uint64_t>()); + void AddMethod(llvm::StringRef name, llvm::codeview::TypeIndex type_idx, + llvm::codeview::MemberAccess access, + llvm::codeview::MethodOptions options, + llvm::codeview::MemberAttributes attrs); }; } // namespace npdb
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/CMakeLists.txt b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/CMakeLists.txt index 19698a7..64168d0 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/CMakeLists.txt
@@ -8,7 +8,7 @@ clangLex lldbCore lldbSymbol - lldbUtility + lldbUtility lldbPluginSymbolFileNativePDB LINK_COMPONENTS DebugInfoPDB
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp index 65e718b..82cfcfb 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp
@@ -1,9 +1,8 @@ //===-- PDBASTParser.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -568,9 +567,12 @@ ast_typedef = ast_typedef.AddVolatileModifier(); GetDeclarationForSymbol(type, decl); + llvm::Optional<uint64_t> size; + if (type_def->getLength()) + size = type_def->getLength(); return std::make_shared<lldb_private::Type>( type_def->getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name), - type_def->getLength(), nullptr, target_type->GetID(), + size, nullptr, target_type->GetID(), lldb_private::Type::eEncodingIsTypedefUID, decl, ast_typedef, lldb_private::Type::eResolveStateFull); } break; @@ -637,16 +639,19 @@ GetDeclarationForSymbol(type, decl); return std::make_shared<lldb_private::Type>( - type.getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name), 0, - nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, - func_sig_ast_type, lldb_private::Type::eResolveStateFull); + type.getSymIndexId(), m_ast.GetSymbolFile(), ConstString(name), + llvm::None, nullptr, LLDB_INVALID_UID, + lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type, + lldb_private::Type::eResolveStateFull); } break; case PDB_SymType::ArrayType: { auto array_type = llvm::dyn_cast<PDBSymbolTypeArray>(&type); assert(array_type); uint32_t num_elements = array_type->getCount(); uint32_t element_uid = array_type->getElementTypeId(); - uint32_t bytes = array_type->getLength(); + llvm::Optional<uint64_t> bytes; + if (uint64_t size = array_type->getLength()) + bytes = size; // If array rank > 0, PDB gives the element type at N=0. So element type // will parsed in the order N=0, N=1,..., N=rank sequentially. @@ -682,10 +687,12 @@ if (builtin_kind == PDB_BuiltinType::None) return nullptr; - uint64_t bytes = builtin_type->getLength(); + llvm::Optional<uint64_t> bytes; + if (uint64_t size = builtin_type->getLength()) + bytes = size; Encoding encoding = TranslateBuiltinEncoding(builtin_kind); CompilerType builtin_ast_type = GetBuiltinTypeForPDBEncodingAndBitSize( - m_ast, *builtin_type, encoding, bytes * 8); + m_ast, *builtin_type, encoding, bytes.getValueOr(0) * 8); if (builtin_type->isConstType()) builtin_ast_type = builtin_ast_type.AddConstModifier();
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h index 0235387..9221d42 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h
@@ -1,9 +1,8 @@ //===-- PDBASTParser.h ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.cpp index 9f398ef..1c17bf6 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.cpp
@@ -1,9 +1,8 @@ //===-- PDBLocationToDWARFExpression.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,487 +12,64 @@ #include "lldb/Core/StreamBuffer.h" #include "lldb/Core/dwarf.h" #include "lldb/Expression/DWARFExpression.h" +#include "lldb/Symbol/Variable.h" #include "lldb/Utility/DataBufferHeap.h" #include "llvm/DebugInfo/CodeView/CodeView.h" +#include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" -#include "Plugins/Process/Utility/lldb-x86-register-enums.h" +#include "Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.h" +#include "Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.h" using namespace lldb; using namespace lldb_private; +using namespace lldb_private::npdb; using namespace llvm::pdb; -namespace { -const uint32_t g_code_view_to_lldb_registers_x86[] = { - LLDB_INVALID_REGNUM, // NONE - lldb_al_i386, // AL - lldb_cl_i386, // CL - lldb_dl_i386, // DL - lldb_bl_i386, // BL - lldb_ah_i386, // AH - lldb_ch_i386, // CH - lldb_dh_i386, // DH - lldb_bh_i386, // BH - lldb_ax_i386, // AX - lldb_cx_i386, // CX - lldb_dx_i386, // DX - lldb_bx_i386, // BX - lldb_sp_i386, // SP - lldb_bp_i386, // BP - lldb_si_i386, // SI - lldb_di_i386, // DI - lldb_eax_i386, // EAX - lldb_ecx_i386, // ECX - lldb_edx_i386, // EDX - lldb_ebx_i386, // EBX - lldb_esp_i386, // ESP - lldb_ebp_i386, // EBP - lldb_esi_i386, // ESI - lldb_edi_i386, // EDI - lldb_es_i386, // ES - lldb_cs_i386, // CS - lldb_ss_i386, // SS - lldb_ds_i386, // DS - lldb_fs_i386, // FS - lldb_gs_i386, // GS - LLDB_INVALID_REGNUM, // IP - LLDB_INVALID_REGNUM, // FLAGS - lldb_eip_i386, // EIP - lldb_eflags_i386, // EFLAGS - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // TEMP - LLDB_INVALID_REGNUM, // TEMPH - LLDB_INVALID_REGNUM, // QUOTE - LLDB_INVALID_REGNUM, // PCDR3 - LLDB_INVALID_REGNUM, // PCDR4 - LLDB_INVALID_REGNUM, // PCDR5 - LLDB_INVALID_REGNUM, // PCDR6 - LLDB_INVALID_REGNUM, // PCDR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // CR0 - LLDB_INVALID_REGNUM, // CR1 - LLDB_INVALID_REGNUM, // CR2 - LLDB_INVALID_REGNUM, // CR3 - LLDB_INVALID_REGNUM, // CR4 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_dr0_i386, // DR0 - lldb_dr1_i386, // DR1 - lldb_dr2_i386, // DR2 - lldb_dr3_i386, // DR3 - lldb_dr4_i386, // DR4 - lldb_dr5_i386, // DR5 - lldb_dr6_i386, // DR6 - lldb_dr7_i386, // DR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // GDTR - LLDB_INVALID_REGNUM, // GDTL - LLDB_INVALID_REGNUM, // IDTR - LLDB_INVALID_REGNUM, // IDTL - LLDB_INVALID_REGNUM, // LDTR - LLDB_INVALID_REGNUM, // TR - LLDB_INVALID_REGNUM, // PSEUDO1 - LLDB_INVALID_REGNUM, // PSEUDO2 - LLDB_INVALID_REGNUM, // PSEUDO3 - LLDB_INVALID_REGNUM, // PSEUDO4 - LLDB_INVALID_REGNUM, // PSEUDO5 - LLDB_INVALID_REGNUM, // PSEUDO6 - LLDB_INVALID_REGNUM, // PSEUDO7 - LLDB_INVALID_REGNUM, // PSEUDO8 - LLDB_INVALID_REGNUM, // PSEUDO9 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_st0_i386, // ST0 - lldb_st1_i386, // ST1 - lldb_st2_i386, // ST2 - lldb_st3_i386, // ST3 - lldb_st4_i386, // ST4 - lldb_st5_i386, // ST5 - lldb_st6_i386, // ST6 - lldb_st7_i386, // ST7 - LLDB_INVALID_REGNUM, // CTRL - LLDB_INVALID_REGNUM, // STAT - LLDB_INVALID_REGNUM, // TAG - LLDB_INVALID_REGNUM, // FPIP - LLDB_INVALID_REGNUM, // FPCS - LLDB_INVALID_REGNUM, // FPDO - LLDB_INVALID_REGNUM, // FPDS - LLDB_INVALID_REGNUM, // ISEM - LLDB_INVALID_REGNUM, // FPEIP - LLDB_INVALID_REGNUM, // FPEDO - lldb_mm0_i386, // MM0 - lldb_mm1_i386, // MM1 - lldb_mm2_i386, // MM2 - lldb_mm3_i386, // MM3 - lldb_mm4_i386, // MM4 - lldb_mm5_i386, // MM5 - lldb_mm6_i386, // MM6 - lldb_mm7_i386, // MM7 - lldb_xmm0_i386, // XMM0 - lldb_xmm1_i386, // XMM1 - lldb_xmm2_i386, // XMM2 - lldb_xmm3_i386, // XMM3 - lldb_xmm4_i386, // XMM4 - lldb_xmm5_i386, // XMM5 - lldb_xmm6_i386, // XMM6 - lldb_xmm7_i386 // XMM7 -}; +static std::unique_ptr<IPDBFrameData> +GetCorrespondingFrameData(const IPDBSession &session, + const Variable::RangeList &ranges) { + auto enumFrameData = session.getFrameData(); + if (!enumFrameData) + return nullptr; -const uint32_t g_code_view_to_lldb_registers_x86_64[] = { - LLDB_INVALID_REGNUM, // NONE - lldb_al_x86_64, // AL - lldb_cl_x86_64, // CL - lldb_dl_x86_64, // DL - lldb_bl_x86_64, // BL - lldb_ah_x86_64, // AH - lldb_ch_x86_64, // CH - lldb_dh_x86_64, // DH - lldb_bh_x86_64, // BH - lldb_ax_x86_64, // AX - lldb_cx_x86_64, // CX - lldb_dx_x86_64, // DX - lldb_bx_x86_64, // BX - lldb_sp_x86_64, // SP - lldb_bp_x86_64, // BP - lldb_si_x86_64, // SI - lldb_di_x86_64, // DI - lldb_eax_x86_64, // EAX - lldb_ecx_x86_64, // ECX - lldb_edx_x86_64, // EDX - lldb_ebx_x86_64, // EBX - lldb_esp_x86_64, // ESP - lldb_ebp_x86_64, // EBP - lldb_esi_x86_64, // ESI - lldb_edi_x86_64, // EDI - lldb_es_x86_64, // ES - lldb_cs_x86_64, // CS - lldb_ss_x86_64, // SS - lldb_ds_x86_64, // DS - lldb_fs_x86_64, // FS - lldb_gs_x86_64, // GS - LLDB_INVALID_REGNUM, // IP - LLDB_INVALID_REGNUM, // FLAGS - LLDB_INVALID_REGNUM, // EIP - LLDB_INVALID_REGNUM, // EFLAGS - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // TEMP - LLDB_INVALID_REGNUM, // TEMPH - LLDB_INVALID_REGNUM, // QUOTE - LLDB_INVALID_REGNUM, // PCDR3 - LLDB_INVALID_REGNUM, // PCDR4 - LLDB_INVALID_REGNUM, // PCDR5 - LLDB_INVALID_REGNUM, // PCDR6 - LLDB_INVALID_REGNUM, // PCDR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // CR0 - LLDB_INVALID_REGNUM, // CR1 - LLDB_INVALID_REGNUM, // CR2 - LLDB_INVALID_REGNUM, // CR3 - LLDB_INVALID_REGNUM, // CR4 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_dr0_x86_64, // DR0 - lldb_dr1_x86_64, // DR1 - lldb_dr2_x86_64, // DR2 - lldb_dr3_x86_64, // DR3 - lldb_dr4_x86_64, // DR4 - lldb_dr5_x86_64, // DR5 - lldb_dr6_x86_64, // DR6 - lldb_dr7_x86_64, // DR7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // GDTR - LLDB_INVALID_REGNUM, // GDTL - LLDB_INVALID_REGNUM, // IDTR - LLDB_INVALID_REGNUM, // IDTL - LLDB_INVALID_REGNUM, // LDTR - LLDB_INVALID_REGNUM, // TR - LLDB_INVALID_REGNUM, // PSEUDO1 - LLDB_INVALID_REGNUM, // PSEUDO2 - LLDB_INVALID_REGNUM, // PSEUDO3 - LLDB_INVALID_REGNUM, // PSEUDO4 - LLDB_INVALID_REGNUM, // PSEUDO5 - LLDB_INVALID_REGNUM, // PSEUDO6 - LLDB_INVALID_REGNUM, // PSEUDO7 - LLDB_INVALID_REGNUM, // PSEUDO8 - LLDB_INVALID_REGNUM, // PSEUDO9 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_st0_x86_64, // ST0 - lldb_st1_x86_64, // ST1 - lldb_st2_x86_64, // ST2 - lldb_st3_x86_64, // ST3 - lldb_st4_x86_64, // ST4 - lldb_st5_x86_64, // ST5 - lldb_st6_x86_64, // ST6 - lldb_st7_x86_64, // ST7 - LLDB_INVALID_REGNUM, // CTRL - LLDB_INVALID_REGNUM, // STAT - LLDB_INVALID_REGNUM, // TAG - LLDB_INVALID_REGNUM, // FPIP - LLDB_INVALID_REGNUM, // FPCS - LLDB_INVALID_REGNUM, // FPDO - LLDB_INVALID_REGNUM, // FPDS - LLDB_INVALID_REGNUM, // ISEM - LLDB_INVALID_REGNUM, // FPEIP - LLDB_INVALID_REGNUM, // FPEDO - lldb_mm0_x86_64, // MM0 - lldb_mm1_x86_64, // MM1 - lldb_mm2_x86_64, // MM2 - lldb_mm3_x86_64, // MM3 - lldb_mm4_x86_64, // MM4 - lldb_mm5_x86_64, // MM5 - lldb_mm6_x86_64, // MM6 - lldb_mm7_x86_64, // MM7 - lldb_xmm0_x86_64, // XMM0 - lldb_xmm1_x86_64, // XMM1 - lldb_xmm2_x86_64, // XMM2 - lldb_xmm3_x86_64, // XMM3 - lldb_xmm4_x86_64, // XMM4 - lldb_xmm5_x86_64, // XMM5 - lldb_xmm6_x86_64, // XMM6 - lldb_xmm7_x86_64, // XMM7 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, - lldb_mxcsr_x86_64, // MXCSR - LLDB_INVALID_REGNUM, // EDXEAX - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, // EMM0L - LLDB_INVALID_REGNUM, // EMM1L - LLDB_INVALID_REGNUM, // EMM2L - LLDB_INVALID_REGNUM, // EMM3L - LLDB_INVALID_REGNUM, // EMM4L - LLDB_INVALID_REGNUM, // EMM5L - LLDB_INVALID_REGNUM, // EMM6L - LLDB_INVALID_REGNUM, // EMM7L - LLDB_INVALID_REGNUM, // EMM0H - LLDB_INVALID_REGNUM, // EMM1H - LLDB_INVALID_REGNUM, // EMM2H - LLDB_INVALID_REGNUM, // EMM3H - LLDB_INVALID_REGNUM, // EMM4H - LLDB_INVALID_REGNUM, // EMM5H - LLDB_INVALID_REGNUM, // EMM6H - LLDB_INVALID_REGNUM, // EMM7H - LLDB_INVALID_REGNUM, // MM00 - LLDB_INVALID_REGNUM, // MM01 - LLDB_INVALID_REGNUM, // MM10 - LLDB_INVALID_REGNUM, // MM11 - LLDB_INVALID_REGNUM, // MM20 - LLDB_INVALID_REGNUM, // MM21 - LLDB_INVALID_REGNUM, // MM30 - LLDB_INVALID_REGNUM, // MM31 - LLDB_INVALID_REGNUM, // MM40 - LLDB_INVALID_REGNUM, // MM41 - LLDB_INVALID_REGNUM, // MM50 - LLDB_INVALID_REGNUM, // MM51 - LLDB_INVALID_REGNUM, // MM60 - LLDB_INVALID_REGNUM, // MM61 - LLDB_INVALID_REGNUM, // MM70 - LLDB_INVALID_REGNUM, // MM71 - lldb_xmm8_x86_64, // XMM8 - lldb_xmm9_x86_64, // XMM9 - lldb_xmm10_x86_64, // XMM10 - lldb_xmm11_x86_64, // XMM11 - lldb_xmm12_x86_64, // XMM12 - lldb_xmm13_x86_64, // XMM13 - lldb_xmm14_x86_64, // XMM14 - lldb_xmm15_x86_64, // XMM15 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, - lldb_sil_x86_64, // SIL - lldb_dil_x86_64, // DIL - lldb_bpl_x86_64, // BPL - lldb_spl_x86_64, // SPL - lldb_rax_x86_64, // RAX - lldb_rbx_x86_64, // RBX - lldb_rcx_x86_64, // RCX - lldb_rdx_x86_64, // RDX - lldb_rsi_x86_64, // RSI - lldb_rdi_x86_64, // RDI - lldb_rbp_x86_64, // RBP - lldb_rsp_x86_64, // RSP - lldb_r8_x86_64, // R8 - lldb_r9_x86_64, // R9 - lldb_r10_x86_64, // R10 - lldb_r11_x86_64, // R11 - lldb_r12_x86_64, // R12 - lldb_r13_x86_64, // R13 - lldb_r14_x86_64, // R14 - lldb_r15_x86_64, // R15 - lldb_r8l_x86_64, // R8B - lldb_r9l_x86_64, // R9B - lldb_r10l_x86_64, // R10B - lldb_r11l_x86_64, // R11B - lldb_r12l_x86_64, // R12B - lldb_r13l_x86_64, // R13B - lldb_r14l_x86_64, // R14B - lldb_r15l_x86_64, // R15B - lldb_r8w_x86_64, // R8W - lldb_r9w_x86_64, // R9W - lldb_r10w_x86_64, // R10W - lldb_r11w_x86_64, // R11W - lldb_r12w_x86_64, // R12W - lldb_r13w_x86_64, // R13W - lldb_r14w_x86_64, // R14W - lldb_r15w_x86_64, // R15W - lldb_r8d_x86_64, // R8D - lldb_r9d_x86_64, // R9D - lldb_r10d_x86_64, // R10D - lldb_r11d_x86_64, // R11D - lldb_r12d_x86_64, // R12D - lldb_r13d_x86_64, // R13D - lldb_r14d_x86_64, // R14D - lldb_r15d_x86_64, // R15D - lldb_ymm0_x86_64, // AMD64_YMM0 - lldb_ymm1_x86_64, // AMD64_YMM1 - lldb_ymm2_x86_64, // AMD64_YMM2 - lldb_ymm3_x86_64, // AMD64_YMM3 - lldb_ymm4_x86_64, // AMD64_YMM4 - lldb_ymm5_x86_64, // AMD64_YMM5 - lldb_ymm6_x86_64, // AMD64_YMM6 - lldb_ymm7_x86_64, // AMD64_YMM7 - lldb_ymm8_x86_64, // AMD64_YMM8 - lldb_ymm9_x86_64, // AMD64_YMM9 - lldb_ymm10_x86_64, // AMD64_YMM10 - lldb_ymm11_x86_64, // AMD64_YMM11 - lldb_ymm12_x86_64, // AMD64_YMM12 - lldb_ymm13_x86_64, // AMD64_YMM13 - lldb_ymm14_x86_64, // AMD64_YMM14 - lldb_ymm15_x86_64, // AMD64_YMM15 - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, - lldb_bnd0_x86_64, // BND0 - lldb_bnd1_x86_64, // BND1 - lldb_bnd2_x86_64 // BND2 -}; + std::unique_ptr<IPDBFrameData> found; + while (auto fd = enumFrameData->getNext()) { + Range<lldb::addr_t, lldb::addr_t> fdRange(fd->getVirtualAddress(), + fd->getLengthBlock()); -uint32_t GetLLDBRegisterNumber(llvm::Triple::ArchType arch_type, - llvm::codeview::RegisterId register_id) { - switch (arch_type) { - case llvm::Triple::x86: - if (static_cast<uint16_t>(register_id) < - sizeof(g_code_view_to_lldb_registers_x86) / - sizeof(g_code_view_to_lldb_registers_x86[0])) - return g_code_view_to_lldb_registers_x86[static_cast<uint16_t>( - register_id)]; + for (size_t i = 0; i < ranges.GetSize(); i++) { + auto range = ranges.GetEntryAtIndex(i); + if (!range) + continue; - switch (register_id) { - case llvm::codeview::RegisterId::MXCSR: - return lldb_mxcsr_i386; - case llvm::codeview::RegisterId::BND0: - return lldb_bnd0_i386; - case llvm::codeview::RegisterId::BND1: - return lldb_bnd1_i386; - case llvm::codeview::RegisterId::BND2: - return lldb_bnd2_i386; - default: - return LLDB_INVALID_REGNUM; + if (!range->DoesIntersect(fdRange)) + continue; + + found = std::move(fd); + + break; } - case llvm::Triple::x86_64: - if (static_cast<uint16_t>(register_id) < - sizeof(g_code_view_to_lldb_registers_x86_64) / - sizeof(g_code_view_to_lldb_registers_x86_64[0])) - return g_code_view_to_lldb_registers_x86_64[static_cast<uint16_t>( - register_id)]; - - return LLDB_INVALID_REGNUM; - default: - return LLDB_INVALID_REGNUM; } + + return found; } -uint32_t GetGenericRegisterNumber(llvm::codeview::RegisterId register_id) { - if (register_id == llvm::codeview::RegisterId::VFRAME) - return LLDB_REGNUM_GENERIC_FP; - - return LLDB_INVALID_REGNUM; +static bool EmitVFrameEvaluationDWARFExpression( + llvm::StringRef program, llvm::Triple::ArchType arch_type, Stream &stream) { + // VFrame value always stored in $TO pseudo-register + return TranslateFPOProgramToDWARFExpression(program, "$T0", arch_type, + stream); } -uint32_t GetRegisterNumber(llvm::Triple::ArchType arch_type, - llvm::codeview::RegisterId register_id, - RegisterKind ®ister_kind) { - register_kind = eRegisterKindLLDB; - uint32_t reg_num = GetLLDBRegisterNumber(arch_type, register_id); - if (reg_num != LLDB_INVALID_REGNUM) - return reg_num; - - register_kind = eRegisterKindGeneric; - return GetGenericRegisterNumber(register_id); -} -} // namespace - -DWARFExpression ConvertPDBLocationToDWARFExpression(ModuleSP module, - const PDBSymbolData &symbol, - bool &is_constant) { +DWARFExpression ConvertPDBLocationToDWARFExpression( + ModuleSP module, const PDBSymbolData &symbol, + const Variable::RangeList &ranges, bool &is_constant) { is_constant = true; if (!module) - return DWARFExpression(nullptr); + return DWARFExpression(); const ArchSpec &architecture = module->GetArchitecture(); llvm::Triple::ArchType arch_type = architecture.GetMachine(); @@ -501,7 +77,7 @@ uint32_t address_size = architecture.GetAddressByteSize(); uint32_t byte_size = architecture.GetDataByteSize(); if (byte_order == eByteOrderInvalid || address_size == 0) - return DWARFExpression(nullptr); + return DWARFExpression(); RegisterKind register_kind = eRegisterKindDWARF; StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order); @@ -512,15 +88,13 @@ SectionList *section_list = module->GetSectionList(); if (!section_list) - return DWARFExpression(nullptr); + return DWARFExpression(); - uint32_t section_idx = symbol.getAddressSection() - 1; - if (section_idx >= section_list->GetSize()) - return DWARFExpression(nullptr); + uint32_t section_id = symbol.getAddressSection(); - auto section = section_list->GetSectionAtIndex(section_idx); + auto section = section_list->FindSectionByID(section_id); if (!section) - return DWARFExpression(nullptr); + return DWARFExpression(); uint32_t offset = symbol.getAddressOffset(); stream.PutMaxHex64(section->GetFileAddress() + offset, address_size, @@ -531,10 +105,32 @@ break; } case PDB_LocType::RegRel: { - uint32_t reg_num = - GetRegisterNumber(arch_type, symbol.getRegisterId(), register_kind); - if (reg_num == LLDB_INVALID_REGNUM) - return DWARFExpression(nullptr); + uint32_t reg_num; + auto reg_id = symbol.getRegisterId(); + if (reg_id == llvm::codeview::RegisterId::VFRAME) { + if (auto fd = GetCorrespondingFrameData(symbol.getSession(), ranges)) { + if (EmitVFrameEvaluationDWARFExpression(fd->getProgram(), arch_type, + stream)) { + int32_t offset = symbol.getOffset(); + stream.PutHex8(DW_OP_consts); + stream.PutSLEB128(offset); + stream.PutHex8(DW_OP_plus); + + register_kind = eRegisterKindLLDB; + + is_constant = false; + break; + } + } + + register_kind = eRegisterKindGeneric; + reg_num = LLDB_REGNUM_GENERIC_FP; + } else { + register_kind = eRegisterKindLLDB; + reg_num = GetLLDBRegisterNumber(arch_type, reg_id); + if (reg_num == LLDB_INVALID_REGNUM) + return DWARFExpression(); + } if (reg_num > 31) { stream.PutHex8(DW_OP_bregx); @@ -550,10 +146,10 @@ break; } case PDB_LocType::Enregistered: { - uint32_t reg_num = - GetRegisterNumber(arch_type, symbol.getRegisterId(), register_kind); + register_kind = eRegisterKindLLDB; + uint32_t reg_num = GetLLDBRegisterNumber(arch_type, symbol.getRegisterId()); if (reg_num == LLDB_INVALID_REGNUM) - return DWARFExpression(nullptr); + return DWARFExpression(); if (reg_num > 31) { stream.PutHex8(DW_OP_regx); @@ -572,7 +168,7 @@ break; } default: - return DWARFExpression(nullptr); + return DWARFExpression(); } DataBufferSP buffer =
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h index 37b80df..2e9d138 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h
@@ -1,9 +1,8 @@ //===-- PDBLocationToDWARFExpression.h --------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -11,6 +10,7 @@ #define lldb_Plugins_SymbolFile_PDB_PDBLocationToDWARFExpression_h_ #include "lldb/Core/Module.h" +#include "lldb/Symbol/Variable.h" namespace lldb_private { class DWARFExpression; @@ -22,24 +22,26 @@ } } // namespace llvm -//------------------------------------------------------------------------------ /// Converts a location information from a PDB symbol to a DWARF expression /// -/// @param[in] module +/// \param[in] module /// The module \a symbol belongs to. /// -/// @param[in] symbol +/// \param[in] symbol /// The symbol with a location information to convert. /// -/// @param[out] is_constant +/// \param[in] ranges +/// Ranges where this variable is valid. +/// +/// \param[out] is_constant /// Set to \b true if the result expression is a constant value data, /// and \b false if it is a DWARF bytecode. /// -/// @return +/// \return /// The DWARF expression corresponding to the location data of \a symbol. -//------------------------------------------------------------------------------ lldb_private::DWARFExpression ConvertPDBLocationToDWARFExpression(lldb::ModuleSP module, const llvm::pdb::PDBSymbolData &symbol, + const lldb_private::Variable::RangeList &ranges, bool &is_constant); #endif
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp index ad25842..17dfcda 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp
@@ -1,9 +1,8 @@ //===-- SymbolFilePDB.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -65,6 +64,8 @@ return lldb::LanguageType::eLanguageTypeC_plus_plus; case PDB_Lang::C: return lldb::LanguageType::eLanguageTypeC; + case PDB_Lang::Swift: + return lldb::LanguageType::eLanguageTypeSwift; default: return lldb::LanguageType::eLanguageTypeUnknown; } @@ -123,7 +124,7 @@ SymbolFilePDB::SymbolFilePDB(lldb_private::ObjectFile *object_file) : SymbolFile(object_file), m_session_up(), m_global_scope_up(), - m_cached_compile_unit_count(0), m_tu_decl_ctx_up() {} + m_cached_compile_unit_count(0) {} SymbolFilePDB::~SymbolFilePDB() {} @@ -182,20 +183,12 @@ } void SymbolFilePDB::InitializeObject() { - lldb::addr_t obj_load_address = m_obj_file->GetFileOffset(); + lldb::addr_t obj_load_address = m_obj_file->GetBaseAddress().GetFileAddress(); lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS); m_session_up->setLoadAddress(obj_load_address); if (!m_global_scope_up) m_global_scope_up = m_session_up->getGlobalScope(); lldbassert(m_global_scope_up.get()); - - TypeSystem *type_system = - GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); - ClangASTContext *clang_type_system = - llvm::dyn_cast_or_null<ClangASTContext>(type_system); - lldbassert(clang_type_system); - m_tu_decl_ctx_up = llvm::make_unique<CompilerDeclContext>( - type_system, clang_type_system->GetTranslationUnitDecl()); } uint32_t SymbolFilePDB::GetNumCompileUnits() { @@ -308,7 +301,8 @@ comp_unit.AddFunction(func_sp); - TypeSystem *type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + LanguageType lang = ParseLanguage(comp_unit); + TypeSystem *type_system = GetTypeSystemForLanguage(lang); if (!type_system) return nullptr; ClangASTContext *clang_type_system = @@ -378,7 +372,7 @@ bool SymbolFilePDB::ParseImportedModules( const lldb_private::SymbolContext &sc, - std::vector<lldb_private::ConstString> &imported_modules) { + std::vector<SourceModule> &imported_modules) { // PDB does not yet support module debug info return false; } @@ -934,12 +928,25 @@ Variable::RangeList ranges; SymbolContextScope *context_scope = sc.comp_unit; - if (scope == eValueTypeVariableLocal) { + if (scope == eValueTypeVariableLocal || scope == eValueTypeVariableArgument) { if (sc.function) { - context_scope = sc.function->GetBlock(true).FindBlockByID( - pdb_data.getLexicalParentId()); - if (context_scope == nullptr) - context_scope = sc.function; + Block &function_block = sc.function->GetBlock(true); + Block *block = + function_block.FindBlockByID(pdb_data.getLexicalParentId()); + if (!block) + block = &function_block; + + context_scope = block; + + for (size_t i = 0, num_ranges = block->GetNumRanges(); i < num_ranges; + ++i) { + AddressRange range; + if (!block->GetRangeAtIndex(i, range)) + continue; + + ranges.Append(range.GetBaseAddress().GetFileAddress(), + range.GetByteSize()); + } } } @@ -952,7 +959,7 @@ bool is_constant; DWARFExpression location = ConvertPDBLocationToDWARFExpression( - GetObjectFile()->GetModule(), pdb_data, is_constant); + GetObjectFile()->GetModule(), pdb_data, ranges, is_constant); var_sp = std::make_shared<Variable>( var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope, @@ -1034,7 +1041,7 @@ } uint32_t SymbolFilePDB::FindGlobalVariables( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, lldb_private::VariableList &variables) { if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) @@ -1234,7 +1241,7 @@ } uint32_t SymbolFilePDB::FindFunctions( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, FunctionNameType name_type_mask, bool include_inlines, bool append, lldb_private::SymbolContextList &sc_list) { @@ -1337,11 +1344,9 @@ return; while (auto pub_symbol = results->getNext()) { - auto section_idx = pub_symbol->getAddressSection() - 1; - if (section_idx >= section_list->GetSize()) - continue; + auto section_id = pub_symbol->getAddressSection(); - auto section = section_list->GetSectionAtIndex(section_idx); + auto section = section_list->FindSectionByID(section_id); if (!section) continue; @@ -1376,7 +1381,7 @@ } uint32_t SymbolFilePDB::FindTypes( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, @@ -1618,7 +1623,7 @@ lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx) { auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h index 8128809..ba3099a 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h
@@ -1,9 +1,8 @@ //===-- SymbolFilePDB.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ class SymbolFilePDB : public lldb_private::SymbolFile { public: - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -40,9 +37,7 @@ static lldb_private::SymbolFile * CreateInstance(lldb_private::ObjectFile *obj_file); - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ SymbolFilePDB(lldb_private::ObjectFile *ofile); ~SymbolFilePDB() override; @@ -51,9 +46,7 @@ void InitializeObject() override; - //------------------------------------------------------------------ // Compile Unit function calls - //------------------------------------------------------------------ uint32_t GetNumCompileUnits() override; @@ -75,7 +68,7 @@ bool ParseImportedModules( const lldb_private::SymbolContext &sc, - std::vector<lldb_private::ConstString> &imported_modules) override; + std::vector<lldb_private::SourceModule> &imported_modules) override; size_t ParseBlocksRecursive(lldb_private::Function &func) override; @@ -111,7 +104,7 @@ lldb_private::SymbolContextList &sc_list) override; uint32_t - FindGlobalVariables(const lldb_private::ConstString &name, + FindGlobalVariables(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, lldb_private::VariableList &variables) override; @@ -121,7 +114,7 @@ lldb_private::VariableList &variables) override; uint32_t - FindFunctions(const lldb_private::ConstString &name, + FindFunctions(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, lldb::FunctionNameType name_type_mask, bool include_inlines, bool append, lldb_private::SymbolContextList &sc_list) override; @@ -137,7 +130,7 @@ void AddSymbols(lldb_private::Symtab &symtab) override; uint32_t - FindTypes(const lldb_private::ConstString &name, + FindTypes(lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, @@ -159,7 +152,7 @@ GetTypeSystemForLanguage(lldb::LanguageType language) override; lldb_private::CompilerDeclContext FindNamespace( - const lldb_private::ConstString &name, + lldb_private::ConstString name, const lldb_private::CompilerDeclContext *parent_decl_ctx) override; lldb_private::ConstString GetPluginName() override; @@ -253,7 +246,6 @@ std::unique_ptr<llvm::pdb::IPDBSession> m_session_up; std::unique_ptr<llvm::pdb::PDBSymbolExe> m_global_scope_up; uint32_t m_cached_compile_unit_count; - std::unique_ptr<lldb_private::CompilerDeclContext> m_tu_decl_ctx_up; lldb_private::UniqueCStringMap<uint32_t> m_func_full_names; lldb_private::UniqueCStringMap<uint32_t> m_func_base_names;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp b/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp index 08778bd..a1b21e5 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp
@@ -1,13 +1,13 @@ //===-- SymbolFileSymtab.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "SymbolFileSymtab.h" + #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Symbol/CompileUnit.h" @@ -20,6 +20,8 @@ #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Timer.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -62,11 +64,9 @@ if (m_obj_file) { const Symtab *symtab = m_obj_file->GetSymtab(); if (symtab) { - //---------------------------------------------------------------------- // The snippet of code below will get the indexes the module symbol table // entries that are code, data, or function related (debug info), sort // them by value (address) and dump the sorted symbols. - //---------------------------------------------------------------------- if (symtab->AppendSymbolIndexesWithType(eSymbolTypeSourceFile, m_source_indexes)) { abilities |= CompileUnits; @@ -124,9 +124,9 @@ const Symbol *cu_symbol = m_obj_file->GetSymtab()->SymbolAtIndex(m_source_indexes[idx]); if (cu_symbol) - cu_sp.reset(new CompileUnit(m_obj_file->GetModule(), NULL, + cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, cu_symbol->GetName().AsCString(), 0, - eLanguageTypeUnknown, eLazyBoolNo)); + eLanguageTypeUnknown, eLazyBoolNo); } return cu_sp; } @@ -139,8 +139,8 @@ size_t num_added = 0; // We must at least have a valid compile unit const Symtab *symtab = m_obj_file->GetSymtab(); - const Symbol *curr_symbol = NULL; - const Symbol *next_symbol = NULL; + const Symbol *curr_symbol = nullptr; + const Symbol *next_symbol = nullptr; // const char *prefix = m_obj_file->SymbolPrefix(); // if (prefix == NULL) // prefix == ""; @@ -188,10 +188,10 @@ LLDB_INVALID_UID, // We don't have any type info // for this function curr_symbol->GetMangled(), // Linker/mangled name - NULL, // no return type for a code symbol... + nullptr, // no return type for a code symbol... func_range)); // first address range - if (func_sp.get() != NULL) { + if (func_sp.get() != nullptr) { comp_unit.AddFunction(func_sp); ++num_added; } @@ -219,7 +219,7 @@ } bool SymbolFileSymtab::ParseImportedModules( - const SymbolContext &sc, std::vector<ConstString> &imported_modules) { + const SymbolContext &sc, std::vector<SourceModule> &imported_modules) { return false; } @@ -230,7 +230,7 @@ } Type *SymbolFileSymtab::ResolveTypeUID(lldb::user_id_t type_uid) { - return NULL; + return nullptr; } llvm::Optional<SymbolFile::ArrayInfo> @@ -246,7 +246,7 @@ uint32_t SymbolFileSymtab::ResolveSymbolContext(const Address &so_addr, SymbolContextItem resolve_scope, SymbolContext &sc) { - if (m_obj_file->GetSymtab() == NULL) + if (m_obj_file->GetSymtab() == nullptr) return 0; uint32_t resolved_flags = 0; @@ -259,9 +259,7 @@ return resolved_flags; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString SymbolFileSymtab::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.h b/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.h index e4ec7a1..bc9a531 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.h
@@ -1,9 +1,8 @@ //===-- SymbolFileSymtab.h --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,16 +17,12 @@ class SymbolFileSymtab : public lldb_private::SymbolFile { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ SymbolFileSymtab(lldb_private::ObjectFile *obj_file); ~SymbolFileSymtab() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -41,9 +36,7 @@ uint32_t CalculateAbilities() override; - //------------------------------------------------------------------ // Compile Unit function calls - //------------------------------------------------------------------ uint32_t GetNumCompileUnits() override; lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override; @@ -64,7 +57,7 @@ bool ParseImportedModules( const lldb_private::SymbolContext &sc, - std::vector<lldb_private::ConstString> &imported_modules) override; + std::vector<lldb_private::SourceModule> &imported_modules) override; size_t ParseBlocksRecursive(lldb_private::Function &func) override; @@ -86,9 +79,7 @@ lldb::TypeClass type_mask, lldb_private::TypeList &type_list) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp b/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp index 425b612..f279af6 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp
@@ -1,9 +1,8 @@ //===-- SymbolVendorELF.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,23 +15,20 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Host/Host.h" -#include "lldb/Host/Symbols.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" +#include "lldb/Target/Target.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // SymbolVendorELF constructor -//---------------------------------------------------------------------- SymbolVendorELF::SymbolVendorELF(const lldb::ModuleSP &module_sp) : SymbolVendor(module_sp) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SymbolVendorELF::~SymbolVendorELF() {} void SymbolVendorELF::Initialize() { @@ -54,31 +50,29 @@ "executables."; } -//---------------------------------------------------------------------- // CreateInstance // // Platforms can register a callback to use when creating symbol vendors to // allow for complex debug information file setups, and to also allow for // finding separate debug information files. -//---------------------------------------------------------------------- SymbolVendor * SymbolVendorELF::CreateInstance(const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm) { if (!module_sp) - return NULL; + return nullptr; ObjectFile *obj_file = module_sp->GetObjectFile(); if (!obj_file) - return NULL; + return nullptr; static ConstString obj_file_elf("elf"); ConstString obj_name = obj_file->GetPluginName(); if (obj_name != obj_file_elf) - return NULL; + return nullptr; - lldb_private::UUID uuid; - if (!obj_file->GetUUID(&uuid)) - return NULL; + lldb_private::UUID uuid = obj_file->GetUUID(); + if (!uuid) + return nullptr; // Get the .gnu_debuglink file (if specified). FileSpecList file_spec_list = obj_file->GetDebugSymbolFilePaths(); @@ -90,7 +84,7 @@ // If we have no debug symbol files, then nothing to do. if (file_spec_list.IsEmpty()) - return NULL; + return nullptr; static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer(func_cat, "SymbolVendorELF::CreateInstance (module = %s)", @@ -104,7 +98,9 @@ FileSystem::Instance().Resolve(module_spec.GetFileSpec()); module_spec.GetSymbolFileSpec() = fspec; module_spec.GetUUID() = uuid; - FileSpec dsym_fspec = Symbols::LocateExecutableSymbolFile(module_spec); + FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths(); + FileSpec dsym_fspec = + Symbols::LocateExecutableSymbolFile(module_spec, search_paths); if (dsym_fspec) { DataBufferSP dsym_file_data_sp; lldb::offset_t dsym_file_data_offset = 0; @@ -157,12 +153,10 @@ } } } - return NULL; + return nullptr; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString SymbolVendorELF::GetPluginName() { return GetPluginNameStatic(); } uint32_t SymbolVendorELF::GetPluginVersion() { return 1; }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.h b/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.h index b0d956e..0cd740d 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.h
@@ -1,9 +1,8 @@ //===-- SymbolVendorELF.h ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,16 +14,12 @@ class SymbolVendorELF : public lldb_private::SymbolVendor { public: - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ SymbolVendorELF(const lldb::ModuleSP &module_sp); ~SymbolVendorELF() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -37,9 +32,7 @@ CreateInstance(const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp b/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp index 169eed8..af9ea0a 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp +++ b/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp
@@ -1,9 +1,8 @@ //===-- SymbolVendorMacOSX.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,33 +15,29 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Host/Host.h" -#include "lldb/Host/Symbols.h" #include "lldb/Host/XML.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include "lldb/Symbol/ObjectFile.h" +#include "lldb/Target/Target.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // SymbolVendorMacOSX constructor -//---------------------------------------------------------------------- SymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp) : SymbolVendor(module_sp) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SymbolVendorMacOSX::~SymbolVendorMacOSX() {} static bool UUIDsMatch(Module *module, ObjectFile *ofile, lldb_private::Stream *feedback_strm) { if (module && ofile) { // Make sure the UUIDs match - lldb_private::UUID dsym_uuid; - - if (!ofile->GetUUID(&dsym_uuid)) { + lldb_private::UUID dsym_uuid = ofile->GetUUID(); + if (!dsym_uuid) { if (feedback_strm) { feedback_strm->PutCString( "warning: failed to get the uuid for object file: '"); @@ -91,13 +86,11 @@ "executables."; } -//---------------------------------------------------------------------- // CreateInstance // // Platforms can register a callback to use when creating symbol vendors to // allow for complex debug information file setups, and to also allow for // finding separate debug information files. -//---------------------------------------------------------------------- SymbolVendor * SymbolVendorMacOSX::CreateInstance(const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm) { @@ -144,7 +137,9 @@ ModuleSpec module_spec(file_spec, module_sp->GetArchitecture()); module_spec.GetUUID() = module_sp->GetUUID(); - dsym_fspec = Symbols::LocateExecutableSymbolFile(module_spec); + FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths(); + dsym_fspec = + Symbols::LocateExecutableSymbolFile(module_spec, search_paths); if (module_spec.GetSourceMappingList().GetSize()) module_sp->GetSourceMappingList().Append( module_spec.GetSourceMappingList(), true); @@ -163,8 +158,8 @@ char dsym_path[PATH_MAX]; if (module_sp->GetSourceMappingList().IsEmpty() && dsym_fspec.GetPath(dsym_path, sizeof(dsym_path))) { - lldb_private::UUID dsym_uuid; - if (dsym_objfile_sp->GetUUID(&dsym_uuid)) { + lldb_private::UUID dsym_uuid = dsym_objfile_sp->GetUUID(); + if (dsym_uuid) { std::string uuid_str = dsym_uuid.GetAsString(); if (!uuid_str.empty()) { char *resources = strstr(dsym_path, "/Contents/Resources/"); @@ -311,9 +306,7 @@ return symbol_vendor; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ ConstString SymbolVendorMacOSX::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h b/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h index 53b5291..01e33ff 100644 --- a/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h +++ b/src/llvm-project/lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h
@@ -1,9 +1,8 @@ //===-- SymbolVendorMacOSX.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -15,9 +14,7 @@ class SymbolVendorMacOSX : public lldb_private::SymbolVendor { public: - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -30,16 +27,12 @@ CreateInstance(const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm); - //------------------------------------------------------------------ // Constructors and Destructors - //------------------------------------------------------------------ SymbolVendorMacOSX(const lldb::ModuleSP &module_sp); virtual ~SymbolVendorMacOSX(); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ virtual lldb_private::ConstString GetPluginName(); virtual uint32_t GetPluginVersion();
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp index 43e4013..c97eb98 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp
@@ -1,10 +1,9 @@ //===-- AppleGetItemInfoHandler.cpp -------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -143,8 +142,8 @@ // First stage is to make the UtilityFunction to hold our injected // function: - if (!m_get_item_info_impl_code.get()) { - if (g_get_item_info_function_code != NULL) { + if (!m_get_item_info_impl_code) { + if (g_get_item_info_function_code != nullptr) { Status error; m_get_item_info_impl_code.reset( exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( @@ -334,7 +333,7 @@ options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetStopOthers(true); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetTryAllThreads(false); options.SetIsForUtilityExpr(true); thread.CalculateExecutionContext(exe_ctx);
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.h b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.h index ac3711e..318d674 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.h +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.h
@@ -1,9 +1,8 @@ //===-- AppleGetItemInfoHandler.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -56,38 +55,36 @@ : item_buffer_ptr(LLDB_INVALID_ADDRESS), item_buffer_size(0) {} }; - //---------------------------------------------------------- /// Get the information about a work item by calling /// __introspection_dispatch_queue_item_get_info. If there's a page of /// memory that needs to be freed, pass in the address and size and it will /// be freed before getting the list of queues. /// - /// @param [in] thread + /// \param [in] thread /// The thread to run this plan on. /// - /// @param [in] item + /// \param [in] item /// The introspection_dispatch_item_info_ref value for the item of /// interest. /// - /// @param [in] page_to_free + /// \param [in] page_to_free /// An address of an inferior process vm page that needs to be /// deallocated, /// LLDB_INVALID_ADDRESS if this is not needed. /// - /// @param [in] page_to_free_size + /// \param [in] page_to_free_size /// The size of the vm page that needs to be deallocated if an address was /// passed in to page_to_free. /// - /// @param [out] error + /// \param [out] error /// This object will be updated with the error status / error string from /// any failures encountered. /// - /// @returns + /// \returns /// The result of the inferior function call execution. If there was a /// failure of any kind while getting /// the information, the item_buffer_ptr value will be /// LLDB_INVALID_ADDRESS. - //---------------------------------------------------------- GetItemInfoReturnInfo GetItemInfo(Thread &thread, lldb::addr_t item, lldb::addr_t page_to_free, uint64_t page_to_free_size,
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp index 78e50e6..12fad7f 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp
@@ -1,10 +1,9 @@ //===-- AppleGetPendingItemsHandler.cpp -------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -147,8 +146,8 @@ // First stage is to make the ClangUtility to hold our injected function: - if (!m_get_pending_items_impl_code.get()) { - if (g_get_pending_items_function_code != NULL) { + if (!m_get_pending_items_impl_code) { + if (g_get_pending_items_function_code != nullptr) { Status error; m_get_pending_items_impl_code.reset( exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( @@ -343,12 +342,12 @@ options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetStopOthers(true); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetTryAllThreads(false); options.SetIsForUtilityExpr(true); thread.CalculateExecutionContext(exe_ctx); - if (get_pending_items_caller == NULL) { + if (get_pending_items_caller == nullptr) { error.SetErrorString("Unable to compile function to call " "__introspection_dispatch_queue_get_pending_items"); return return_value;
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.h b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.h index d35a72c..0780e3c 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.h +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.h
@@ -1,10 +1,9 @@ //===-- AppleGetPendingItemsHandler.h ----------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -61,37 +60,35 @@ count(0) {} }; - //---------------------------------------------------------- /// Get the list of pending items for a given queue via a call to /// __introspection_dispatch_queue_get_pending_items. If there's a page of /// memory that needs to be freed, pass in the address and size and it will /// be freed before getting the list of queues. /// - /// @param [in] thread + /// \param [in] thread /// The thread to run this plan on. /// - /// @param [in] queue + /// \param [in] queue /// The dispatch_queue_t value for the queue of interest. /// - /// @param [in] page_to_free + /// \param [in] page_to_free /// An address of an inferior process vm page that needs to be /// deallocated, /// LLDB_INVALID_ADDRESS if this is not needed. /// - /// @param [in] page_to_free_size + /// \param [in] page_to_free_size /// The size of the vm page that needs to be deallocated if an address was /// passed in to page_to_free. /// - /// @param [out] error + /// \param [out] error /// This object will be updated with the error status / error string from /// any failures encountered. /// - /// @returns + /// \returns /// The result of the inferior function call execution. If there was a /// failure of any kind while getting /// the information, the items_buffer_ptr value will be /// LLDB_INVALID_ADDRESS. - //---------------------------------------------------------- GetPendingItemsReturnInfo GetPendingItems(Thread &thread, lldb::addr_t queue, lldb::addr_t page_to_free, uint64_t page_to_free_size,
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp index 245ff67..e1dabae 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp
@@ -1,9 +1,8 @@ //===-- AppleGetQueuesHandler.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -158,8 +157,8 @@ // First stage is to make the ClangUtility to hold our injected function: - if (!m_get_queues_impl_code_up.get()) { - if (g_get_current_queues_function_code != NULL) { + if (!m_get_queues_impl_code_up) { + if (g_get_current_queues_function_code != nullptr) { Status error; m_get_queues_impl_code_up.reset( exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( @@ -336,7 +335,7 @@ FunctionCaller *get_queues_caller = m_get_queues_impl_code_up->GetFunctionCaller(); - if (get_queues_caller == NULL) { + if (get_queues_caller == nullptr) { error.SetErrorString( "Unable to get caller for call __introspection_dispatch_get_queues"); return return_value; @@ -348,7 +347,7 @@ options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetStopOthers(true); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetTryAllThreads(false); options.SetIsForUtilityExpr(true); thread.CalculateExecutionContext(exe_ctx);
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.h b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.h index 0d8e4dc..bd314f9 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.h +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.h
@@ -1,9 +1,8 @@ //===-- AppleGetQueuesHandler.h ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -57,34 +56,32 @@ count(0) {} }; - //---------------------------------------------------------- /// Get the list of queues that exist (with any active or pending items) via /// a call to introspection_get_dispatch_queues(). If there's a page of /// memory that needs to be freed, pass in the address and size and it will /// be freed before getting the list of queues. /// - /// @param [in] thread + /// \param [in] thread /// The thread to run this plan on. /// - /// @param [in] page_to_free + /// \param [in] page_to_free /// An address of an inferior process vm page that needs to be /// deallocated, /// LLDB_INVALID_ADDRESS if this is not needed. /// - /// @param [in] page_to_free_size + /// \param [in] page_to_free_size /// The size of the vm page that needs to be deallocated if an address was /// passed in to page_to_free. /// - /// @param [out] error + /// \param [out] error /// This object will be updated with the error status / error string from /// any failures encountered. /// - /// @returns + /// \returns /// The result of the inferior function call execution. If there was a /// failure of any kind while getting /// the information, the queues_buffer_ptr value will be /// LLDB_INVALID_ADDRESS. - //---------------------------------------------------------- GetQueuesReturnInfo GetCurrentQueues(Thread &thread, lldb::addr_t page_to_free, uint64_t page_to_free_size,
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp index ede8133..7d0cbc0 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp
@@ -1,10 +1,9 @@ //===-- AppleGetThreadItemInfoHandler.cpp -------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -153,9 +152,9 @@ // First stage is to make the ClangUtility to hold our injected function: - if (!m_get_thread_item_info_impl_code.get()) { + if (!m_get_thread_item_info_impl_code) { Status error; - if (g_get_thread_item_info_function_code != NULL) { + if (g_get_thread_item_info_function_code != nullptr) { m_get_thread_item_info_impl_code.reset( exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( g_get_thread_item_info_function_code, eLanguageTypeC, @@ -345,7 +344,7 @@ options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetStopOthers(true); - options.SetTimeout(std::chrono::milliseconds(500)); + options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); options.SetTryAllThreads(false); options.SetIsForUtilityExpr(true); thread.CalculateExecutionContext(exe_ctx);
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.h b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.h index 47e1961..b45314d 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.h +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.h
@@ -1,10 +1,9 @@ //===-- AppleGetThreadItemInfoHandler.h ----------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -57,34 +56,32 @@ : item_buffer_ptr(LLDB_INVALID_ADDRESS), item_buffer_size(0) {} }; - //---------------------------------------------------------- /// Get the information about a work item by calling /// __introspection_dispatch_thread_get_item_info. If there's a page of /// memory that needs to be freed, pass in the address and size and it will /// be freed before getting the list of queues. /// - /// @param [in] thread_id + /// \param [in] thread_id /// The thread to get the extended backtrace for. /// - /// @param [in] page_to_free + /// \param [in] page_to_free /// An address of an inferior process vm page that needs to be /// deallocated, /// LLDB_INVALID_ADDRESS if this is not needed. /// - /// @param [in] page_to_free_size + /// \param [in] page_to_free_size /// The size of the vm page that needs to be deallocated if an address was /// passed in to page_to_free. /// - /// @param [out] error + /// \param [out] error /// This object will be updated with the error status / error string from /// any failures encountered. /// - /// @returns + /// \returns /// The result of the inferior function call execution. If there was a /// failure of any kind while getting /// the information, the item_buffer_ptr value will be /// LLDB_INVALID_ADDRESS. - //---------------------------------------------------------- GetThreadItemInfoReturnInfo GetThreadItemInfo(Thread &thread, lldb::tid_t thread_id, lldb::addr_t page_to_free,
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp index e61f04e..dfcc6ac 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp
@@ -1,9 +1,8 @@ //===-- SystemRuntimeMacOSX.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,14 +29,14 @@ #include "SystemRuntimeMacOSX.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Create an instance of this class. This function is filled into the plugin // info class that gets handed out by the plugin factory and allows the lldb to // instantiate an instance of this class. -//---------------------------------------------------------------------- SystemRuntime *SystemRuntimeMacOSX::CreateInstance(Process *process) { bool create = false; if (!create) { @@ -71,12 +70,10 @@ if (create) return new SystemRuntimeMacOSX(process); - return NULL; + return nullptr; } -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- SystemRuntimeMacOSX::SystemRuntimeMacOSX(Process *process) : SystemRuntime(process), m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(), m_get_queues_handler(process), m_get_pending_items_handler(process), @@ -91,9 +88,7 @@ m_dispatch_voucher_offsets_addr(LLDB_INVALID_ADDRESS), m_libdispatch_voucher_offsets() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SystemRuntimeMacOSX::~SystemRuntimeMacOSX() { Clear(true); } void SystemRuntimeMacOSX::Detach() { @@ -103,9 +98,7 @@ m_get_thread_item_info_handler.Detach(); } -//---------------------------------------------------------------------- // Clear out the state of this class. -//---------------------------------------------------------------------- void SystemRuntimeMacOSX::Clear(bool clear_process) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -113,7 +106,7 @@ m_process->ClearBreakpointSiteByID(m_break_id); if (clear_process) - m_process = NULL; + m_process = nullptr; m_break_id = LLDB_INVALID_BREAK_ID; } @@ -273,7 +266,7 @@ static ConstString g_dispatch_queue_offsets_symbol_name( "dispatch_queue_offsets"); - const Symbol *dispatch_queue_offsets_symbol = NULL; + const Symbol *dispatch_queue_offsets_symbol = nullptr; // libdispatch symbols were in libSystem.B.dylib up through Mac OS X 10.6 // ("Snow Leopard") @@ -286,7 +279,7 @@ // libdispatch symbols are in their own dylib as of Mac OS X 10.7 ("Lion") // and later - if (dispatch_queue_offsets_symbol == NULL) { + if (dispatch_queue_offsets_symbol == nullptr) { ModuleSpec libdispatch_module_spec(FileSpec("libdispatch.dylib")); module_sp = m_process->GetTarget().GetImages().FindFirstModule( libdispatch_module_spec); @@ -329,7 +322,7 @@ static ConstString g_libpthread_layout_offsets_symbol_name( "pthread_layout_offsets"); - const Symbol *libpthread_layout_offsets_symbol = NULL; + const Symbol *libpthread_layout_offsets_symbol = nullptr; ModuleSpec libpthread_module_spec(FileSpec("libsystem_pthread.dylib")); ModuleSP module_sp(m_process->GetTarget().GetImages().FindFirstModule( @@ -377,7 +370,7 @@ static ConstString g_libdispatch_tsd_indexes_symbol_name( "dispatch_tsd_indexes"); - const Symbol *libdispatch_tsd_indexes_symbol = NULL; + const Symbol *libdispatch_tsd_indexes_symbol = nullptr; ModuleSpec libpthread_module_spec(FileSpec("libdispatch.dylib")); ModuleSP module_sp(m_process->GetTarget().GetImages().FindFirstModule( @@ -461,8 +454,7 @@ ThreadSP SystemRuntimeMacOSX::GetExtendedBacktraceThread(ThreadSP real_thread, ConstString type) { ThreadSP originating_thread_sp; - if (BacktraceRecordingHeadersInitialized() && - type == ConstString("libdispatch")) { + if (BacktraceRecordingHeadersInitialized() && type == "libdispatch") { Status error; // real_thread is either an actual, live thread (in which case we need to @@ -493,12 +485,8 @@ m_process->GetByteOrder(), m_process->GetAddressByteSize()); ItemInfo item = ExtractItemInfoFromBuffer(extractor); - bool stop_id_is_valid = true; - if (item.stop_id == 0) - stop_id_is_valid = false; - originating_thread_sp.reset(new HistoryThread( - *m_process, item.enqueuing_thread_id, item.enqueuing_callstack, - item.stop_id, stop_id_is_valid)); + originating_thread_sp = std::make_shared<HistoryThread>( + *m_process, item.enqueuing_thread_id, item.enqueuing_callstack); originating_thread_sp->SetExtendedBacktraceToken( item.item_that_enqueued_this); originating_thread_sp->SetQueueName( @@ -538,12 +526,8 @@ m_process->GetByteOrder(), m_process->GetAddressByteSize()); ItemInfo item = ExtractItemInfoFromBuffer(extractor); - bool stop_id_is_valid = true; - if (item.stop_id == 0) - stop_id_is_valid = false; - return_thread_sp.reset(new HistoryThread( - *m_process, item.enqueuing_thread_id, item.enqueuing_callstack, - item.stop_id, stop_id_is_valid)); + return_thread_sp = std::make_shared<HistoryThread>( + *m_process, item.enqueuing_thread_id, item.enqueuing_callstack); return_thread_sp->SetExtendedBacktraceToken(item.item_that_enqueued_this); return_thread_sp->SetQueueName(item.enqueuing_queue_label.c_str()); return_thread_sp->SetQueueID(item.enqueuing_queue_serialnum); @@ -561,17 +545,12 @@ SystemRuntimeMacOSX::GetExtendedBacktraceForQueueItem(QueueItemSP queue_item_sp, ConstString type) { ThreadSP extended_thread_sp; - if (type != ConstString("libdispatch")) + if (type != "libdispatch") return extended_thread_sp; - bool stop_id_is_valid = true; - if (queue_item_sp->GetStopID() == 0) - stop_id_is_valid = false; - - extended_thread_sp.reset( - new HistoryThread(*m_process, queue_item_sp->GetEnqueueingThreadID(), - queue_item_sp->GetEnqueueingBacktrace(), - queue_item_sp->GetStopID(), stop_id_is_valid)); + extended_thread_sp = std::make_shared<HistoryThread>( + *m_process, queue_item_sp->GetEnqueueingThreadID(), + queue_item_sp->GetEnqueueingBacktrace()); extended_thread_sp->SetExtendedBacktraceToken( queue_item_sp->GetItemThatEnqueuedThis()); extended_thread_sp->SetQueueName(queue_item_sp->GetQueueLabel().c_str()); @@ -734,7 +713,8 @@ for (ThreadSP thread_sp : m_process->Threads()) { if (thread_sp->GetAssociatedWithLibdispatchQueue() != eLazyBoolNo) { if (thread_sp->GetQueueID() != LLDB_INVALID_QUEUE_ID) { - if (queue_list.FindQueueByID(thread_sp->GetQueueID()).get() == NULL) { + if (queue_list.FindQueueByID(thread_sp->GetQueueID()).get() == + nullptr) { QueueSP queue_sp(new Queue(m_process->shared_from_this(), thread_sp->GetQueueID(), thread_sp->GetQueueName())); @@ -941,7 +921,7 @@ offset = start_of_this_item + m_lib_backtrace_recording_info.queue_info_data_offset; const char *queue_label = extractor.GetCStr(&offset); - if (queue_label == NULL) + if (queue_label == nullptr) queue_label = ""; offset_t start_of_next_item = start_of_this_item + offset_to_next; @@ -1011,9 +991,7 @@ return "System runtime plugin for Mac OS X native libraries."; } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString SystemRuntimeMacOSX::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h index 5fa78ce..d6a18e2 100644 --- a/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h +++ b/src/llvm-project/lldb/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h
@@ -1,9 +1,8 @@ //===-- SystemRuntimeMacOSX.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,9 +34,7 @@ ~SystemRuntimeMacOSX() override; - //------------------------------------------------------------------ // Static Functions - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -49,9 +46,7 @@ static lldb_private::SystemRuntime * CreateInstance(lldb_private::Process *process); - //------------------------------------------------------------------ // instance methods - //------------------------------------------------------------------ void Clear(bool clear_process); @@ -102,9 +97,7 @@ bool SafeToCallFunctionsOnThisThread(lldb::ThreadSP thread_sp) override; - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override;
diff --git a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp index b70c2c4..4aa9fb6 100644 --- a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp +++ b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp
@@ -1,9 +1,8 @@ //===-- UnwindAssemblyInstEmulation.cpp --------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,9 +28,7 @@ using namespace lldb; using namespace lldb_private; -//----------------------------------------------------------------------------------------------- // UnwindAssemblyInstEmulation method definitions -//----------------------------------------------------------------------------------------------- bool UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly( AddressRange &range, Thread &thread, UnwindPlan &unwind_plan) { @@ -57,11 +54,11 @@ return false; if (range.GetByteSize() > 0 && range.GetBaseAddress().IsValid() && - m_inst_emulator_ap.get()) { + m_inst_emulator_up.get()) { // The instruction emulation subclass setup the unwind plan for the first // instruction. - m_inst_emulator_ap->CreateFunctionEntryUnwind(unwind_plan); + m_inst_emulator_up->CreateFunctionEntryUnwind(unwind_plan); // CreateFunctionEntryUnwind should have created the first row. If it // doesn't, then we are done. @@ -70,8 +67,8 @@ const bool prefer_file_cache = true; DisassemblerSP disasm_sp(Disassembler::DisassembleBytes( - m_arch, NULL, NULL, range.GetBaseAddress(), opcode_data, opcode_size, - 99999, prefer_file_cache)); + m_arch, nullptr, nullptr, range.GetBaseAddress(), opcode_data, + opcode_size, 99999, prefer_file_cache)); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND)); @@ -83,7 +80,7 @@ const uint32_t addr_byte_size = m_arch.GetAddressByteSize(); const bool show_address = true; const bool show_bytes = true; - m_inst_emulator_ap->GetRegisterInfo(unwind_plan.GetRegisterKind(), + m_inst_emulator_up->GetRegisterInfo(unwind_plan.GetRegisterKind(), unwind_plan.GetInitialCFARegister(), m_cfa_reg_info); @@ -129,14 +126,14 @@ // cache the pc register number (in whatever register numbering this // UnwindPlan uses) for quick reference during instruction parsing. RegisterInfo pc_reg_info; - m_inst_emulator_ap->GetRegisterInfo( + m_inst_emulator_up->GetRegisterInfo( eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc_reg_info); // cache the return address register number (in whatever register // numbering this UnwindPlan uses) for quick reference during // instruction parsing. RegisterInfo ra_reg_info; - m_inst_emulator_ap->GetRegisterInfo( + m_inst_emulator_up->GetRegisterInfo( eRegisterKindGeneric, LLDB_REGNUM_GENERIC_RA, ra_reg_info); // The architecture dependent condition code of the last processed @@ -170,12 +167,12 @@ m_register_values = it->second.second; } - m_inst_emulator_ap->SetInstruction(inst->GetOpcode(), + m_inst_emulator_up->SetInstruction(inst->GetOpcode(), inst->GetAddress(), nullptr); if (last_condition != - m_inst_emulator_ap->GetInstructionCondition()) { - if (m_inst_emulator_ap->GetInstructionCondition() != + m_inst_emulator_up->GetInstructionCondition()) { + if (m_inst_emulator_up->GetInstructionCondition() != EmulateInstruction::UnconditionalCondition && saved_unwind_states.count(current_offset) == 0) { // If we don't have a saved row for the current offset then @@ -216,13 +213,13 @@ lldb_private::FormatEntity::Entry format; FormatEntity::Parse("${frame.pc}: ", format); inst->Dump(&strm, inst_list.GetMaxOpcocdeByteSize(), show_address, - show_bytes, NULL, NULL, NULL, &format, 0); + show_bytes, nullptr, nullptr, nullptr, &format, 0); log->PutString(strm.GetString()); } - last_condition = m_inst_emulator_ap->GetInstructionCondition(); + last_condition = m_inst_emulator_up->GetInstructionCondition(); - m_inst_emulator_ap->EvaluateInstruction( + m_inst_emulator_up->EvaluateInstruction( eEmulateInstructionOptionIgnoreConditions); // If the current instruction is a branch forward then save the @@ -297,18 +294,16 @@ UnwindAssembly * UnwindAssemblyInstEmulation::CreateInstance(const ArchSpec &arch) { - std::unique_ptr<EmulateInstruction> inst_emulator_ap( + std::unique_ptr<EmulateInstruction> inst_emulator_up( EmulateInstruction::FindPlugin(arch, eInstructionTypePrologueEpilogue, - NULL)); + nullptr)); // Make sure that all prologue instructions are handled - if (inst_emulator_ap.get()) - return new UnwindAssemblyInstEmulation(arch, inst_emulator_ap.release()); - return NULL; + if (inst_emulator_up) + return new UnwindAssemblyInstEmulation(arch, inst_emulator_up.release()); + return nullptr; } -//------------------------------------------------------------------ // PluginInterface protocol in UnwindAssemblyParser_x86 -//------------------------------------------------------------------ ConstString UnwindAssemblyInstEmulation::GetPluginName() { return GetPluginNameStatic(); }
diff --git a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h index 5539b52..9125bd5 100644 --- a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h +++ b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h
@@ -1,9 +1,8 @@ //===-- UnwindAssemblyInstEmulation.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -48,9 +47,7 @@ static lldb_private::UnwindAssembly * CreateInstance(const lldb_private::ArchSpec &arch); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ static void Initialize(); static void Terminate(); @@ -67,14 +64,14 @@ // Call CreateInstance to get an instance of this class UnwindAssemblyInstEmulation(const lldb_private::ArchSpec &arch, lldb_private::EmulateInstruction *inst_emulator) - : UnwindAssembly(arch), m_inst_emulator_ap(inst_emulator), - m_range_ptr(NULL), m_unwind_plan_ptr(NULL), m_curr_row(), + : UnwindAssembly(arch), m_inst_emulator_up(inst_emulator), + m_range_ptr(nullptr), m_unwind_plan_ptr(nullptr), m_curr_row(), m_cfa_reg_info(), m_fp_is_cfa(false), m_register_values(), m_pushed_regs(), m_curr_row_modified(false), m_forward_branch_offset(0) { - if (m_inst_emulator_ap.get()) { - m_inst_emulator_ap->SetBaton(this); - m_inst_emulator_ap->SetCallbacks(ReadMemory, WriteMemory, ReadRegister, + if (m_inst_emulator_up.get()) { + m_inst_emulator_up->SetBaton(this); + m_inst_emulator_up->SetCallbacks(ReadMemory, WriteMemory, ReadRegister, WriteRegister); } } @@ -129,7 +126,7 @@ bool GetRegisterValue(const lldb_private::RegisterInfo ®_info, lldb_private::RegisterValue ®_value); - std::unique_ptr<lldb_private::EmulateInstruction> m_inst_emulator_ap; + std::unique_ptr<lldb_private::EmulateInstruction> m_inst_emulator_up; lldb_private::AddressRange *m_range_ptr; lldb_private::UnwindPlan *m_unwind_plan_ptr; lldb_private::UnwindPlan::RowSP m_curr_row;
diff --git a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp index 04f9cbb..ce168f0 100644 --- a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp +++ b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp
@@ -1,9 +1,8 @@ //===-- UnwindAssembly-x86.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,9 +30,7 @@ using namespace lldb; using namespace lldb_private; -//----------------------------------------------------------------------------------------------- // UnwindAssemblyParser_x86 method definitions -//----------------------------------------------------------------------------------------------- UnwindAssembly_x86::UnwindAssembly_x86(const ArchSpec &arch) : lldb_private::UnwindAssembly(arch), @@ -242,12 +239,10 @@ const llvm::Triple::ArchType cpu = arch.GetMachine(); if (cpu == llvm::Triple::x86 || cpu == llvm::Triple::x86_64) return new UnwindAssembly_x86(arch); - return NULL; + return nullptr; } -//------------------------------------------------------------------ // PluginInterface protocol in UnwindAssemblyParser_x86 -//------------------------------------------------------------------ ConstString UnwindAssembly_x86::GetPluginName() { return GetPluginNameStatic();
diff --git a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h index c4052a8..7c198bb 100644 --- a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h +++ b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h
@@ -1,9 +1,8 @@ //===-- UnwindAssembly-x86.h ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -42,9 +41,7 @@ static lldb_private::UnwindAssembly * CreateInstance(const lldb_private::ArchSpec &arch); - //------------------------------------------------------------------ // PluginInterface protocol - //------------------------------------------------------------------ static void Initialize(); static void Terminate();
diff --git a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp index f8e7020..43041ca 100644 --- a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp +++ b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp
@@ -1,14 +1,15 @@ //===-- x86AssemblyInspectionEngine.cpp -------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 "x86AssemblyInspectionEngine.h" +#include <memory> + #include "llvm-c/Disassembler.h" #include "lldb/Core/Address.h" @@ -365,8 +366,8 @@ uint8_t *p = m_cur_insn; int regno_prefix_bit = 0; // If we have a rex prefix byte, check to see if a B bit is set - if (m_wordsize == 8 && *p == 0x41) { - regno_prefix_bit = 1 << 3; + if (m_wordsize == 8 && (*p & 0xfe) == 0x40) { + regno_prefix_bit = (*p & 1) << 3; p++; } if (*p >= 0x50 && *p <= 0x57) { @@ -563,8 +564,8 @@ uint8_t *p = m_cur_insn; int regno_prefix_bit = 0; // If we have a rex prefix byte, check to see if a B bit is set - if (m_wordsize == 8 && *p == 0x41) { - regno_prefix_bit = 1 << 3; + if (m_wordsize == 8 && (*p & 0xfe) == 0x40) { + regno_prefix_bit = (*p & 1) << 3; p++; } if (*p >= 0x58 && *p <= 0x5f) { @@ -666,10 +667,207 @@ return false; } -// ret [0xc9] or [0xc2 imm8] or [0xca imm8] +// Returns true if this is a jmp instruction where we can't +// know the destination address statically. +// +// ff e0 jmpq *%rax +// ff e1 jmpq *%rcx +// ff 60 28 jmpq *0x28(%rax) +// ff 60 60 jmpq *0x60(%rax) +bool x86AssemblyInspectionEngine::jmp_to_reg_p() { + if (*m_cur_insn != 0xff) + return false; + + // The second byte is a ModR/M /4 byte, strip off the registers + uint8_t second_byte_sans_reg = *(m_cur_insn + 1) & ~7; + + // Don't handle 0x24 disp32, because the target address is + // knowable statically - pc_rel_branch_or_jump_p() will + // return the target address. + + // [reg] + if (second_byte_sans_reg == 0x20) + return true; + + // [reg]+disp8 + if (second_byte_sans_reg == 0x60) + return true; + + // [reg]+disp32 + if (second_byte_sans_reg == 0xa0) + return true; + + // reg + if (second_byte_sans_reg == 0xe0) + return true; + + // disp32 + // jumps to an address stored in memory, the value can't be cached + // in an unwind plan. + if (second_byte_sans_reg == 0x24) + return true; + + // use SIB byte + // ff 24 fe jmpq *(%rsi,%rdi,8) + if (second_byte_sans_reg == 0x24) + return true; + + return false; +} + +// Detect branches to fixed pc-relative offsets. +// Returns the offset from the address of the next instruction +// that may be branch/jumped to. +// +// Cannot determine the offset of a JMP that jumps to the address in +// a register ("jmpq *%rax") or offset from a register value +// ("jmpq *0x28(%rax)"), this method will return false on those +// instructions. +// +// These instructions all end in either a relative 8/16/32 bit value +// depending on the instruction and the current execution mode of the +// inferior process. Once we know the size of the opcode instruction, +// we can use the total instruction length to determine the size of +// the relative offset without having to compute it correctly. + +bool x86AssemblyInspectionEngine::pc_rel_branch_or_jump_p ( + const int instruction_length, int &offset) +{ + int opcode_size = 0; + + uint8_t b1 = m_cur_insn[0]; + + switch (b1) { + case 0x77: // JA/JNBE rel8 + case 0x73: // JAE/JNB/JNC rel8 + case 0x72: // JB/JC/JNAE rel8 + case 0x76: // JBE/JNA rel8 + case 0xe3: // JCXZ/JECXZ/JRCXZ rel8 + case 0x74: // JE/JZ rel8 + case 0x7f: // JG/JNLE rel8 + case 0x7d: // JGE/JNL rel8 + case 0x7c: // JL/JNGE rel8 + case 0x7e: // JNG/JLE rel8 + case 0x71: // JNO rel8 + case 0x7b: // JNP/JPO rel8 + case 0x79: // JNS rel8 + case 0x75: // JNE/JNZ rel8 + case 0x70: // JO rel8 + case 0x7a: // JP/JPE rel8 + case 0x78: // JS rel8 + case 0xeb: // JMP rel8 + case 0xe9: // JMP rel16/rel32 + opcode_size = 1; + break; + default: + break; + } + if (b1 == 0x0f && opcode_size == 0) { + uint8_t b2 = m_cur_insn[1]; + switch (b2) { + case 0x87: // JA/JNBE rel16/rel32 + case 0x86: // JBE/JNA rel16/rel32 + case 0x84: // JE/JZ rel16/rel32 + case 0x8f: // JG/JNLE rel16/rel32 + case 0x8d: // JNL/JGE rel16/rel32 + case 0x8e: // JLE rel16/rel32 + case 0x82: // JB/JC/JNAE rel16/rel32 + case 0x83: // JAE/JNB/JNC rel16/rel32 + case 0x85: // JNE/JNZ rel16/rel32 + case 0x8c: // JL/JNGE rel16/rel32 + case 0x81: // JNO rel16/rel32 + case 0x8b: // JNP/JPO rel16/rel32 + case 0x89: // JNS rel16/rel32 + case 0x80: // JO rel16/rel32 + case 0x8a: // JP rel16/rel32 + case 0x88: // JS rel16/rel32 + opcode_size = 2; + break; + default: + break; + } + } + + if (opcode_size == 0) + return false; + + offset = 0; + if (instruction_length - opcode_size == 1) { + int8_t rel8 = (int8_t) *(m_cur_insn + opcode_size); + offset = rel8; + } else if (instruction_length - opcode_size == 2) { + int16_t rel16 = extract_2_signed (m_cur_insn + opcode_size); + offset = rel16; + } else if (instruction_length - opcode_size == 4) { + int32_t rel32 = extract_4_signed (m_cur_insn + opcode_size); + offset = rel32; + } else { + return false; + } + return true; +} + +// Returns true if this instruction is a intra-function branch or jump - +// a branch/jump within the bounds of this same function. +// Cannot predict where a jump through a register value ("jmpq *%rax") +// will go, so it will return false on that instruction. +bool x86AssemblyInspectionEngine::local_branch_p ( + const addr_t current_func_text_offset, + const AddressRange &func_range, + const int instruction_length, + addr_t &target_insn_offset) { + int offset; + if (pc_rel_branch_or_jump_p (instruction_length, offset) && offset != 0) { + addr_t next_pc_value = current_func_text_offset + instruction_length; + if (offset < 0 && addr_t(-offset) > current_func_text_offset) { + // Branch target is before the start of this function + return false; + } + if (offset + next_pc_value > func_range.GetByteSize()) { + // Branch targets outside this function's bounds + return false; + } + // This instruction branches to target_insn_offset (byte offset into the function) + target_insn_offset = next_pc_value + offset; + return true; + } + return false; +} + +// Returns true if this instruction is a inter-function branch or jump - a +// branch/jump to another function. +// Cannot predict where a jump through a register value ("jmpq *%rax") +// will go, so it will return false on that instruction. +bool x86AssemblyInspectionEngine::non_local_branch_p ( + const addr_t current_func_text_offset, + const AddressRange &func_range, + const int instruction_length) { + int offset; + addr_t target_insn_offset; + if (pc_rel_branch_or_jump_p (instruction_length, offset)) { + return !local_branch_p(current_func_text_offset,func_range,instruction_length,target_insn_offset); + } + return false; +} + +// ret [0xc3] or [0xcb] or [0xc2 imm16] or [0xca imm16] bool x86AssemblyInspectionEngine::ret_pattern_p() { uint8_t *p = m_cur_insn; - return *p == 0xc9 || *p == 0xc2 || *p == 0xca || *p == 0xc3; + return *p == 0xc3 || *p == 0xc2 || *p == 0xca || *p == 0xcb; +} + +uint16_t x86AssemblyInspectionEngine::extract_2(uint8_t *b) { + uint16_t v = 0; + for (int i = 1; i >= 0; i--) + v = (v << 8) | b[i]; + return v; +} + +int16_t x86AssemblyInspectionEngine::extract_2_signed(uint8_t *b) { + int16_t v = 0; + for (int i = 1; i >= 0; i--) + v = (v << 8) | b[i]; + return v; } uint32_t x86AssemblyInspectionEngine::extract_4(uint8_t *b) { @@ -679,6 +877,14 @@ return v; } +int32_t x86AssemblyInspectionEngine::extract_4_signed(uint8_t *b) { + int32_t v = 0; + for (int i = 3; i >= 0; i--) + v = (v << 8) | b[i]; + return v; +} + + bool x86AssemblyInspectionEngine::instruction_length(uint8_t *insn_p, int &length, uint32_t buffer_remaining_bytes) { @@ -704,7 +910,6 @@ return true; } return false; - return false; } bool x86AssemblyInspectionEngine::GetNonCallSiteUnwindPlanFromAssembly( @@ -1028,25 +1233,47 @@ } } - else if (ret_pattern_p() && prologue_completed_row.get()) { - // Reinstate the saved prologue setup for any instructions that come - // after the ret instruction + else if (prologue_completed_row.get() && + (ret_pattern_p() || + non_local_branch_p (current_func_text_offset, func_range, insn_len) || + jmp_to_reg_p())) { + // Check if the current instruction is the end of an epilogue sequence, + // and if so, re-instate the prologue-completed unwind state. - UnwindPlan::Row *newrow = new UnwindPlan::Row; - *newrow = *prologue_completed_row.get(); - row.reset(newrow); - current_sp_bytes_offset_from_fa = - prologue_completed_sp_bytes_offset_from_cfa; - is_aligned = prologue_completed_is_aligned; + // The current instruction is a branch/jump outside this function, + // a ret, or a jump through a register value which we cannot + // determine the effcts of. Verify that the stack frame state + // has been unwound to the same as it was at function entry to avoid + // mis-identifying a JMP instruction as an epilogue. + UnwindPlan::Row::RegisterLocation sp, pc; + if (row->GetRegisterInfo(m_lldb_sp_regnum, sp) && + row->GetRegisterInfo(m_lldb_ip_regnum, pc)) { + // Any ret instruction variant is definitely indicative of an + // epilogue; for other insn patterns verify that we're back to + // the original unwind state. + if (ret_pattern_p() || + (sp.IsCFAPlusOffset() && sp.GetOffset() == 0 && + pc.IsAtCFAPlusOffset() && pc.GetOffset() == -m_wordsize)) { + // Reinstate the saved prologue setup for any instructions that come + // after the epilogue - saved_registers.clear(); - saved_registers.resize(prologue_completed_saved_registers.size(), false); - for (size_t i = 0; i < prologue_completed_saved_registers.size(); ++i) { - saved_registers[i] = prologue_completed_saved_registers[i]; + UnwindPlan::Row *newrow = new UnwindPlan::Row; + *newrow = *prologue_completed_row.get(); + row.reset(newrow); + current_sp_bytes_offset_from_fa = + prologue_completed_sp_bytes_offset_from_cfa; + is_aligned = prologue_completed_is_aligned; + + saved_registers.clear(); + saved_registers.resize(prologue_completed_saved_registers.size(), false); + for (size_t i = 0; i < prologue_completed_saved_registers.size(); ++i) { + saved_registers[i] = prologue_completed_saved_registers[i]; + } + + in_epilogue = true; + row_updated = true; + } } - - in_epilogue = true; - row_updated = true; } // call next instruction @@ -1173,7 +1400,7 @@ *new_row = *original_last_row; new_row->SetOffset(offset); unwind_plan.AppendRow(new_row); - row.reset(new UnwindPlan::Row()); + row = std::make_shared<UnwindPlan::Row>(); *row = *new_row; reinstate_unwind_state = false; unwind_plan_updated = true;
diff --git a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h index e02b510..680598a 100644 --- a/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h +++ b/src/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h
@@ -1,9 +1,8 @@ //===-- x86AssemblyInspectionEngine.h ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -115,7 +114,19 @@ bool call_next_insn_pattern_p(); bool mov_reg_to_local_stack_frame_p(int ®no, int &rbp_offset); bool ret_pattern_p(); + bool jmp_to_reg_p(); + bool pc_rel_branch_or_jump_p (const int instruction_length, int &offset); + bool non_local_branch_p (const lldb::addr_t current_func_text_offset, + const lldb_private::AddressRange &func_range, + const int instruction_length); + bool local_branch_p (const lldb::addr_t current_func_text_offset, + const lldb_private::AddressRange &func_range, + const int instruction_length, + lldb::addr_t &target_insn_offset); + uint16_t extract_2(uint8_t *b); + int16_t extract_2_signed(uint8_t *b); uint32_t extract_4(uint8_t *b); + int32_t extract_4_signed(uint8_t *b); bool instruction_length(uint8_t *insn, int &length, uint32_t buffer_remaining_bytes);
diff --git a/src/llvm-project/lldb/source/Symbol/ArmUnwindInfo.cpp b/src/llvm-project/lldb/source/Symbol/ArmUnwindInfo.cpp index 08f2807..b9fd84b 100644 --- a/src/llvm-project/lldb/source/Symbol/ArmUnwindInfo.cpp +++ b/src/llvm-project/lldb/source/Symbol/ArmUnwindInfo.cpp
@@ -1,9 +1,8 @@ //===-- ArmUnwindInfo.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -305,7 +304,7 @@ // 11001yyy // Spare (yyy != 000, 001) return false; - } else if ((byte1 & 0xf8) == 0xc0) { + } else if ((byte1 & 0xf8) == 0xd0) { // 11010nnn // Pop VFP double-precision registers D[8]-D[8+nnn] saved (as if) by // FSTMFDD (see remark d)
diff --git a/src/llvm-project/lldb/source/Symbol/Block.cpp b/src/llvm-project/lldb/source/Symbol/Block.cpp index d034235..6fe6170 100644 --- a/src/llvm-project/lldb/source/Symbol/Block.cpp +++ b/src/llvm-project/lldb/source/Symbol/Block.cpp
@@ -1,9 +1,8 @@ //===-- Block.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,6 +16,8 @@ #include "lldb/Symbol/VariableList.h" #include "lldb/Utility/Log.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -211,6 +212,21 @@ return nullptr; } +Block *Block::GetContainingInlinedBlockWithCallSite( + const Declaration &find_call_site) { + Block *inlined_block = GetContainingInlinedBlock(); + + while (inlined_block) { + const auto *function_info = inlined_block->GetInlinedFunctionInfo(); + + if (function_info && + function_info->GetCallSite().FileAndLineEqual(find_call_site)) + return inlined_block; + inlined_block = inlined_block->GetInlinedParent(); + } + return nullptr; +} + bool Block::GetRangeContainingOffset(const addr_t offset, Range &range) { const Range *range_ptr = m_ranges.FindEntryThatContains(offset); if (range_ptr) { @@ -364,8 +380,8 @@ void Block::SetInlinedFunctionInfo(const char *name, const char *mangled, const Declaration *decl_ptr, const Declaration *call_decl_ptr) { - m_inlineInfoSP.reset( - new InlineFunctionInfo(name, mangled, decl_ptr, call_decl_ptr)); + m_inlineInfoSP = std::make_shared<InlineFunctionInfo>(name, mangled, decl_ptr, + call_decl_ptr); } VariableListSP Block::GetBlockVariableList(bool can_create) {
diff --git a/src/llvm-project/lldb/source/Symbol/CMakeLists.txt b/src/llvm-project/lldb/source/Symbol/CMakeLists.txt index d1b4390..4b922c2 100644 --- a/src/llvm-project/lldb/source/Symbol/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Symbol/CMakeLists.txt
@@ -1,3 +1,9 @@ +set(LLVM_OPTIONAL_SOURCES LocateSymbolFileMacOSX.cpp) + +if (CMAKE_SYSTEM_NAME MATCHES "Darwin") + set(PLATFORM_SOURCES LocateSymbolFileMacOSX.cpp) +endif() + add_lldb_library(lldbSymbol ArmUnwindInfo.cpp Block.cpp @@ -6,20 +12,23 @@ ClangExternalASTSourceCallbacks.cpp ClangExternalASTSourceCommon.cpp ClangUtil.cpp + CompactUnwindInfo.cpp + CompileUnit.cpp CompilerDecl.cpp CompilerDeclContext.cpp CompilerType.cpp - CompileUnit.cpp - CompactUnwindInfo.cpp + CxxModuleHandler.cpp + DWARFCallFrameInfo.cpp DebugMacros.cpp Declaration.cpp - DWARFCallFrameInfo.cpp - Function.cpp + DeclVendor.cpp FuncUnwinders.cpp + Function.cpp LineEntry.cpp LineTable.cpp + LocateSymbolFile.cpp ObjectFile.cpp - RustASTContext.cpp + PostfixExpression.cpp Symbol.cpp SymbolContext.cpp SymbolFile.cpp @@ -35,6 +44,8 @@ VariableList.cpp VerifyDecl.cpp + ${PLATFORM_SOURCES} + LINK_LIBS clangAST clangBasic @@ -47,8 +58,8 @@ lldbPluginExpressionParserClang lldbPluginSymbolFileDWARF lldbPluginSymbolFilePDB - lldbPluginCPlusPlusLanguage lldbPluginObjCLanguage + lldbPluginObjCRuntime LINK_COMPONENTS Support
diff --git a/src/llvm-project/lldb/source/Symbol/ClangASTContext.cpp b/src/llvm-project/lldb/source/Symbol/ClangASTContext.cpp index 868daa1..2055233 100644 --- a/src/llvm-project/lldb/source/Symbol/ClangASTContext.cpp +++ b/src/llvm-project/lldb/source/Symbol/ClangASTContext.cpp
@@ -1,9 +1,8 @@ //===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -53,6 +52,7 @@ #include "clang/Basic/TargetOptions.h" #include "clang/Frontend/FrontendOptions.h" #include "clang/Frontend/LangStandard.h" +#include "clang/Sema/Sema.h" #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG #undef NDEBUG @@ -86,7 +86,6 @@ #include "lldb/Symbol/VerifyDecl.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Language.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataExtractor.h" @@ -95,6 +94,7 @@ #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Scalar.h" +#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h" #include "Plugins/SymbolFile/PDB/PDBASTParser.h" @@ -115,6 +115,8 @@ Language::LanguageIsCPlusPlus(language) || Language::LanguageIsObjC(language) || Language::LanguageIsPascal(language) || + // Use Clang for Rust until there is a proper language plugin for it + language == eLanguageTypeRust || language == eLanguageTypeExtRenderScript || // Use Clang for D until there is a proper language plugin for it language == eLanguageTypeD || @@ -652,19 +654,17 @@ } ClangASTContext::ClangASTContext(const char *target_triple) - : TypeSystem(TypeSystem::eKindClang), m_target_triple(), m_ast_ap(), - m_language_options_ap(), m_source_manager_ap(), m_diagnostics_engine_ap(), - m_target_options_rp(), m_target_info_ap(), m_identifier_table_ap(), - m_selector_table_ap(), m_builtins_ap(), m_callback_tag_decl(nullptr), + : TypeSystem(TypeSystem::eKindClang), m_target_triple(), m_ast_up(), + m_language_options_up(), m_source_manager_up(), m_diagnostics_engine_up(), + m_target_options_rp(), m_target_info_up(), m_identifier_table_up(), + m_selector_table_up(), m_builtins_up(), m_callback_tag_decl(nullptr), m_callback_objc_decl(nullptr), m_callback_baton(nullptr), m_pointer_byte_size(0), m_ast_owned(false) { if (target_triple && target_triple[0]) SetTargetTriple(target_triple); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ClangASTContext::~ClangASTContext() { Finalize(); } ConstString ClangASTContext::GetPluginNameStatic() { @@ -713,13 +713,13 @@ new ClangASTContextForExpressions(*target)); if (ast_sp) { ast_sp->SetArchitecture(fixed_arch); - ast_sp->m_scratch_ast_source_ap.reset( + ast_sp->m_scratch_ast_source_up.reset( new ClangASTSource(target->shared_from_this())); lldbassert(ast_sp->getFileManager()); - ast_sp->m_scratch_ast_source_ap->InstallASTContext( + ast_sp->m_scratch_ast_source_up->InstallASTContext( *ast_sp->getASTContext(), *ast_sp->getFileManager(), true); llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source( - ast_sp->m_scratch_ast_source_ap->CreateProxy()); + ast_sp->m_scratch_ast_source_up->CreateProxy()); ast_sp->SetExternalSource(proxy_ast_source); return ast_sp; } @@ -762,37 +762,43 @@ } void ClangASTContext::Finalize() { - if (m_ast_ap.get()) { - GetASTMap().Erase(m_ast_ap.get()); + if (m_ast_up) { + GetASTMap().Erase(m_ast_up.get()); if (!m_ast_owned) - m_ast_ap.release(); + m_ast_up.release(); } - m_builtins_ap.reset(); - m_selector_table_ap.reset(); - m_identifier_table_ap.reset(); - m_target_info_ap.reset(); + m_builtins_up.reset(); + m_selector_table_up.reset(); + m_identifier_table_up.reset(); + m_target_info_up.reset(); m_target_options_rp.reset(); - m_diagnostics_engine_ap.reset(); - m_source_manager_ap.reset(); - m_language_options_ap.reset(); - m_ast_ap.reset(); - m_scratch_ast_source_ap.reset(); + m_diagnostics_engine_up.reset(); + m_source_manager_up.reset(); + m_language_options_up.reset(); + m_ast_up.reset(); + m_scratch_ast_source_up.reset(); } void ClangASTContext::Clear() { - m_ast_ap.reset(); - m_language_options_ap.reset(); - m_source_manager_ap.reset(); - m_diagnostics_engine_ap.reset(); + m_ast_up.reset(); + m_language_options_up.reset(); + m_source_manager_up.reset(); + m_diagnostics_engine_up.reset(); m_target_options_rp.reset(); - m_target_info_ap.reset(); - m_identifier_table_ap.reset(); - m_selector_table_ap.reset(); - m_builtins_ap.reset(); + m_target_info_up.reset(); + m_identifier_table_up.reset(); + m_selector_table_up.reset(); + m_builtins_up.reset(); m_pointer_byte_size = 0; } +void ClangASTContext::setSema(Sema *s) { + // Ensure that the new sema actually belongs to our ASTContext. + assert(s == nullptr || &s->getASTContext() == m_ast_up.get()); + m_sema = s; +} + const char *ClangASTContext::GetTargetTriple() { return m_target_triple.c_str(); } @@ -814,10 +820,10 @@ } void ClangASTContext::SetExternalSource( - llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_ap) { + llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) { ASTContext *ast = getASTContext(); if (ast) { - ast->setExternalSource(ast_source_ap); + ast->setExternalSource(ast_source_up); ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true); } } @@ -826,52 +832,52 @@ ASTContext *ast = getASTContext(); if (ast) { - llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_ap; - ast->setExternalSource(empty_ast_source_ap); + llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_up; + ast->setExternalSource(empty_ast_source_up); ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false); } } void ClangASTContext::setASTContext(clang::ASTContext *ast_ctx) { if (!m_ast_owned) { - m_ast_ap.release(); + m_ast_up.release(); } m_ast_owned = false; - m_ast_ap.reset(ast_ctx); + m_ast_up.reset(ast_ctx); GetASTMap().Insert(ast_ctx, this); } ASTContext *ClangASTContext::getASTContext() { - if (m_ast_ap.get() == nullptr) { + if (m_ast_up == nullptr) { m_ast_owned = true; - m_ast_ap.reset(new ASTContext(*getLanguageOptions(), *getSourceManager(), + m_ast_up.reset(new ASTContext(*getLanguageOptions(), *getSourceManager(), *getIdentifierTable(), *getSelectorTable(), *getBuiltinContext())); - m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false); + m_ast_up->getDiagnostics().setClient(getDiagnosticConsumer(), false); // This can be NULL if we don't know anything about the architecture or if // the target for an architecture isn't enabled in the llvm/clang that we // built TargetInfo *target_info = getTargetInfo(); if (target_info) - m_ast_ap->InitBuiltinTypes(*target_info); + m_ast_up->InitBuiltinTypes(*target_info); if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton) { - m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage(); - // m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage(); + m_ast_up->getTranslationUnitDecl()->setHasExternalLexicalStorage(); + // m_ast_up->getTranslationUnitDecl()->setHasExternalVisibleStorage(); } - GetASTMap().Insert(m_ast_ap.get(), this); + GetASTMap().Insert(m_ast_up.get(), this); - llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_ap( + llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up( new ClangExternalASTSourceCallbacks( ClangASTContext::CompleteTagDecl, ClangASTContext::CompleteObjCInterfaceDecl, nullptr, ClangASTContext::LayoutRecordType, this)); - SetExternalSource(ast_source_ap); + SetExternalSource(ast_source_up); } - return m_ast_ap.get(); + return m_ast_up.get(); } ClangASTContext *ClangASTContext::GetASTContext(clang::ASTContext *ast) { @@ -880,61 +886,62 @@ } Builtin::Context *ClangASTContext::getBuiltinContext() { - if (m_builtins_ap.get() == nullptr) - m_builtins_ap.reset(new Builtin::Context()); - return m_builtins_ap.get(); + if (m_builtins_up == nullptr) + m_builtins_up.reset(new Builtin::Context()); + return m_builtins_up.get(); } IdentifierTable *ClangASTContext::getIdentifierTable() { - if (m_identifier_table_ap.get() == nullptr) - m_identifier_table_ap.reset( + if (m_identifier_table_up == nullptr) + m_identifier_table_up.reset( new IdentifierTable(*ClangASTContext::getLanguageOptions(), nullptr)); - return m_identifier_table_ap.get(); + return m_identifier_table_up.get(); } LangOptions *ClangASTContext::getLanguageOptions() { - if (m_language_options_ap.get() == nullptr) { - m_language_options_ap.reset(new LangOptions()); - ParseLangArgs(*m_language_options_ap, InputKind::ObjCXX, GetTargetTriple()); - // InitializeLangOptions(*m_language_options_ap, InputKind::ObjCXX); + if (m_language_options_up == nullptr) { + m_language_options_up.reset(new LangOptions()); + ParseLangArgs(*m_language_options_up, InputKind::ObjCXX, GetTargetTriple()); + // InitializeLangOptions(*m_language_options_up, InputKind::ObjCXX); } - return m_language_options_ap.get(); + return m_language_options_up.get(); } SelectorTable *ClangASTContext::getSelectorTable() { - if (m_selector_table_ap.get() == nullptr) - m_selector_table_ap.reset(new SelectorTable()); - return m_selector_table_ap.get(); + if (m_selector_table_up == nullptr) + m_selector_table_up.reset(new SelectorTable()); + return m_selector_table_up.get(); } clang::FileManager *ClangASTContext::getFileManager() { - if (m_file_manager_ap.get() == nullptr) { + if (m_file_manager_up == nullptr) { clang::FileSystemOptions file_system_options; - m_file_manager_ap.reset(new clang::FileManager(file_system_options)); + m_file_manager_up.reset(new clang::FileManager( + file_system_options, FileSystem::Instance().GetVirtualFileSystem())); } - return m_file_manager_ap.get(); + return m_file_manager_up.get(); } clang::SourceManager *ClangASTContext::getSourceManager() { - if (m_source_manager_ap.get() == nullptr) - m_source_manager_ap.reset( + if (m_source_manager_up == nullptr) + m_source_manager_up.reset( new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager())); - return m_source_manager_ap.get(); + return m_source_manager_up.get(); } clang::DiagnosticsEngine *ClangASTContext::getDiagnosticsEngine() { - if (m_diagnostics_engine_ap.get() == nullptr) { + if (m_diagnostics_engine_up == nullptr) { llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs()); - m_diagnostics_engine_ap.reset( + m_diagnostics_engine_up.reset( new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions())); } - return m_diagnostics_engine_ap.get(); + return m_diagnostics_engine_up.get(); } clang::MangleContext *ClangASTContext::getMangleContext() { - if (m_mangle_ctx_ap.get() == nullptr) - m_mangle_ctx_ap.reset(getASTContext()->createMangleContext()); - return m_mangle_ctx_ap.get(); + if (m_mangle_ctx_up == nullptr) + m_mangle_ctx_up.reset(getASTContext()->createMangleContext()); + return m_mangle_ctx_up.get(); } class NullDiagnosticConsumer : public DiagnosticConsumer { @@ -944,7 +951,7 @@ } void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, - const clang::Diagnostic &info) { + const clang::Diagnostic &info) override { if (m_log) { llvm::SmallVector<char, 32> diag_str(10); info.FormatDiagnostic(diag_str); @@ -962,16 +969,16 @@ }; DiagnosticConsumer *ClangASTContext::getDiagnosticConsumer() { - if (m_diagnostic_consumer_ap.get() == nullptr) - m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer); + if (m_diagnostic_consumer_up == nullptr) + m_diagnostic_consumer_up.reset(new NullDiagnosticConsumer); - return m_diagnostic_consumer_ap.get(); + return m_diagnostic_consumer_up.get(); } std::shared_ptr<clang::TargetOptions> &ClangASTContext::getTargetOptions() { - if (m_target_options_rp.get() == nullptr && !m_target_triple.empty()) { + if (m_target_options_rp == nullptr && !m_target_triple.empty()) { m_target_options_rp = std::make_shared<clang::TargetOptions>(); - if (m_target_options_rp.get() != nullptr) + if (m_target_options_rp != nullptr) m_target_options_rp->Triple = m_target_triple; } return m_target_options_rp; @@ -979,10 +986,10 @@ TargetInfo *ClangASTContext::getTargetInfo() { // target_triple should be something like "x86_64-apple-macosx" - if (m_target_info_ap.get() == nullptr && !m_target_triple.empty()) - m_target_info_ap.reset(TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), + if (m_target_info_up == nullptr && !m_target_triple.empty()) + m_target_info_up.reset(TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), getTargetOptions())); - return m_target_info_ap.get(); + return m_target_info_up.get(); } #pragma mark Basic Types @@ -1063,7 +1070,7 @@ } lldb::BasicType -ClangASTContext::GetBasicTypeEnumeration(const ConstString &name) { +ClangASTContext::GetBasicTypeEnumeration(ConstString name) { if (name) { typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap; static TypeNameToBasicTypeMap g_type_map; @@ -1129,7 +1136,7 @@ } CompilerType ClangASTContext::GetBasicType(ASTContext *ast, - const ConstString &name) { + ConstString name) { if (ast) { lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration(name); return ClangASTContext::GetBasicType(ast, basic_type); @@ -1408,7 +1415,14 @@ FileManager file_manager(file_system_options); ASTImporter importer(*dst_ast, file_manager, *src_ast, file_manager, false); - return importer.Import(source_decl); + if (llvm::Expected<clang::Decl *> ret_or_error = + importer.Import(source_decl)) { + return *ret_or_error; + } else { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + LLDB_LOG_ERROR(log, ret_or_error.takeError(), "Couldn't import decl: {0}"); + return nullptr; + } } bool ClangASTContext::AreTypesSame(CompilerType type1, CompilerType type2, @@ -1548,25 +1562,24 @@ } } - if (template_param_infos.packed_args && - template_param_infos.packed_args->args.size()) { + if (template_param_infos.packed_args) { IdentifierInfo *identifier_info = nullptr; if (template_param_infos.pack_name && template_param_infos.pack_name[0]) identifier_info = &ast->Idents.get(template_param_infos.pack_name); const bool parameter_pack_true = true; - if (IsValueParam(template_param_infos.packed_args->args[0])) { + + if (!template_param_infos.packed_args->args.empty() && + IsValueParam(template_param_infos.packed_args->args[0])) { template_param_decls.push_back(NonTypeTemplateParmDecl::Create( - *ast, decl_context, - SourceLocation(), SourceLocation(), depth, num_template_params, - identifier_info, + *ast, decl_context, SourceLocation(), SourceLocation(), depth, + num_template_params, identifier_info, template_param_infos.packed_args->args[0].getIntegralType(), parameter_pack_true, nullptr)); } else { template_param_decls.push_back(TemplateTypeParmDecl::Create( - *ast, decl_context, - SourceLocation(), SourceLocation(), depth, num_template_params, - identifier_info, - is_typename, parameter_pack_true)); + *ast, decl_context, SourceLocation(), SourceLocation(), depth, + num_template_params, identifier_info, is_typename, + parameter_pack_true)); } } clang::Expr *const requires_clause = nullptr; // TODO: Concepts @@ -1602,10 +1615,11 @@ void ClangASTContext::CreateFunctionTemplateSpecializationInfo( FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl, const TemplateParameterInfos &infos) { - TemplateArgumentList template_args(TemplateArgumentList::OnStack, infos.args); + TemplateArgumentList *template_args_ptr = + TemplateArgumentList::CreateCopy(func_decl->getASTContext(), infos.args); - func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, &template_args, - nullptr); + func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, + template_args_ptr, nullptr); } ClassTemplateDecl *ClangASTContext::CreateClassTemplateDecl( @@ -1654,6 +1668,7 @@ decl_ctx, // What decl context do we use here? TU? The actual decl // context? SourceLocation(), decl_name, template_param_list, template_cxx_decl); + template_cxx_decl->setDescribedClassTemplate(class_template_decl); if (class_template_decl) { if (access_type != eAccessNone) @@ -1891,9 +1906,8 @@ #pragma mark Namespace Declarations -NamespaceDecl * -ClangASTContext::GetUniqueNamespaceDeclaration(const char *name, - DeclContext *decl_ctx) { +NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration( + const char *name, DeclContext *decl_ctx, bool is_inline) { NamespaceDecl *namespace_decl = nullptr; ASTContext *ast = getASTContext(); TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl(); @@ -1911,7 +1925,7 @@ } namespace_decl = - NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(), + NamespaceDecl::Create(*ast, decl_ctx, is_inline, SourceLocation(), SourceLocation(), &identifier_info, nullptr); decl_ctx->addDecl(namespace_decl); @@ -1941,7 +1955,8 @@ assert(namespace_decl == parent_namespace_decl->getAnonymousNamespace()); } else { - // BAD!!! + assert(false && "GetUniqueNamespaceDeclaration called with no name and " + "no namespace as decl_ctx"); } } } @@ -1952,12 +1967,13 @@ } NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration( - clang::ASTContext *ast, const char *name, clang::DeclContext *decl_ctx) { + clang::ASTContext *ast, const char *name, clang::DeclContext *decl_ctx, + bool is_inline) { ClangASTContext *ast_ctx = ClangASTContext::GetASTContext(ast); if (ast_ctx == nullptr) return nullptr; - return ast_ctx->GetUniqueNamespaceDeclaration(name, decl_ctx); + return ast_ctx->GetUniqueNamespaceDeclaration(name, decl_ctx, is_inline); } clang::BlockDecl * @@ -2156,7 +2172,7 @@ *ast, decl_ctx, SourceLocation(), SourceLocation(), declarationName, ClangUtil::GetQualType(function_clang_type), nullptr, (clang::StorageClass)storage, is_inline, hasWrittenPrototype, - isConstexprSpecified); + isConstexprSpecified ? CSK_constexpr : CSK_unspecified); if (func_decl) decl_ctx->addDecl(func_decl); @@ -2232,7 +2248,7 @@ CompilerType ClangASTContext::CreateBlockPointerType(const CompilerType &function_type) { - QualType block_type = m_ast_ap->getBlockPointerType( + QualType block_type = m_ast_up->getBlockPointerType( clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType())); return CompilerType(this, block_type.getAsOpaquePtr()); @@ -2270,7 +2286,7 @@ } CompilerType ClangASTContext::CreateStructForIdentifier( - const ConstString &type_name, + ConstString type_name, const std::initializer_list<std::pair<const char *, CompilerType>> &type_fields, bool packed) { @@ -2295,7 +2311,7 @@ } CompilerType ClangASTContext::GetOrCreateStructForIdentifier( - const ConstString &type_name, + ConstString type_name, const std::initializer_list<std::pair<const char *, CompilerType>> &type_fields, bool packed) { @@ -2433,21 +2449,17 @@ bool ClangASTContext::DeclsAreEquivalent(clang::Decl *lhs_decl, clang::Decl *rhs_decl) { if (lhs_decl && rhs_decl) { - //---------------------------------------------------------------------- // Make sure the decl kinds match first - //---------------------------------------------------------------------- const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind(); const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind(); if (lhs_decl_kind == rhs_decl_kind) { - //------------------------------------------------------------------ // Now check that the decl contexts kinds are all equivalent before we // have to check any names of the decl contexts... - //------------------------------------------------------------------ clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext(); clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext(); if (lhs_decl_ctx && rhs_decl_ctx) { - while (1) { + while (true) { if (lhs_decl_ctx && rhs_decl_ctx) { const clang::Decl::Kind lhs_decl_ctx_kind = lhs_decl_ctx->getDeclKind(); @@ -2465,9 +2477,7 @@ return false; } - //-------------------------------------------------------------- // Now make sure the name of the decls match - //-------------------------------------------------------------- clang::NamedDecl *lhs_named_decl = llvm::dyn_cast<clang::NamedDecl>(lhs_decl); clang::NamedDecl *rhs_named_decl = @@ -2483,13 +2493,11 @@ } else return false; - //-------------------------------------------------------------- // We know that the decl context kinds all match, so now we need to // make sure the names match as well - //-------------------------------------------------------------- lhs_decl_ctx = lhs_decl->getDeclContext(); rhs_decl_ctx = rhs_decl->getDeclContext(); - while (1) { + while (true) { switch (lhs_decl_ctx->getDeclKind()) { case clang::Decl::TranslationUnit: // We don't care about the translation unit names @@ -2828,9 +2836,7 @@ return clang::ObjCIvarDecl::None; } -//---------------------------------------------------------------------- // Tests -//---------------------------------------------------------------------- bool ClangASTContext::IsAggregateType(lldb::opaque_compiler_type_t type) { clang::QualType qual_type(GetCanonicalQualType(type)); @@ -3322,7 +3328,7 @@ const clang::BlockPointerType *block_pointer_type = qual_type->getAs<clang::BlockPointerType>(); QualType pointee_type = block_pointer_type->getPointeeType(); - QualType function_pointer_type = m_ast_ap->getPointerType(pointee_type); + QualType function_pointer_type = m_ast_up->getPointerType(pointee_type); *function_pointer_type_ptr = CompilerType(getASTContext(), function_pointer_type); } @@ -3907,6 +3913,14 @@ return GetCanonicalQualType(type)->isVoidType(); } +bool ClangASTContext::CanPassInRegisters(const CompilerType &type) { + if (auto *record_decl = + ClangASTContext::GetAsRecordDecl(type)) { + return record_decl->canPassInRegisters(); + } + return false; +} + bool ClangASTContext::SupportsLanguage(lldb::LanguageType language) { return ClangASTContextSupportsLanguage(language); } @@ -3992,9 +4006,7 @@ return false; } -//---------------------------------------------------------------------- // Type Completion -//---------------------------------------------------------------------- bool ClangASTContext::GetCompleteType(lldb::opaque_compiler_type_t type) { if (!type) @@ -4262,9 +4274,11 @@ if (qual_type->isAnyPointerType()) { if (qual_type->isObjCObjectPointerType()) return lldb::eLanguageTypeObjC; + if (qual_type->getPointeeCXXRecordDecl()) + return lldb::eLanguageTypeC_plus_plus; clang::QualType pointee_type(qual_type->getPointeeType()); - if (pointee_type->getPointeeCXXRecordDecl() != nullptr) + if (pointee_type->getPointeeCXXRecordDecl()) return lldb::eLanguageTypeC_plus_plus; if (pointee_type->isObjCObjectOrInterfaceType()) return lldb::eLanguageTypeObjC; @@ -4472,6 +4486,8 @@ case clang::Type::DependentAddressSpace: break; + case clang::Type::MacroQualified: + break; } // We don't know hot to display this type... return lldb::eTypeClassOther; @@ -4483,9 +4499,7 @@ return 0; } -//---------------------------------------------------------------------- // Creating related types -//---------------------------------------------------------------------- CompilerType ClangASTContext::GetArrayElementType(lldb::opaque_compiler_type_t type, @@ -4997,19 +5011,16 @@ return CompilerType(); } -//---------------------------------------------------------------------- // Create related types using the current type's AST -//---------------------------------------------------------------------- CompilerType ClangASTContext::GetBasicTypeFromAST(lldb::BasicType basic_type) { return ClangASTContext::GetBasicType(getASTContext(), basic_type); } -//---------------------------------------------------------------------- // Exploring the type -//---------------------------------------------------------------------- -uint64_t ClangASTContext::GetBitSize(lldb::opaque_compiler_type_t type, - ExecutionContextScope *exe_scope) { +Optional<uint64_t> +ClangASTContext::GetBitSize(lldb::opaque_compiler_type_t type, + ExecutionContextScope *exe_scope) { if (GetCompleteType(type)) { clang::QualType qual_type(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); @@ -5018,7 +5029,7 @@ if (GetCompleteType(type)) return getASTContext()->getTypeSize(qual_type); else - return 0; + return None; break; case clang::Type::ObjCInterface: @@ -5026,7 +5037,7 @@ ExecutionContext exe_ctx(exe_scope); Process *process = exe_ctx.GetProcessPtr(); if (process) { - ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime(); + ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process); if (objc_runtime) { uint64_t bit_size = 0; if (objc_runtime->GetTypeBitSize( @@ -5063,10 +5074,14 @@ return bit_size + getASTContext()->getTypeSize( getASTContext()->ObjCBuiltinClassTy); - return bit_size; + // Function types actually have a size of 0, that's not an error. + if (qual_type->isFunctionProtoType()) + return bit_size; + if (bit_size) + return bit_size; } } - return 0; + return None; } size_t ClangASTContext::GetTypeBitAlign(lldb::opaque_compiler_type_t type) { @@ -5341,6 +5356,8 @@ case clang::Type::DependentAddressSpace: break; + case clang::Type::MacroQualified: + break; } count = 0; return lldb::eEncodingInvalid; @@ -5508,6 +5525,8 @@ case clang::Type::DependentAddressSpace: break; + case clang::Type::MacroQualified: + break; } // We don't know hot to display this type... return lldb::eFormatBytes; @@ -5732,7 +5751,7 @@ return num_children; } -CompilerType ClangASTContext::GetBuiltinTypeByName(const ConstString &name) { +CompilerType ClangASTContext::GetBuiltinTypeByName(ConstString name) { return GetBasicType(GetBasicTypeEnumeration(name)); } @@ -5812,7 +5831,7 @@ void ClangASTContext::ForEachEnumerator( lldb::opaque_compiler_type_t type, std::function<bool(const CompilerType &integer_type, - const ConstString &name, + ConstString name, const llvm::APSInt &value)> const &callback) { const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type)); @@ -6825,7 +6844,7 @@ process = exe_ctx->GetProcessPtr(); if (process) { ObjCLanguageRuntime *objc_runtime = - process->GetObjCLanguageRuntime(); + ObjCLanguageRuntime::Get(*process); if (objc_runtime != nullptr) { CompilerType parent_ast_type(getASTContext(), parent_qual_type); @@ -6885,7 +6904,7 @@ } else { child_is_deref_of_parent = true; const char *parent_name = - valobj ? valobj->GetName().GetCString() : NULL; + valobj ? valobj->GetName().GetCString() : nullptr; if (parent_name) { child_name.assign(1, '*'); child_name += parent_name; @@ -6966,7 +6985,7 @@ child_is_deref_of_parent = true; const char *parent_name = - valobj ? valobj->GetName().GetCString() : NULL; + valobj ? valobj->GetName().GetCString() : nullptr; if (parent_name) { child_name.assign(1, '*'); child_name += parent_name; @@ -7003,7 +7022,7 @@ language_flags); } else { const char *parent_name = - valobj ? valobj->GetName().GetCString() : NULL; + valobj ? valobj->GetName().GetCString() : nullptr; if (parent_name) { child_name.assign(1, '&'); child_name += parent_name; @@ -7833,7 +7852,7 @@ llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type)); if (enutype) return enutype->getDecl(); - return NULL; + return nullptr; } clang::RecordDecl *ClangASTContext::GetAsRecordDecl(const CompilerType &type) { @@ -8171,6 +8190,10 @@ if (is_artificial) return nullptr; // skip everything artificial + const clang::ExplicitSpecifier explicit_spec( + nullptr /*expr*/, is_explicit + ? clang::ExplicitSpecKind::ResolvedTrue + : clang::ExplicitSpecKind::ResolvedFalse); if (name[0] == '~') { cxx_dtor_decl = clang::CXXDestructorDecl::Create( *getASTContext(), cxx_record_decl, clang::SourceLocation(), @@ -8189,7 +8212,7 @@ clang::SourceLocation()), method_qual_type, nullptr, // TypeSourceInfo * - is_explicit, is_inline, is_artificial, false /*is_constexpr*/); + explicit_spec, is_inline, is_artificial, CSK_unspecified); cxx_method_decl = cxx_ctor_decl; } else { clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None; @@ -8212,7 +8235,7 @@ clang::SourceLocation()), method_qual_type, nullptr, // TypeSourceInfo * - SC, is_inline, false /*is_constexpr*/, clang::SourceLocation()); + SC, is_inline, CSK_unspecified, clang::SourceLocation()); } else if (num_params == 0) { // Conversion operators don't take params... cxx_method_decl = clang::CXXConversionDecl::Create( @@ -8224,7 +8247,7 @@ clang::SourceLocation()), method_qual_type, nullptr, // TypeSourceInfo * - is_inline, is_explicit, false /*is_constexpr*/, + is_inline, explicit_spec, CSK_unspecified, clang::SourceLocation()); } } @@ -8235,7 +8258,7 @@ clang::DeclarationNameInfo(decl_name, clang::SourceLocation()), method_qual_type, nullptr, // TypeSourceInfo * - SC, is_inline, false /*is_constexpr*/, clang::SourceLocation()); + SC, is_inline, CSK_unspecified, clang::SourceLocation()); } } @@ -8248,7 +8271,7 @@ if (is_attr_used) cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(*getASTContext())); - if (mangled_name != NULL) { + if (mangled_name != nullptr) { cxx_method_decl->addAttr( clang::AsmLabelAttr::CreateImplicit(*getASTContext(), mangled_name)); } @@ -9074,11 +9097,19 @@ return 0; } -//---------------------------------------------------------------------- // Dumping types -//---------------------------------------------------------------------- #define DEPTH_INCREMENT 2 +#ifndef NDEBUG +LLVM_DUMP_METHOD void +ClangASTContext::dump(lldb::opaque_compiler_type_t type) const { + if (!type) + return; + clang::QualType qual_type(GetQualType(type)); + qual_type.dump(); +} +#endif + void ClangASTContext::Dump(Stream &s) { Decl *tu = Decl::castFromDeclContext(GetTranslationUnitDecl()); tu->dump(s.AsRawOstream()); @@ -9608,7 +9639,7 @@ break; } } - return 0; + return false; } void ClangASTContext::DumpSummary(lldb::opaque_compiler_type_t type, @@ -9847,7 +9878,7 @@ template_basename.c_str(), tag_decl_kind, template_param_infos); } - return NULL; + return nullptr; } void ClangASTContext::CompleteTagDecl(void *baton, clang::TagDecl *decl) { @@ -9872,15 +9903,15 @@ } DWARFASTParser *ClangASTContext::GetDWARFParser() { - if (!m_dwarf_ast_parser_ap) - m_dwarf_ast_parser_ap.reset(new DWARFASTParserClang(*this)); - return m_dwarf_ast_parser_ap.get(); + if (!m_dwarf_ast_parser_up) + m_dwarf_ast_parser_up.reset(new DWARFASTParserClang(*this)); + return m_dwarf_ast_parser_up.get(); } PDBASTParser *ClangASTContext::GetPDBParser() { - if (!m_pdb_ast_parser_ap) - m_pdb_ast_parser_ap.reset(new PDBASTParser(*this)); - return m_pdb_ast_parser_ap.get(); + if (!m_pdb_ast_parser_up) + m_pdb_ast_parser_up.reset(new PDBASTParser(*this)); + return m_pdb_ast_parser_up.get(); } bool ClangASTContext::LayoutRecordType( @@ -9893,10 +9924,10 @@ &vbase_offsets) { ClangASTContext *ast = (ClangASTContext *)baton; lldb_private::ClangASTImporter *importer = nullptr; - if (ast->m_dwarf_ast_parser_ap) - importer = &ast->m_dwarf_ast_parser_ap->GetClangASTImporter(); - if (!importer && ast->m_pdb_ast_parser_ap) - importer = &ast->m_pdb_ast_parser_ap->GetClangASTImporter(); + if (ast->m_dwarf_ast_parser_up) + importer = &ast->m_dwarf_ast_parser_up->GetClangASTImporter(); + if (!importer && ast->m_pdb_ast_parser_up) + importer = &ast->m_pdb_ast_parser_up->GetClangASTImporter(); if (!importer) return false; @@ -9904,9 +9935,7 @@ field_offsets, base_offsets, vbase_offsets); } -//---------------------------------------------------------------------- // CompilerDecl override functions -//---------------------------------------------------------------------- ConstString ClangASTContext::DeclGetName(void *opaque_decl) { if (opaque_decl) { @@ -9994,9 +10023,7 @@ return CompilerType(); } -//---------------------------------------------------------------------- // CompilerDeclContext functions -//---------------------------------------------------------------------- std::vector<CompilerDecl> ClangASTContext::DeclContextFindDeclByName( void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) { @@ -10247,6 +10274,23 @@ return false; } +bool ClangASTContext::DeclContextIsContainedInLookup( + void *opaque_decl_ctx, void *other_opaque_decl_ctx) { + auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx; + auto *other = (clang::DeclContext *)other_opaque_decl_ctx; + + do { + // A decl context always includes its own contents in its lookup. + if (decl_ctx == other) + return true; + + // If we have an inline namespace, then the lookup of the parent context + // also includes the inline namespace contents. + } while (other->isInlineNamespace() && (other = other->getParent())); + + return false; +} + clang::DeclContext * ClangASTContext::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) { if (dc.IsClang()) @@ -10312,13 +10356,14 @@ UserExpression *ClangASTContextForExpressions::GetUserExpression( llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, Expression::ResultType desired_type, - const EvaluateExpressionOptions &options) { + const EvaluateExpressionOptions &options, + ValueObject *ctx_obj) { TargetSP target_sp = m_target_wp.lock(); if (!target_sp) return nullptr; return new ClangUserExpression(*target_sp.get(), expr, prefix, language, - desired_type, options); + desired_type, options, ctx_obj); } FunctionCaller *ClangASTContextForExpressions::GetFunctionCaller( @@ -10353,6 +10398,6 @@ clang::ExternalASTMerger & ClangASTContextForExpressions::GetMergerUnchecked() { - lldbassert(m_scratch_ast_source_ap != nullptr); - return m_scratch_ast_source_ap->GetMergerUnchecked(); + lldbassert(m_scratch_ast_source_up != nullptr); + return m_scratch_ast_source_up->GetMergerUnchecked(); }
diff --git a/src/llvm-project/lldb/source/Symbol/ClangASTImporter.cpp b/src/llvm-project/lldb/source/Symbol/ClangASTImporter.cpp index 6214414..32d0c47 100644 --- a/src/llvm-project/lldb/source/Symbol/ClangASTImporter.cpp +++ b/src/llvm-project/lldb/source/Symbol/ClangASTImporter.cpp
@@ -1,9 +1,8 @@ //===-- ClangASTImporter.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,8 +16,12 @@ #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" +#include "clang/Sema/Lookup.h" +#include "clang/Sema/Sema.h" #include "llvm/Support/raw_ostream.h" +#include <memory> + using namespace lldb_private; using namespace clang; @@ -55,12 +58,22 @@ clang::QualType ClangASTImporter::CopyType(clang::ASTContext *dst_ast, clang::ASTContext *src_ast, clang::QualType type) { - MinionSP minion_sp(GetMinion(dst_ast, src_ast)); + ImporterDelegateSP delegate_sp(GetDelegate(dst_ast, src_ast)); - if (minion_sp) - return minion_sp->Import(type); + ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast); - return QualType(); + if (!delegate_sp) + return QualType(); + + llvm::Expected<QualType> ret_or_error = delegate_sp->Import(type); + if (!ret_or_error) { + Log *log = + lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + LLDB_LOG_ERROR(log, ret_or_error.takeError(), + "Couldn't import type: {0}"); + return QualType(); + } + return *ret_or_error; } lldb::opaque_compiler_type_t @@ -94,38 +107,39 @@ clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast, clang::ASTContext *src_ast, clang::Decl *decl) { - MinionSP minion_sp; + ImporterDelegateSP delegate_sp; - minion_sp = GetMinion(dst_ast, src_ast); + delegate_sp = GetDelegate(dst_ast, src_ast); - if (minion_sp) { - clang::Decl *result = minion_sp->Import(decl); + ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast); - if (!result) { - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + if (!delegate_sp) + return nullptr; - if (log) { - lldb::user_id_t user_id = LLDB_INVALID_UID; - ClangASTMetadata *metadata = GetDeclMetadata(decl); - if (metadata) - user_id = metadata->GetUserID(); + llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl); + if (!result) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}"); + if (log) { + lldb::user_id_t user_id = LLDB_INVALID_UID; + ClangASTMetadata *metadata = GetDeclMetadata(decl); + if (metadata) + user_id = metadata->GetUserID(); - if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl)) - log->Printf(" [ClangASTImporter] WARNING: Failed to import a %s " - "'%s', metadata 0x%" PRIx64, - decl->getDeclKindName(), - named_decl->getNameAsString().c_str(), user_id); - else - log->Printf(" [ClangASTImporter] WARNING: Failed to import a %s, " - "metadata 0x%" PRIx64, - decl->getDeclKindName(), user_id); - } + if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl)) + log->Printf(" [ClangASTImporter] WARNING: Failed to import a %s " + "'%s', metadata 0x%" PRIx64, + decl->getDeclKindName(), + named_decl->getNameAsString().c_str(), user_id); + else + log->Printf(" [ClangASTImporter] WARNING: Failed to import a %s, " + "metadata 0x%" PRIx64, + decl->getDeclKindName(), user_id); } - - return result; + return nullptr; } - return nullptr; + return *result; } class DeclContextOverride { @@ -247,9 +261,9 @@ (unsigned long long)type, static_cast<void *>(src_ctx), static_cast<void *>(dst_ctx)); - MinionSP minion_sp(GetMinion(dst_ctx, src_ctx)); + ImporterDelegateSP delegate_sp(GetDelegate(dst_ctx, src_ctx)); - if (!minion_sp) + if (!delegate_sp) return nullptr; std::set<NamedDecl *> decls_to_deport; @@ -263,11 +277,11 @@ tag_type->getDecl()); } - minion_sp->InitDeportWorkQueues(&decls_to_deport, &decls_already_deported); + delegate_sp->InitDeportWorkQueues(&decls_to_deport, &decls_already_deported); lldb::opaque_compiler_type_t result = CopyType(dst_ctx, src_ctx, type); - minion_sp->ExecuteDeportWorkQueues(); + delegate_sp->ExecuteDeportWorkQueues(); if (!result) return nullptr; @@ -286,9 +300,9 @@ decl->getDeclKindName(), static_cast<void *>(decl), static_cast<void *>(src_ctx), static_cast<void *>(dst_ctx)); - MinionSP minion_sp(GetMinion(dst_ctx, src_ctx)); + ImporterDelegateSP delegate_sp(GetDelegate(dst_ctx, src_ctx)); - if (!minion_sp) + if (!delegate_sp) return nullptr; std::set<NamedDecl *> decls_to_deport; @@ -298,11 +312,11 @@ decl_context_override.OverrideAllDeclsFromContainingFunction(decl); - minion_sp->InitDeportWorkQueues(&decls_to_deport, &decls_already_deported); + delegate_sp->InitDeportWorkQueues(&decls_to_deport, &decls_already_deported); clang::Decl *result = CopyDecl(dst_ctx, src_ctx, decl); - minion_sp->ExecuteDeportWorkQueues(); + delegate_sp->ExecuteDeportWorkQueues(); if (!result) return nullptr; @@ -332,7 +346,7 @@ const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { - if (ResolveDeclOrigin(cxx_record_decl, NULL, NULL)) + if (ResolveDeclOrigin(cxx_record_decl, nullptr, nullptr)) return true; } } break; @@ -341,7 +355,7 @@ clang::EnumDecl *enum_decl = llvm::cast<clang::EnumType>(qual_type)->getDecl(); if (enum_decl) { - if (ResolveDeclOrigin(enum_decl, NULL, NULL)) + if (ResolveDeclOrigin(enum_decl, nullptr, nullptr)) return true; } } break; @@ -356,7 +370,7 @@ // We currently can't complete objective C types through the newly added // ASTContext because it only supports TagDecl objects right now... if (class_interface_decl) { - if (ResolveDeclOrigin(class_interface_decl, NULL, NULL)) + if (ResolveDeclOrigin(class_interface_decl, nullptr, nullptr)) return true; } } @@ -408,7 +422,7 @@ const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { - if (ResolveDeclOrigin(cxx_record_decl, NULL, NULL)) + if (ResolveDeclOrigin(cxx_record_decl, nullptr, nullptr)) return CompleteAndFetchChildren(qual_type); } } break; @@ -417,7 +431,7 @@ clang::EnumDecl *enum_decl = llvm::cast<clang::EnumType>(qual_type)->getDecl(); if (enum_decl) { - if (ResolveDeclOrigin(enum_decl, NULL, NULL)) + if (ResolveDeclOrigin(enum_decl, nullptr, nullptr)) return CompleteAndFetchChildren(qual_type); } } break; @@ -432,7 +446,7 @@ // We currently can't complete objective C types through the newly added // ASTContext because it only supports TagDecl objects right now... if (class_interface_decl) { - if (ResolveDeclOrigin(class_interface_decl, NULL, NULL)) + if (ResolveDeclOrigin(class_interface_decl, nullptr, nullptr)) return CompleteAndFetchChildren(qual_type); } } @@ -554,10 +568,13 @@ if (!ClangASTContext::GetCompleteDecl(decl_origin.ctx, decl_origin.decl)) return false; - MinionSP minion_sp(GetMinion(&decl->getASTContext(), decl_origin.ctx)); + ImporterDelegateSP delegate_sp( + GetDelegate(&decl->getASTContext(), decl_origin.ctx)); - if (minion_sp) - minion_sp->ImportDefinitionTo(decl, decl_origin.decl); + ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, + &decl->getASTContext()); + if (delegate_sp) + delegate_sp->ImportDefinitionTo(decl, decl_origin.decl); return true; } @@ -571,10 +588,11 @@ if (!ClangASTContext::GetCompleteDecl(origin_ast_ctx, origin_decl)) return false; - MinionSP minion_sp(GetMinion(&decl->getASTContext(), origin_ast_ctx)); + ImporterDelegateSP delegate_sp( + GetDelegate(&decl->getASTContext(), origin_ast_ctx)); - if (minion_sp) - minion_sp->ImportDefinitionTo(decl, origin_decl); + if (delegate_sp) + delegate_sp->ImportDefinitionTo(decl, origin_decl); ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext()); @@ -597,11 +615,11 @@ if (!ClangASTContext::GetCompleteDecl(decl_origin.ctx, decl_origin.decl)) return false; - MinionSP minion_sp( - GetMinion(&interface_decl->getASTContext(), decl_origin.ctx)); + ImporterDelegateSP delegate_sp( + GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx)); - if (minion_sp) - minion_sp->ImportDefinitionTo(interface_decl, decl_origin.decl); + if (delegate_sp) + delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl); if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass()) RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0)); @@ -613,6 +631,8 @@ if (!RequireCompleteType(type)) return false; + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + if (const TagType *tag_type = type->getAs<TagType>()) { TagDecl *tag_decl = tag_type->getDecl(); @@ -621,12 +641,22 @@ if (!decl_origin.Valid()) return false; - MinionSP minion_sp(GetMinion(&tag_decl->getASTContext(), decl_origin.ctx)); + ImporterDelegateSP delegate_sp( + GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx)); + + ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, + &tag_decl->getASTContext()); TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl); for (Decl *origin_child_decl : origin_tag_decl->decls()) { - minion_sp->Import(origin_child_decl); + llvm::Expected<Decl *> imported_or_err = + delegate_sp->Import(origin_child_decl); + if (!imported_or_err) { + LLDB_LOG_ERROR(log, imported_or_err.takeError(), + "Couldn't import decl: {0}"); + return false; + } } if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl)) { @@ -644,14 +674,20 @@ if (!decl_origin.Valid()) return false; - MinionSP minion_sp( - GetMinion(&objc_interface_decl->getASTContext(), decl_origin.ctx)); + ImporterDelegateSP delegate_sp( + GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx)); ObjCInterfaceDecl *origin_interface_decl = llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl); for (Decl *origin_child_decl : origin_interface_decl->decls()) { - minion_sp->Import(origin_child_decl); + llvm::Expected<Decl *> imported_or_err = + delegate_sp->Import(origin_child_decl); + if (!imported_or_err) { + LLDB_LOG_ERROR(log, imported_or_err.takeError(), + "Couldn't import decl: {0}"); + return false; + } } return true; @@ -766,7 +802,7 @@ NamespaceMapSP new_map; - new_map.reset(new NamespaceMap); + new_map = std::make_shared<NamespaceMap>(); if (context_md->m_map_completer) { std::string namespace_string = decl->getDeclName().getAsString(); @@ -802,7 +838,7 @@ if (!md) return; - md->m_minions.erase(src_ast); + md->m_delegates.erase(src_ast); for (OriginMap::iterator iter = md->m_origins.begin(); iter != md->m_origins.end();) { @@ -815,7 +851,25 @@ ClangASTImporter::MapCompleter::~MapCompleter() { return; } -void ClangASTImporter::Minion::InitDeportWorkQueues( +llvm::Expected<Decl *> +ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl *From) { + if (m_std_handler) { + llvm::Optional<Decl *> D = m_std_handler->Import(From); + if (D) { + // Make sure we don't use this decl later to map it back to it's original + // decl. The decl the CxxModuleHandler created has nothing to do with + // the one from debug info, and linking those two would just cause the + // ASTImporter to try 'updating' the module decl with the minimal one from + // the debug info. + m_decls_to_ignore.insert(*D); + return *D; + } + } + + return ASTImporter::ImportImpl(From); +} + +void ClangASTImporter::ASTImporterDelegate::InitDeportWorkQueues( std::set<clang::NamedDecl *> *decls_to_deport, std::set<clang::NamedDecl *> *decls_already_deported) { assert(!m_decls_to_deport); @@ -825,7 +879,7 @@ m_decls_already_deported = decls_already_deported; } -void ClangASTImporter::Minion::ExecuteDeportWorkQueues() { +void ClangASTImporter::ASTImporterDelegate::ExecuteDeportWorkQueues() { assert(m_decls_to_deport); assert(m_decls_already_deported); @@ -872,8 +926,8 @@ m_decls_already_deported = nullptr; } -void ClangASTImporter::Minion::ImportDefinitionTo(clang::Decl *to, - clang::Decl *from) { +void ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo( + clang::Decl *to, clang::Decl *from) { ASTImporter::Imported(from, to); /* @@ -886,11 +940,39 @@ to_cxx_record->startDefinition(); */ - ImportDefinition(from); + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + + if (llvm::Error err = ImportDefinition(from)) { + LLDB_LOG_ERROR(log, std::move(err), + "[ClangASTImporter] Error during importing definition: {0}"); + return; + } if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) { if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) { to_tag->setCompleteDefinition(from_tag->isCompleteDefinition()); + + if (Log *log_ast = + lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_AST)) { + std::string name_string; + if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) { + llvm::raw_string_ostream name_stream(name_string); + from_named_decl->printName(name_stream); + name_stream.flush(); + } + LLDB_LOG(log_ast, "==== [ClangASTImporter][TUDecl: {0}] Imported " + "({1}Decl*){2}, named {3} (from " + "(Decl*){4})", + static_cast<void *>(to->getTranslationUnitDecl()), + from->getDeclKindName(), static_cast<void *>(to), name_string, + static_cast<void *>(from)); + + // Log the AST of the TU. + std::string ast_string; + llvm::raw_string_ostream ast_stream(ast_string); + to->getTranslationUnitDecl()->dump(ast_stream); + LLDB_LOG(log_ast, "{0}", ast_string); + } } } @@ -916,13 +998,17 @@ if (!from_superclass) break; - Decl *imported_from_superclass_decl = Import(from_superclass); + llvm::Expected<Decl *> imported_from_superclass_decl = + Import(from_superclass); - if (!imported_from_superclass_decl) + if (!imported_from_superclass_decl) { + LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(), + "Couldn't import decl: {0}"); break; + } ObjCInterfaceDecl *imported_from_superclass = - dyn_cast<ObjCInterfaceDecl>(imported_from_superclass_decl); + dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl); if (!imported_from_superclass) break; @@ -932,16 +1018,21 @@ to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo( m_source_ctx->getObjCInterfaceType(imported_from_superclass))); - } while (0); + } while (false); } } -clang::Decl *ClangASTImporter::Minion::Imported(clang::Decl *from, - clang::Decl *to) { +void ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl *from, + clang::Decl *to) { ClangASTMetrics::RegisterClangImport(); Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); + // Some decls shouldn't be tracked here because they were not created by + // copying 'from' to 'to'. Just exit early for those. + if (m_decls_to_ignore.find(to) != m_decls_to_ignore.end()) + return clang::ASTImporter::Imported(from, to); + lldb::user_id_t user_id = LLDB_INVALID_UID; ClangASTMetadata *metadata = m_master.GetDeclMetadata(from); if (metadata) @@ -983,8 +1074,8 @@ to_context_md->m_origins[to] = origin_iter->second; } - MinionSP direct_completer = - m_master.GetMinion(&to->getASTContext(), origin_iter->second.ctx); + ImporterDelegateSP direct_completer = + m_master.GetDelegate(&to->getASTContext(), origin_iter->second.ctx); if (direct_completer.get() != this) direct_completer->ASTImporter::Imported(origin_iter->second.decl, to); @@ -1095,11 +1186,10 @@ } } } - - return clang::ASTImporter::Imported(from, to); } -clang::Decl *ClangASTImporter::Minion::GetOriginalDecl(clang::Decl *To) { +clang::Decl * +ClangASTImporter::ASTImporterDelegate::GetOriginalDecl(clang::Decl *To) { ASTContextMetadataSP to_context_md = m_master.GetContextMetadata(&To->getASTContext());
diff --git a/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCallbacks.cpp b/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCallbacks.cpp index a96ef19..c35fc58 100644 --- a/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCallbacks.cpp +++ b/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCallbacks.cpp
@@ -1,9 +1,8 @@ //===-- ClangExternalASTSourceCallbacks.cpp ---------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCommon.cpp b/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCommon.cpp index 992a763..3dcf905 100644 --- a/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCommon.cpp +++ b/src/llvm-project/lldb/source/Symbol/ClangExternalASTSourceCommon.cpp
@@ -1,9 +1,8 @@ //===-- ClangExternalASTSourceCommon.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Symbol/ClangUtil.cpp b/src/llvm-project/lldb/source/Symbol/ClangUtil.cpp index 687fba7..86be895 100644 --- a/src/llvm-project/lldb/source/Symbol/ClangUtil.cpp +++ b/src/llvm-project/lldb/source/Symbol/ClangUtil.cpp
@@ -1,9 +1,8 @@ //===-- ClangUtil.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // // A collection of helper methods and data structures for manipulating clang // types and decls.
diff --git a/src/llvm-project/lldb/source/Symbol/CompactUnwindInfo.cpp b/src/llvm-project/lldb/source/Symbol/CompactUnwindInfo.cpp index 6f0f35f..3a2a4d3 100644 --- a/src/llvm-project/lldb/source/Symbol/CompactUnwindInfo.cpp +++ b/src/llvm-project/lldb/source/Symbol/CompactUnwindInfo.cpp
@@ -1,9 +1,8 @@ //===-- CompactUnwindInfo.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,10 +17,12 @@ #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" -#include <algorithm> #include "llvm/Support/MathExtras.h" +#include <algorithm> +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -156,9 +157,7 @@ llvm::countTrailingZeros(static_cast<uint32_t>(mask), llvm::ZB_Width)) & \ (((1 << llvm::countPopulation(static_cast<uint32_t>(mask)))) - 1)) -//---------------------- // constructor -//---------------------- CompactUnwindInfo::CompactUnwindInfo(ObjectFile &objfile, SectionSP §ion_sp) : m_objfile(objfile), m_section_sp(section_sp), @@ -166,9 +165,7 @@ m_indexes_computed(eLazyBoolCalculate), m_unwindinfo_data(), m_unwindinfo_data_computed(false), m_unwind_header() {} -//---------------------- // destructor -//---------------------- CompactUnwindInfo::~CompactUnwindInfo() {} @@ -189,7 +186,7 @@ if (log && log->GetVerbose()) { StreamString strm; addr.Dump( - &strm, NULL, + &strm, nullptr, Address::DumpStyle::DumpStyleResolvedDescriptionNoFunctionArguments, Address::DumpStyle::DumpStyleFileAddress, arch.GetAddressByteSize()); @@ -264,8 +261,8 @@ // have a live process and can read them out of memory. if (process_sp.get() == nullptr) return; - m_section_contents_if_encrypted.reset( - new DataBufferHeap(m_section_sp->GetByteSize(), 0)); + m_section_contents_if_encrypted = + std::make_shared<DataBufferHeap>(m_section_sp->GetByteSize(), 0); Status error; if (process_sp->ReadMemory( m_section_sp->GetLoadBaseAddress(&process_sp->GetTarget()),
diff --git a/src/llvm-project/lldb/source/Symbol/CompileUnit.cpp b/src/llvm-project/lldb/source/Symbol/CompileUnit.cpp index 74512c8..5fb9b6b 100644 --- a/src/llvm-project/lldb/source/Symbol/CompileUnit.cpp +++ b/src/llvm-project/lldb/source/Symbol/CompileUnit.cpp
@@ -1,9 +1,8 @@ //===-- CompileUnit.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,7 +22,7 @@ lldb_private::LazyBool is_optimized) : ModuleChild(module_sp), FileSpec(pathname), UserID(cu_sym_id), m_user_data(user_data), m_language(language), m_flags(0), - m_support_files(), m_line_table_ap(), m_variables(), + m_support_files(), m_line_table_up(), m_variables(), m_is_optimized(is_optimized) { if (language != eLanguageTypeUnknown) m_flags.Set(flagsParsedLanguage); @@ -36,7 +35,7 @@ lldb_private::LazyBool is_optimized) : ModuleChild(module_sp), FileSpec(fspec), UserID(cu_sym_id), m_user_data(user_data), m_language(language), m_flags(0), - m_support_files(), m_line_table_ap(), m_variables(), + m_support_files(), m_line_table_up(), m_variables(), m_is_optimized(is_optimized) { if (language != eLanguageTypeUnknown) m_flags.Set(flagsParsedLanguage); @@ -82,12 +81,10 @@ return; } -//---------------------------------------------------------------------- // Dump the current contents of this object. No functions that cause on demand // parsing of functions, globals, statics are called, so this is a good // function to call to get an idea of the current contents of the CompileUnit // object. -//---------------------------------------------------------------------- void CompileUnit::Dump(Stream *s, bool show_context) const { const char *language = Language::GetNameForLanguageType(m_language); @@ -117,14 +114,11 @@ } } -//---------------------------------------------------------------------- // Add a function to this compile unit -//---------------------------------------------------------------------- void CompileUnit::AddFunction(FunctionSP &funcSP) { m_functions_by_uid[funcSP->GetID()] = funcSP; } -//---------------------------------------------------------------------- // Find functions using the Mangled::Tokens token list. This function currently // implements an interactive approach designed to find all instances of certain // functions. It isn't designed to the quickest way to lookup functions as it @@ -146,7 +140,6 @@ // method should be able to take advantage of any accelerator tables available // in the debug information (which is parsed by the SymbolFile parser plug-ins // and registered with each Module). -//---------------------------------------------------------------------- // void // CompileUnit::FindFunctions(const Mangled::Tokens& tokens) //{ @@ -190,7 +183,7 @@ } LineTable *CompileUnit::GetLineTable() { - if (m_line_table_ap.get() == nullptr) { + if (m_line_table_up == nullptr) { if (m_flags.IsClear(flagsParsedLineTable)) { m_flags.Set(flagsParsedLineTable); SymbolVendor *symbol_vendor = GetModule()->GetSymbolVendor(); @@ -198,7 +191,7 @@ symbol_vendor->ParseLineTable(*this); } } - return m_line_table_ap.get(); + return m_line_table_up.get(); } void CompileUnit::SetLineTable(LineTable *line_table) { @@ -206,7 +199,7 @@ m_flags.Clear(flagsParsedLineTable); else m_flags.Set(flagsParsedLineTable); - m_line_table_ap.reset(line_table); + m_line_table_up.reset(line_table); } DebugMacros *CompileUnit::GetDebugMacros() { @@ -255,7 +248,7 @@ // All the line table entries actually point to the version of the Compile // Unit that is in the support files (the one at 0 was artificially added.) // So prefer the one further on in the support files if it exists... - FileSpecList &support_files = GetSupportFiles(); + const FileSpecList &support_files = GetSupportFiles(); const bool full = true; file_idx = support_files.FindFileIndex( 1, support_files.GetFileSpecAtIndex(0), full); @@ -391,7 +384,7 @@ m_variables = variables; } -const std::vector<ConstString> &CompileUnit::GetImportedModules() { +const std::vector<SourceModule> &CompileUnit::GetImportedModules() { if (m_imported_modules.empty() && m_flags.IsClear(flagsParsedImportedModules)) { m_flags.Set(flagsParsedImportedModules); @@ -404,7 +397,7 @@ return m_imported_modules; } -FileSpecList &CompileUnit::GetSupportFiles() { +const FileSpecList &CompileUnit::GetSupportFiles() { if (m_support_files.GetSize() == 0) { if (m_flags.IsClear(flagsParsedSupportFiles)) { m_flags.Set(flagsParsedSupportFiles);
diff --git a/src/llvm-project/lldb/source/Symbol/CompilerDecl.cpp b/src/llvm-project/lldb/source/Symbol/CompilerDecl.cpp index 2b632c5..2c64113 100644 --- a/src/llvm-project/lldb/source/Symbol/CompilerDecl.cpp +++ b/src/llvm-project/lldb/source/Symbol/CompilerDecl.cpp
@@ -1,9 +1,8 @@ //===-- CompilerDecl.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Symbol/CompilerDeclContext.cpp b/src/llvm-project/lldb/source/Symbol/CompilerDeclContext.cpp index 43a83bb..a6f046c 100644 --- a/src/llvm-project/lldb/source/Symbol/CompilerDeclContext.cpp +++ b/src/llvm-project/lldb/source/Symbol/CompilerDeclContext.cpp
@@ -1,9 +1,8 @@ //===-- CompilerDeclContext.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -60,6 +59,19 @@ return false; } +bool CompilerDeclContext::IsContainedInLookup(CompilerDeclContext other) const { + if (!IsValid()) + return false; + + // If the other context is just the current context, we don't need to go + // over the type system to know that the lookup is identical. + if (this == &other) + return true; + + return m_type_system->DeclContextIsContainedInLookup(m_opaque_decl_ctx, + other.m_opaque_decl_ctx); +} + bool lldb_private::operator==(const lldb_private::CompilerDeclContext &lhs, const lldb_private::CompilerDeclContext &rhs) { return lhs.GetTypeSystem() == rhs.GetTypeSystem() &&
diff --git a/src/llvm-project/lldb/source/Symbol/CompilerType.cpp b/src/llvm-project/lldb/source/Symbol/CompilerType.cpp index 7e381ab..bb9a1a6 100644 --- a/src/llvm-project/lldb/source/Symbol/CompilerType.cpp +++ b/src/llvm-project/lldb/source/Symbol/CompilerType.cpp
@@ -1,9 +1,8 @@ //===-- CompilerType.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,17 +35,13 @@ CompilerType::CompilerType(clang::ASTContext *ast, clang::QualType qual_type) : m_type(qual_type.getAsOpaquePtr()), m_type_system(ClangASTContext::GetASTContext(ast)) { -#ifdef LLDB_CONFIGURATION_DEBUG if (m_type) assert(m_type_system != nullptr); -#endif } CompilerType::~CompilerType() {} -//---------------------------------------------------------------------- // Tests -//---------------------------------------------------------------------- bool CompilerType::IsAggregateType() const { if (IsValid()) @@ -149,7 +144,7 @@ CompilerType *function_pointer_type_ptr) const { if (IsValid()) return m_type_system->IsBlockPointerType(m_type, function_pointer_type_ptr); - return 0; + return false; } bool CompilerType::IsIntegerType(bool &is_signed) const { @@ -273,9 +268,7 @@ return m_type_system->IsBeingDefined(m_type); } -//---------------------------------------------------------------------- // Type Completion -//---------------------------------------------------------------------- bool CompilerType::GetCompleteType() const { if (!IsValid()) @@ -283,9 +276,7 @@ return m_type_system->GetCompleteType(m_type); } -//---------------------------------------------------------------------- // AST related queries -//---------------------------------------------------------------------- size_t CompilerType::GetPointerByteSize() const { if (m_type_system) return m_type_system->GetPointerByteSize(); @@ -354,9 +345,7 @@ return 0; } -//---------------------------------------------------------------------- // Creating related types -//---------------------------------------------------------------------- CompilerType CompilerType::GetArrayElementType(uint64_t *stride) const { if (IsValid()) { @@ -490,9 +479,7 @@ return CompilerType(); } -//---------------------------------------------------------------------- // Create related types using the current type's AST -//---------------------------------------------------------------------- CompilerType CompilerType::GetBasicTypeFromAST(lldb::BasicType basic_type) const { @@ -500,9 +487,7 @@ return m_type_system->GetBasicTypeFromAST(basic_type); return CompilerType(); } -//---------------------------------------------------------------------- // Exploring the type -//---------------------------------------------------------------------- llvm::Optional<uint64_t> CompilerType::GetBitSize(ExecutionContextScope *exe_scope) const { @@ -554,7 +539,7 @@ void CompilerType::ForEachEnumerator( std::function<bool(const CompilerType &integer_type, - const ConstString &name, + ConstString name, const llvm::APSInt &value)> const &callback) const { if (IsValid()) return m_type_system->ForEachEnumerator(m_type, callback); @@ -751,9 +736,7 @@ return 0; } -//---------------------------------------------------------------------- // Dumping types -//---------------------------------------------------------------------- #define DEPTH_INCREMENT 2 void CompilerType::DumpValue(ExecutionContext *exe_ctx, Stream *s, @@ -803,6 +786,15 @@ } } +#ifndef NDEBUG +LLVM_DUMP_METHOD void CompilerType::dump() const { + if (IsValid()) + m_type_system->dump(m_type); + else + llvm::errs() << "<invalid>\n"; +} +#endif + bool CompilerType::GetValueAsScalar(const lldb_private::DataExtractor &data, lldb::offset_t data_byte_offset, size_t data_byte_size, @@ -1003,7 +995,7 @@ return false; auto byte_size = - GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL); + GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr); if (!byte_size) return false; @@ -1048,7 +1040,7 @@ return false; auto byte_size = - GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL); + GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr); if (!byte_size) return false;
diff --git a/src/llvm-project/lldb/source/Symbol/CxxModuleHandler.cpp b/src/llvm-project/lldb/source/Symbol/CxxModuleHandler.cpp new file mode 100644 index 0000000..68a2aab --- /dev/null +++ b/src/llvm-project/lldb/source/Symbol/CxxModuleHandler.cpp
@@ -0,0 +1,283 @@ +//===-- CxxModuleHandler.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/Symbol/CxxModuleHandler.h" + +#include "lldb/Symbol/ClangASTContext.h" +#include "lldb/Utility/Log.h" +#include "clang/Sema/Lookup.h" +#include "llvm/Support/Error.h" + +using namespace lldb_private; +using namespace clang; + +CxxModuleHandler::CxxModuleHandler(ASTImporter &importer, ASTContext *target) + : m_importer(&importer), + m_sema(ClangASTContext::GetASTContext(target)->getSema()) { + + std::initializer_list<const char *> supported_names = { + // containers + "deque", + "forward_list", + "list", + "queue", + "stack", + "vector", + // pointers + "shared_ptr", + "unique_ptr", + "weak_ptr", + // utility + "allocator", + }; + m_supported_templates.insert(supported_names.begin(), supported_names.end()); +} + +/// Builds a list of scopes that point into the given context. +/// +/// \param sema The sema that will be using the scopes. +/// \param ctxt The context that the scope should look into. +/// \param result A list of scopes. The scopes need to be freed by the caller +/// (except the TUScope which is owned by the sema). +static void makeScopes(Sema &sema, DeclContext *ctxt, + std::vector<Scope *> &result) { + // FIXME: The result should be a list of unique_ptrs, but the TUScope makes + // this currently impossible as it's owned by the Sema. + + if (auto parent = ctxt->getParent()) { + makeScopes(sema, parent, result); + + Scope *scope = + new Scope(result.back(), Scope::DeclScope, sema.getDiagnostics()); + scope->setEntity(ctxt); + result.push_back(scope); + } else + result.push_back(sema.TUScope); +} + +/// Uses the Sema to look up the given name in the given DeclContext. +static std::unique_ptr<LookupResult> +emulateLookupInCtxt(Sema &sema, llvm::StringRef name, DeclContext *ctxt) { + IdentifierInfo &ident = sema.getASTContext().Idents.get(name); + + std::unique_ptr<LookupResult> lookup_result; + lookup_result.reset(new LookupResult(sema, DeclarationName(&ident), + SourceLocation(), + Sema::LookupOrdinaryName)); + + // Usually during parsing we already encountered the scopes we would use. But + // here don't have these scopes so we have to emulate the behavior of the + // Sema during parsing. + std::vector<Scope *> scopes; + makeScopes(sema, ctxt, scopes); + + // Now actually perform the lookup with the sema. + sema.LookupName(*lookup_result, scopes.back()); + + // Delete all the allocated scopes beside the translation unit scope (which + // has depth 0). + for (Scope *s : scopes) + if (s->getDepth() != 0) + delete s; + + return lookup_result; +} + +/// Error class for handling problems when finding a certain DeclContext. +struct MissingDeclContext : public llvm::ErrorInfo<MissingDeclContext> { + + static char ID; + + MissingDeclContext(DeclContext *context, std::string error) + : m_context(context), m_error(error) {} + + DeclContext *m_context; + std::string m_error; + + void log(llvm::raw_ostream &OS) const override { + OS << llvm::formatv("error when reconstructing context of kind {0}:{1}", + m_context->getDeclKindName(), m_error); + } + + std::error_code convertToErrorCode() const override { + return llvm::inconvertibleErrorCode(); + } +}; + +char MissingDeclContext::ID = 0; + +/// Given a foreign decl context, this function finds the equivalent local +/// decl context in the ASTContext of the given Sema. Potentially deserializes +/// decls from the 'std' module if necessary. +static llvm::Expected<DeclContext *> +getEqualLocalDeclContext(Sema &sema, DeclContext *foreign_ctxt) { + + // Inline namespaces don't matter for lookups, so let's skip them. + while (foreign_ctxt && foreign_ctxt->isInlineNamespace()) + foreign_ctxt = foreign_ctxt->getParent(); + + // If the foreign context is the TU, we just return the local TU. + if (foreign_ctxt->isTranslationUnit()) + return sema.getASTContext().getTranslationUnitDecl(); + + // Recursively find/build the parent DeclContext. + llvm::Expected<DeclContext *> parent = + getEqualLocalDeclContext(sema, foreign_ctxt->getParent()); + if (!parent) + return parent; + + // We currently only support building namespaces. + if (foreign_ctxt->isNamespace()) { + NamedDecl *ns = llvm::dyn_cast<NamedDecl>(foreign_ctxt); + llvm::StringRef ns_name = ns->getName(); + + auto lookup_result = emulateLookupInCtxt(sema, ns_name, *parent); + for (NamedDecl *named_decl : *lookup_result) { + if (DeclContext *DC = llvm::dyn_cast<DeclContext>(named_decl)) + return DC->getPrimaryContext(); + } + return llvm::make_error<MissingDeclContext>( + foreign_ctxt, + "Couldn't find namespace " + ns->getQualifiedNameAsString()); + } + + return llvm::make_error<MissingDeclContext>(foreign_ctxt, "Unknown context "); +} + +/// Returns true iff tryInstantiateStdTemplate supports instantiating a template +/// with the given template arguments. +static bool templateArgsAreSupported(ArrayRef<TemplateArgument> a) { + for (const TemplateArgument &arg : a) { + switch (arg.getKind()) { + case TemplateArgument::Type: + case TemplateArgument::Integral: + break; + default: + // TemplateArgument kind hasn't been handled yet. + return false; + } + } + return true; +} + +/// Constructor function for Clang declarations. Ensures that the created +/// declaration is registered with the ASTImporter. +template <typename T, typename... Args> +T *createDecl(ASTImporter &importer, Decl *from_d, Args &&... args) { + T *to_d = T::Create(std::forward<Args>(args)...); + importer.RegisterImportedDecl(from_d, to_d); + return to_d; +} + +llvm::Optional<Decl *> CxxModuleHandler::tryInstantiateStdTemplate(Decl *d) { + // If we don't have a template to instiantiate, then there is nothing to do. + auto td = dyn_cast<ClassTemplateSpecializationDecl>(d); + if (!td) + return {}; + + // We only care about templates in the std namespace. + if (!td->getDeclContext()->isStdNamespace()) + return {}; + + // We have a whitelist of supported template names. + if (m_supported_templates.find(td->getName()) == m_supported_templates.end()) + return {}; + + // Early check if we even support instantiating this template. We do this + // before we import anything into the target AST. + auto &foreign_args = td->getTemplateInstantiationArgs(); + if (!templateArgsAreSupported(foreign_args.asArray())) + return {}; + + // Find the local DeclContext that corresponds to the DeclContext of our + // decl we want to import. + auto to_context = getEqualLocalDeclContext(*m_sema, td->getDeclContext()); + if (!to_context) + return {}; + + // Look up the template in our local context. + std::unique_ptr<LookupResult> lookup = + emulateLookupInCtxt(*m_sema, td->getName(), *to_context); + + ClassTemplateDecl *new_class_template = nullptr; + for (auto LD : *lookup) { + if ((new_class_template = dyn_cast<ClassTemplateDecl>(LD))) + break; + } + if (!new_class_template) + return {}; + + // Import the foreign template arguments. + llvm::SmallVector<TemplateArgument, 4> imported_args; + + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); + + // If this logic is changed, also update templateArgsAreSupported. + for (const TemplateArgument &arg : foreign_args.asArray()) { + switch (arg.getKind()) { + case TemplateArgument::Type: { + llvm::Expected<QualType> type = m_importer->Import(arg.getAsType()); + if (!type) { + LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}"); + return {}; + } + imported_args.push_back(TemplateArgument(*type)); + break; + } + case TemplateArgument::Integral: { + llvm::APSInt integral = arg.getAsIntegral(); + llvm::Expected<QualType> type = + m_importer->Import(arg.getIntegralType()); + if (!type) { + LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}"); + return {}; + } + imported_args.push_back( + TemplateArgument(d->getASTContext(), integral, *type)); + break; + } + default: + assert(false && "templateArgsAreSupported not updated?"); + } + } + + // Find the class template specialization declaration that + // corresponds to these arguments. + void *InsertPos = nullptr; + ClassTemplateSpecializationDecl *result = + new_class_template->findSpecialization(imported_args, InsertPos); + + if (result) { + // We found an existing specialization in the module that fits our arguments + // so we can treat it as the result and register it with the ASTImporter. + m_importer->RegisterImportedDecl(d, result); + return result; + } + + // Instantiate the template. + result = createDecl<ClassTemplateSpecializationDecl>( + *m_importer, d, m_sema->getASTContext(), + new_class_template->getTemplatedDecl()->getTagKind(), + new_class_template->getDeclContext(), + new_class_template->getTemplatedDecl()->getLocation(), + new_class_template->getLocation(), new_class_template, imported_args, + nullptr); + + new_class_template->AddSpecialization(result, InsertPos); + if (new_class_template->isOutOfLine()) + result->setLexicalDeclContext( + new_class_template->getLexicalDeclContext()); + return result; +} + +llvm::Optional<Decl *> CxxModuleHandler::Import(Decl *d) { + if (!isValid()) + return {}; + + return tryInstantiateStdTemplate(d); +}
diff --git a/src/llvm-project/lldb/source/Symbol/DWARFCallFrameInfo.cpp b/src/llvm-project/lldb/source/Symbol/DWARFCallFrameInfo.cpp index c8c3a10..0ab9fa4 100644 --- a/src/llvm-project/lldb/source/Symbol/DWARFCallFrameInfo.cpp +++ b/src/llvm-project/lldb/source/Symbol/DWARFCallFrameInfo.cpp
@@ -1,9 +1,8 @@ //===-- DWARFCallFrameInfo.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,12 +23,10 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // GetDwarfEHPtr // // Used for calls when the value type is specified by a DWARF EH Frame pointer // encoding. -//---------------------------------------------------------------------- static uint64_t GetGNUEHPointer(const DataExtractor &DE, offset_t *offset_ptr, uint32_t eh_ptr_enc, addr_t pc_rel_addr, addr_t text_addr, @@ -41,9 +38,7 @@ uint64_t baseAddress = 0; uint64_t addressValue = 0; const uint32_t addr_size = DE.GetAddressByteSize(); -#ifdef LLDB_CONFIGURATION_DEBUG assert(addr_size == 4 || addr_size == 8); -#endif bool signExtendValue = false; // Decode the base part or adjust our offset @@ -151,8 +146,15 @@ SectionSP §ion_sp, Type type) : m_objfile(objfile), m_section_sp(section_sp), m_type(type) {} -bool DWARFCallFrameInfo::GetUnwindPlan(Address addr, UnwindPlan &unwind_plan) { +bool DWARFCallFrameInfo::GetUnwindPlan(const Address &addr, + UnwindPlan &unwind_plan) { + return GetUnwindPlan(AddressRange(addr, 1), unwind_plan); +} + +bool DWARFCallFrameInfo::GetUnwindPlan(const AddressRange &range, + UnwindPlan &unwind_plan) { FDEEntryMap::Entry fde_entry; + Address addr = range.GetBaseAddress(); // Make sure that the Address we're searching for is the same object file as // this DWARFCallFrameInfo, we only store File offsets in m_fde_index. @@ -161,9 +163,9 @@ module_sp->GetObjectFile() != &m_objfile) return false; - if (!GetFDEEntryByFileAddress(addr.GetFileAddress(), fde_entry)) - return false; - return FDEToUnwindPlan(fde_entry.data, addr, unwind_plan); + if (llvm::Optional<FDEEntryMap::Entry> entry = GetFirstFDEEntryInRange(range)) + return FDEToUnwindPlan(entry->data, addr, unwind_plan); + return false; } bool DWARFCallFrameInfo::GetAddressRange(Address addr, AddressRange &range) { @@ -188,23 +190,21 @@ return true; } -bool DWARFCallFrameInfo::GetFDEEntryByFileAddress( - addr_t file_addr, FDEEntryMap::Entry &fde_entry) { - if (m_section_sp.get() == nullptr || m_section_sp->IsEncrypted()) - return false; +llvm::Optional<DWARFCallFrameInfo::FDEEntryMap::Entry> +DWARFCallFrameInfo::GetFirstFDEEntryInRange(const AddressRange &range) { + if (!m_section_sp || m_section_sp->IsEncrypted()) + return llvm::None; GetFDEIndex(); - if (m_fde_index.IsEmpty()) - return false; + addr_t start_file_addr = range.GetBaseAddress().GetFileAddress(); + const FDEEntryMap::Entry *fde = + m_fde_index.FindEntryThatContainsOrFollows(start_file_addr); + if (fde && fde->DoesIntersect( + FDEEntryMap::Range(start_file_addr, range.GetByteSize()))) + return *fde; - FDEEntryMap::Entry *fde = m_fde_index.FindEntryThatContains(file_addr); - - if (fde == nullptr) - return false; - - fde_entry = *fde; - return true; + return llvm::None; } void DWARFCallFrameInfo::GetFunctionAddressAndSizeVector( @@ -231,7 +231,7 @@ if (pos != m_cie_map.end()) { // Parse and cache the CIE - if (pos->second.get() == nullptr) + if (pos->second == nullptr) pos->second = ParseCIE(cie_offset); return pos->second.get(); @@ -999,61 +999,6 @@ uint32_t block_len = (uint32_t)m_cfi_data.GetULEB128(&offset); const uint8_t *block_data = (const uint8_t *)m_cfi_data.GetData(&offset, block_len); - //#if defined(__i386__) || defined(__x86_64__) - // // The EH frame info for EIP and RIP contains code that - // looks for traps to - // // be a specific type and increments the PC. - // // For i386: - // // DW_CFA_val_expression where: - // // eip = DW_OP_breg6(+28), DW_OP_deref, DW_OP_dup, - // DW_OP_plus_uconst(0x34), - // // DW_OP_deref, DW_OP_swap, DW_OP_plus_uconst(0), - // DW_OP_deref, - // // DW_OP_dup, DW_OP_lit3, DW_OP_ne, DW_OP_swap, - // DW_OP_lit4, DW_OP_ne, - // // DW_OP_and, DW_OP_plus - // // This basically does a: - // // eip = ucontenxt.mcontext32->gpr.eip; - // // if (ucontenxt.mcontext32->exc.trapno != 3 && - // ucontenxt.mcontext32->exc.trapno != 4) - // // eip++; - // // - // // For x86_64: - // // DW_CFA_val_expression where: - // // rip = DW_OP_breg3(+48), DW_OP_deref, DW_OP_dup, - // DW_OP_plus_uconst(0x90), DW_OP_deref, - // // DW_OP_swap, DW_OP_plus_uconst(0), - // DW_OP_deref_size(4), DW_OP_dup, DW_OP_lit3, - // // DW_OP_ne, DW_OP_swap, DW_OP_lit4, DW_OP_ne, - // DW_OP_and, DW_OP_plus - // // This basically does a: - // // rip = ucontenxt.mcontext64->gpr.rip; - // // if (ucontenxt.mcontext64->exc.trapno != 3 && - // ucontenxt.mcontext64->exc.trapno != 4) - // // rip++; - // // The trap comparisons and increments are not needed as - // it hoses up the unwound PC which - // // is expected to point at least past the instruction that - // causes the fault/trap. So we - // // take it out by trimming the expression right at the - // first "DW_OP_swap" opcodes - // if (block_data != NULL && thread->GetPCRegNum(Thread::GCC) - // == reg_num) - // { - // if (thread->Is64Bit()) - // { - // if (block_len > 9 && block_data[8] == DW_OP_swap - // && block_data[9] == DW_OP_plus_uconst) - // block_len = 8; - // } - // else - // { - // if (block_len > 8 && block_data[7] == DW_OP_swap - // && block_data[8] == DW_OP_plus_uconst) - // block_len = 7; - // } - // } - //#endif reg_location.SetIsDWARFExpression(block_data, block_len); row.SetRegisterInfo(reg_num, reg_location); return true;
diff --git a/src/llvm-project/lldb/source/Symbol/DebugMacros.cpp b/src/llvm-project/lldb/source/Symbol/DebugMacros.cpp index 22576ee..d119a78 100644 --- a/src/llvm-project/lldb/source/Symbol/DebugMacros.cpp +++ b/src/llvm-project/lldb/source/Symbol/DebugMacros.cpp
@@ -1,9 +1,8 @@ //===-- DebugMacros.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Symbol/DeclVendor.cpp b/src/llvm-project/lldb/source/Symbol/DeclVendor.cpp new file mode 100644 index 0000000..0a912a2 --- /dev/null +++ b/src/llvm-project/lldb/source/Symbol/DeclVendor.cpp
@@ -0,0 +1,29 @@ +//===-- DeclVendor.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/Symbol/DeclVendor.h" + +#include "lldb/Symbol/ClangASTContext.h" + +#include <vector> + +using namespace lldb; +using namespace lldb_private; + +std::vector<CompilerType> DeclVendor::FindTypes(ConstString name, + uint32_t max_matches) { + // FIXME: This depends on clang, but should be able to support any + // TypeSystem. + std::vector<CompilerType> ret; + std::vector<clang::NamedDecl *> decls; + if (FindDecls(name, /*append*/ true, max_matches, decls)) + for (auto *decl : decls) + if (auto type = ClangASTContext::GetTypeForDecl(decl)) + ret.push_back(type); + return ret; +}
diff --git a/src/llvm-project/lldb/source/Symbol/Declaration.cpp b/src/llvm-project/lldb/source/Symbol/Declaration.cpp index 83df578..d78ba96 100644 --- a/src/llvm-project/lldb/source/Symbol/Declaration.cpp +++ b/src/llvm-project/lldb/source/Symbol/Declaration.cpp
@@ -1,9 +1,8 @@ //===-- Declaration.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -84,6 +83,11 @@ return 0; } +bool Declaration::FileAndLineEqual(const Declaration &declaration) const { + int file_compare = FileSpec::Compare(this->m_file, declaration.m_file, true); + return file_compare == 0 && this->m_line == declaration.m_line; +} + bool lldb_private::operator==(const Declaration &lhs, const Declaration &rhs) { #ifdef LLDB_ENABLE_DECLARATION_COLUMNS if (lhs.GetColumn() == rhs.GetColumn())
diff --git a/src/llvm-project/lldb/source/Symbol/FuncUnwinders.cpp b/src/llvm-project/lldb/source/Symbol/FuncUnwinders.cpp index 35ce72f..09cb9b0 100644 --- a/src/llvm-project/lldb/source/Symbol/FuncUnwinders.cpp +++ b/src/llvm-project/lldb/source/Symbol/FuncUnwinders.cpp
@@ -1,9 +1,8 @@ //===-- FuncUnwinders.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,22 +13,24 @@ #include "lldb/Symbol/CompactUnwindInfo.h" #include "lldb/Symbol/DWARFCallFrameInfo.h" #include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/SymbolFile.h" #include "lldb/Symbol/UnwindPlan.h" #include "lldb/Symbol/UnwindTable.h" #include "lldb/Target/ABI.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" +#include "lldb/Target/RegisterContext.h" #include "lldb/Target/RegisterNumber.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/UnwindAssembly.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -//------------------------------------------------ /// constructor -//------------------------------------------------ FuncUnwinders::FuncUnwinders(UnwindTable &unwind_table, AddressRange range) : m_unwind_table(unwind_table), m_range(range), m_mutex(), @@ -43,35 +44,35 @@ m_tried_unwind_plan_eh_frame_augmented(false), m_tried_unwind_plan_debug_frame_augmented(false), m_tried_unwind_plan_compact_unwind(false), - m_tried_unwind_plan_arm_unwind(false), m_tried_unwind_fast(false), + m_tried_unwind_plan_arm_unwind(false), + m_tried_unwind_plan_symbol_file(false), m_tried_unwind_fast(false), m_tried_unwind_arch_default(false), m_tried_unwind_arch_default_at_func_entry(false), m_first_non_prologue_insn() {} -//------------------------------------------------ /// destructor -//------------------------------------------------ FuncUnwinders::~FuncUnwinders() {} UnwindPlanSP FuncUnwinders::GetUnwindPlanAtCallSite(Target &target, - int current_offset) { + Thread &thread) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - if (UnwindPlanSP plan_sp = GetEHFrameUnwindPlan(target, current_offset)) + if (UnwindPlanSP plan_sp = GetSymbolFileUnwindPlan(thread)) return plan_sp; - if (UnwindPlanSP plan_sp = GetDebugFrameUnwindPlan(target, current_offset)) + if (UnwindPlanSP plan_sp = GetDebugFrameUnwindPlan(target)) return plan_sp; - if (UnwindPlanSP plan_sp = GetCompactUnwindUnwindPlan(target, current_offset)) + if (UnwindPlanSP plan_sp = GetEHFrameUnwindPlan(target)) return plan_sp; - if (UnwindPlanSP plan_sp = GetArmUnwindUnwindPlan(target, current_offset)) + if (UnwindPlanSP plan_sp = GetCompactUnwindUnwindPlan(target)) + return plan_sp; + if (UnwindPlanSP plan_sp = GetArmUnwindUnwindPlan(target)) return plan_sp; return nullptr; } -UnwindPlanSP FuncUnwinders::GetCompactUnwindUnwindPlan(Target &target, - int current_offset) { +UnwindPlanSP FuncUnwinders::GetCompactUnwindUnwindPlan(Target &target) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_unwind_plan_compact_unwind.size() > 0) return m_unwind_plan_compact_unwind[0]; // FIXME support multiple compact @@ -82,8 +83,6 @@ m_tried_unwind_plan_compact_unwind = true; if (m_range.GetBaseAddress().IsValid()) { Address current_pc(m_range.GetBaseAddress()); - if (current_offset != -1) - current_pc.SetOffset(current_pc.GetOffset() + current_offset); CompactUnwindInfo *compact_unwind = m_unwind_table.GetCompactUnwindInfo(); if (compact_unwind) { UnwindPlanSP unwind_plan_sp(new UnwindPlan(lldb::eRegisterKindGeneric)); @@ -98,53 +97,43 @@ return UnwindPlanSP(); } -UnwindPlanSP FuncUnwinders::GetEHFrameUnwindPlan(Target &target, - int current_offset) { +UnwindPlanSP FuncUnwinders::GetEHFrameUnwindPlan(Target &target) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_unwind_plan_eh_frame_sp.get() || m_tried_unwind_plan_eh_frame) return m_unwind_plan_eh_frame_sp; m_tried_unwind_plan_eh_frame = true; if (m_range.GetBaseAddress().IsValid()) { - Address current_pc(m_range.GetBaseAddress()); - if (current_offset != -1) - current_pc.SetOffset(current_pc.GetOffset() + current_offset); DWARFCallFrameInfo *eh_frame = m_unwind_table.GetEHFrameInfo(); if (eh_frame) { - m_unwind_plan_eh_frame_sp.reset( - new UnwindPlan(lldb::eRegisterKindGeneric)); - if (!eh_frame->GetUnwindPlan(current_pc, *m_unwind_plan_eh_frame_sp)) + m_unwind_plan_eh_frame_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); + if (!eh_frame->GetUnwindPlan(m_range, *m_unwind_plan_eh_frame_sp)) m_unwind_plan_eh_frame_sp.reset(); } } return m_unwind_plan_eh_frame_sp; } -UnwindPlanSP FuncUnwinders::GetDebugFrameUnwindPlan(Target &target, - int current_offset) { +UnwindPlanSP FuncUnwinders::GetDebugFrameUnwindPlan(Target &target) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_unwind_plan_debug_frame_sp || m_tried_unwind_plan_debug_frame) return m_unwind_plan_debug_frame_sp; m_tried_unwind_plan_debug_frame = true; if (m_range.GetBaseAddress().IsValid()) { - Address current_pc(m_range.GetBaseAddress()); - if (current_offset != -1) - current_pc.SetOffset(current_pc.GetOffset() + current_offset); DWARFCallFrameInfo *debug_frame = m_unwind_table.GetDebugFrameInfo(); if (debug_frame) { - m_unwind_plan_debug_frame_sp.reset( - new UnwindPlan(lldb::eRegisterKindGeneric)); - if (!debug_frame->GetUnwindPlan(current_pc, - *m_unwind_plan_debug_frame_sp)) + m_unwind_plan_debug_frame_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); + if (!debug_frame->GetUnwindPlan(m_range, *m_unwind_plan_debug_frame_sp)) m_unwind_plan_debug_frame_sp.reset(); } } return m_unwind_plan_debug_frame_sp; } -UnwindPlanSP FuncUnwinders::GetArmUnwindUnwindPlan(Target &target, - int current_offset) { +UnwindPlanSP FuncUnwinders::GetArmUnwindUnwindPlan(Target &target) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_unwind_plan_arm_unwind_sp.get() || m_tried_unwind_plan_arm_unwind) return m_unwind_plan_arm_unwind_sp; @@ -152,12 +141,10 @@ m_tried_unwind_plan_arm_unwind = true; if (m_range.GetBaseAddress().IsValid()) { Address current_pc(m_range.GetBaseAddress()); - if (current_offset != -1) - current_pc.SetOffset(current_pc.GetOffset() + current_offset); ArmUnwindInfo *arm_unwind_info = m_unwind_table.GetArmUnwindInfo(); if (arm_unwind_info) { - m_unwind_plan_arm_unwind_sp.reset( - new UnwindPlan(lldb::eRegisterKindGeneric)); + m_unwind_plan_arm_unwind_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); if (!arm_unwind_info->GetUnwindPlan(target, current_pc, *m_unwind_plan_arm_unwind_sp)) m_unwind_plan_arm_unwind_sp.reset(); @@ -166,9 +153,40 @@ return m_unwind_plan_arm_unwind_sp; } +namespace { +class RegisterContextToInfo: public SymbolFile::RegisterInfoResolver { +public: + RegisterContextToInfo(RegisterContext &ctx) : m_ctx(ctx) {} + + const RegisterInfo *ResolveName(llvm::StringRef name) const { + return m_ctx.GetRegisterInfoByName(name); + } + const RegisterInfo *ResolveNumber(lldb::RegisterKind kind, + uint32_t number) const { + return m_ctx.GetRegisterInfo(kind, number); + } + +private: + RegisterContext &m_ctx; +}; +} // namespace + +UnwindPlanSP FuncUnwinders::GetSymbolFileUnwindPlan(Thread &thread) { + std::lock_guard<std::recursive_mutex> guard(m_mutex); + if (m_unwind_plan_symbol_file_sp.get() || m_tried_unwind_plan_symbol_file) + return m_unwind_plan_symbol_file_sp; + + m_tried_unwind_plan_symbol_file = true; + if (SymbolFile *symfile = m_unwind_table.GetSymbolFile()) { + m_unwind_plan_symbol_file_sp = symfile->GetUnwindPlan( + m_range.GetBaseAddress(), + RegisterContextToInfo(*thread.GetRegisterContext())); + } + return m_unwind_plan_symbol_file_sp; +} + UnwindPlanSP FuncUnwinders::GetEHFrameAugmentedUnwindPlan(Target &target, - Thread &thread, - int current_offset) { + Thread &thread) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_unwind_plan_eh_frame_augmented_sp.get() || m_tried_unwind_plan_eh_frame_augmented) @@ -186,11 +204,12 @@ m_tried_unwind_plan_eh_frame_augmented = true; - UnwindPlanSP eh_frame_plan = GetEHFrameUnwindPlan(target, current_offset); + UnwindPlanSP eh_frame_plan = GetEHFrameUnwindPlan(target); if (!eh_frame_plan) return m_unwind_plan_eh_frame_augmented_sp; - m_unwind_plan_eh_frame_augmented_sp.reset(new UnwindPlan(*eh_frame_plan)); + m_unwind_plan_eh_frame_augmented_sp = + std::make_shared<UnwindPlan>(*eh_frame_plan); // Augment the eh_frame instructions with epilogue descriptions if necessary // so the UnwindPlan can be used at any instruction in the function. @@ -207,9 +226,8 @@ return m_unwind_plan_eh_frame_augmented_sp; } -UnwindPlanSP -FuncUnwinders::GetDebugFrameAugmentedUnwindPlan(Target &target, Thread &thread, - int current_offset) { +UnwindPlanSP FuncUnwinders::GetDebugFrameAugmentedUnwindPlan(Target &target, + Thread &thread) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_unwind_plan_debug_frame_augmented_sp.get() || m_tried_unwind_plan_debug_frame_augmented) @@ -227,13 +245,12 @@ m_tried_unwind_plan_debug_frame_augmented = true; - UnwindPlanSP debug_frame_plan = - GetDebugFrameUnwindPlan(target, current_offset); + UnwindPlanSP debug_frame_plan = GetDebugFrameUnwindPlan(target); if (!debug_frame_plan) return m_unwind_plan_debug_frame_augmented_sp; - m_unwind_plan_debug_frame_augmented_sp.reset( - new UnwindPlan(*debug_frame_plan)); + m_unwind_plan_debug_frame_augmented_sp = + std::make_shared<UnwindPlan>(*debug_frame_plan); // Augment the debug_frame instructions with epilogue descriptions if // necessary so the UnwindPlan can be used at any instruction in the @@ -251,8 +268,7 @@ } UnwindPlanSP FuncUnwinders::GetAssemblyUnwindPlan(Target &target, - Thread &thread, - int current_offset) { + Thread &thread) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_unwind_plan_assembly_sp.get() || m_tried_unwind_plan_assembly || !m_unwind_table.GetAllowAssemblyEmulationUnwindPlans()) { @@ -263,7 +279,8 @@ UnwindAssemblySP assembly_profiler_sp(GetUnwindAssemblyProfiler(target)); if (assembly_profiler_sp) { - m_unwind_plan_assembly_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric)); + m_unwind_plan_assembly_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); if (!assembly_profiler_sp->GetNonCallSiteUnwindPlanFromAssembly( m_range, thread, *m_unwind_plan_assembly_sp)) { m_unwind_plan_assembly_sp.reset(); @@ -307,16 +324,14 @@ } UnwindPlanSP FuncUnwinders::GetUnwindPlanAtNonCallSite(Target &target, - Thread &thread, - int current_offset) { - UnwindPlanSP eh_frame_sp = GetEHFrameUnwindPlan(target, current_offset); + Thread &thread) { + UnwindPlanSP eh_frame_sp = GetEHFrameUnwindPlan(target); if (!eh_frame_sp) - eh_frame_sp = GetDebugFrameUnwindPlan(target, current_offset); + eh_frame_sp = GetDebugFrameUnwindPlan(target); UnwindPlanSP arch_default_at_entry_sp = GetUnwindPlanArchitectureDefaultAtFunctionEntry(thread); UnwindPlanSP arch_default_sp = GetUnwindPlanArchitectureDefault(thread); - UnwindPlanSP assembly_sp = - GetAssemblyUnwindPlan(target, thread, current_offset); + UnwindPlanSP assembly_sp = GetAssemblyUnwindPlan(target, thread); // This point of this code is to detect when a function is using a non- // standard ABI, and the eh_frame correctly describes that alternate ABI. @@ -345,11 +360,11 @@ return eh_frame_sp; } - if (UnwindPlanSP plan_sp = - GetEHFrameAugmentedUnwindPlan(target, thread, current_offset)) + if (UnwindPlanSP plan_sp = GetSymbolFileUnwindPlan(thread)) return plan_sp; - if (UnwindPlanSP plan_sp = - GetDebugFrameAugmentedUnwindPlan(target, thread, current_offset)) + if (UnwindPlanSP plan_sp = GetDebugFrameAugmentedUnwindPlan(target, thread)) + return plan_sp; + if (UnwindPlanSP plan_sp = GetEHFrameAugmentedUnwindPlan(target, thread)) return plan_sp; return assembly_sp; @@ -365,7 +380,8 @@ UnwindAssemblySP assembly_profiler_sp(GetUnwindAssemblyProfiler(target)); if (assembly_profiler_sp) { - m_unwind_plan_fast_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric)); + m_unwind_plan_fast_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); if (!assembly_profiler_sp->GetFastUnwindPlan(m_range, thread, *m_unwind_plan_fast_sp)) { m_unwind_plan_fast_sp.reset(); @@ -386,8 +402,8 @@ if (process_sp) { ABI *abi = process_sp->GetABI().get(); if (abi) { - m_unwind_plan_arch_default_sp.reset( - new UnwindPlan(lldb::eRegisterKindGeneric)); + m_unwind_plan_arch_default_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); if (!abi->CreateDefaultUnwindPlan(*m_unwind_plan_arch_default_sp)) { m_unwind_plan_arch_default_sp.reset(); } @@ -411,8 +427,8 @@ if (process_sp) { ABI *abi = process_sp->GetABI().get(); if (abi) { - m_unwind_plan_arch_default_at_func_entry_sp.reset( - new UnwindPlan(lldb::eRegisterKindGeneric)); + m_unwind_plan_arch_default_at_func_entry_sp = + std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric); if (!abi->CreateFunctionEntryUnwindPlan( *m_unwind_plan_arch_default_at_func_entry_sp)) { m_unwind_plan_arch_default_at_func_entry_sp.reset(); @@ -453,9 +469,9 @@ Address FuncUnwinders::GetLSDAAddress(Target &target) { Address lsda_addr; - UnwindPlanSP unwind_plan_sp = GetEHFrameUnwindPlan(target, -1); + UnwindPlanSP unwind_plan_sp = GetEHFrameUnwindPlan(target); if (unwind_plan_sp.get() == nullptr) { - unwind_plan_sp = GetCompactUnwindUnwindPlan(target, -1); + unwind_plan_sp = GetCompactUnwindUnwindPlan(target); } if (unwind_plan_sp.get() && unwind_plan_sp->GetLSDAAddress().IsValid()) { lsda_addr = unwind_plan_sp->GetLSDAAddress(); @@ -466,9 +482,9 @@ Address FuncUnwinders::GetPersonalityRoutinePtrAddress(Target &target) { Address personality_addr; - UnwindPlanSP unwind_plan_sp = GetEHFrameUnwindPlan(target, -1); + UnwindPlanSP unwind_plan_sp = GetEHFrameUnwindPlan(target); if (unwind_plan_sp.get() == nullptr) { - unwind_plan_sp = GetCompactUnwindUnwindPlan(target, -1); + unwind_plan_sp = GetCompactUnwindUnwindPlan(target); } if (unwind_plan_sp.get() && unwind_plan_sp->GetPersonalityFunctionPtr().IsValid()) {
diff --git a/src/llvm-project/lldb/source/Symbol/Function.cpp b/src/llvm-project/lldb/source/Symbol/Function.cpp index f792a5c..951392c 100644 --- a/src/llvm-project/lldb/source/Symbol/Function.cpp +++ b/src/llvm-project/lldb/source/Symbol/Function.cpp
@@ -1,9 +1,8 @@ //===-- Function.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,14 +24,12 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Basic function information is contained in the FunctionInfo class. It is // designed to contain the name, linkage name, and declaration location. -//---------------------------------------------------------------------- FunctionInfo::FunctionInfo(const char *name, const Declaration *decl_ptr) : m_name(name), m_declaration(decl_ptr) {} -FunctionInfo::FunctionInfo(const ConstString &name, const Declaration *decl_ptr) +FunctionInfo::FunctionInfo(ConstString name, const Declaration *decl_ptr) : m_name(name), m_declaration(decl_ptr) {} FunctionInfo::~FunctionInfo() {} @@ -69,7 +66,7 @@ : FunctionInfo(name, decl_ptr), m_mangled(ConstString(mangled), true), m_call_decl(call_decl_ptr) {} -InlineFunctionInfo::InlineFunctionInfo(const ConstString &name, +InlineFunctionInfo::InlineFunctionInfo(ConstString name, const Mangled &mangled, const Declaration *decl_ptr, const Declaration *call_decl_ptr) @@ -130,9 +127,7 @@ return FunctionInfo::MemorySize() + m_mangled.MemorySize(); } -//---------------------------------------------------------------------- // -//---------------------------------------------------------------------- CallEdge::CallEdge(const char *symbol_name, lldb::addr_t return_pc) : return_pc(return_pc), resolved(false) { lazy_callee.symbol_name = symbol_name; @@ -183,15 +178,13 @@ return base.GetLoadAddress(&target) + return_pc; } -//---------------------------------------------------------------------- // -//---------------------------------------------------------------------- Function::Function(CompileUnit *comp_unit, lldb::user_id_t func_uid, lldb::user_id_t type_uid, const Mangled &mangled, Type *type, const AddressRange &range) : UserID(func_uid), m_comp_unit(comp_unit), m_type_uid(type_uid), m_type(type), m_mangled(mangled), m_block(func_uid), m_range(range), - m_frame_base(nullptr), m_flags(), m_prologue_byte_size(0) { + m_frame_base(), m_flags(), m_prologue_byte_size(0) { m_block.SetParentScope(this); assert(comp_unit != nullptr); } @@ -553,7 +546,7 @@ // Now calculate the offset to pass the subsequent line 0 entries. uint32_t first_non_zero_line = prologue_end_line_idx; - while (1) { + while (true) { LineEntry line_entry; if (line_table->GetLineEntryAtIndex(first_non_zero_line, line_entry)) { @@ -596,10 +589,14 @@ } lldb::LanguageType Function::GetLanguage() const { + lldb::LanguageType lang = m_mangled.GuessLanguage(); + if (lang != lldb::eLanguageTypeUnknown) + return lang; + if (m_comp_unit) return m_comp_unit->GetLanguage(); - else - return lldb::eLanguageTypeUnknown; + + return lldb::eLanguageTypeUnknown; } ConstString Function::GetName() const {
diff --git a/src/llvm-project/lldb/source/Symbol/LineEntry.cpp b/src/llvm-project/lldb/source/Symbol/LineEntry.cpp index bffcc53..959a327 100644 --- a/src/llvm-project/lldb/source/Symbol/LineEntry.cpp +++ b/src/llvm-project/lldb/source/Symbol/LineEntry.cpp
@@ -1,9 +1,8 @@ //===-- LineEntry.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -191,40 +190,62 @@ return FileSpec::Compare(a.file, b.file, true); } -AddressRange LineEntry::GetSameLineContiguousAddressRange() const { +AddressRange LineEntry::GetSameLineContiguousAddressRange( + bool include_inlined_functions) const { // Add each LineEntry's range to complete_line_range until we find a // different file / line number. AddressRange complete_line_range = range; + auto symbol_context_scope = lldb::eSymbolContextLineEntry; + Declaration start_call_site(original_file, line); + if (include_inlined_functions) + symbol_context_scope |= lldb::eSymbolContextBlock; while (true) { SymbolContext next_line_sc; Address range_end(complete_line_range.GetBaseAddress()); range_end.Slide(complete_line_range.GetByteSize()); - range_end.CalculateSymbolContext(&next_line_sc, - lldb::eSymbolContextLineEntry); + range_end.CalculateSymbolContext(&next_line_sc, symbol_context_scope); - if (next_line_sc.line_entry.IsValid() && - next_line_sc.line_entry.range.GetByteSize() > 0 && - original_file == next_line_sc.line_entry.original_file) { + if (!next_line_sc.line_entry.IsValid() || + next_line_sc.line_entry.range.GetByteSize() == 0) + break; + + if (original_file == next_line_sc.line_entry.original_file && + (next_line_sc.line_entry.line == 0 || + line == next_line_sc.line_entry.line)) { // Include any line 0 entries - they indicate that this is compiler- // generated code that does not correspond to user source code. - if (next_line_sc.line_entry.line == 0) { - complete_line_range.SetByteSize( - complete_line_range.GetByteSize() + - next_line_sc.line_entry.range.GetByteSize()); - continue; - } - - if (line == next_line_sc.line_entry.line) { - // next_line_sc is the same file & line as this LineEntry, so extend - // our AddressRange by its size and continue to see if there are more - // LineEntries that we can combine. - complete_line_range.SetByteSize( - complete_line_range.GetByteSize() + - next_line_sc.line_entry.range.GetByteSize()); - continue; - } + // next_line_sc is the same file & line as this LineEntry, so extend + // our AddressRange by its size and continue to see if there are more + // LineEntries that we can combine. However, if there was nothing to + // extend we're done. + if (!complete_line_range.Extend(next_line_sc.line_entry.range)) + break; + continue; } + + if (include_inlined_functions && next_line_sc.block && + next_line_sc.block->GetContainingInlinedBlock() != nullptr) { + // The next_line_sc might be in a different file if it's an inlined + // function. If this is the case then we still want to expand our line + // range to include them if the inlined function is at the same call site + // as this line entry. The current block could represent a nested inline + // function call so we need to need to check up the block tree to see if + // we find one. + auto inlined_parent_block = + next_line_sc.block->GetContainingInlinedBlockWithCallSite( + start_call_site); + if (!inlined_parent_block) + // We didn't find any parent inlined block with a call site at this line + // entry so this inlined function is probably at another line. + break; + // Extend our AddressRange by the size of the inlined block, but if there + // was nothing to add then we're done. + if (!complete_line_range.Extend(next_line_sc.line_entry.range)) + break; + continue; + } + break; } return complete_line_range;
diff --git a/src/llvm-project/lldb/source/Symbol/LineTable.cpp b/src/llvm-project/lldb/source/Symbol/LineTable.cpp index 06e3021..8d4d72c 100644 --- a/src/llvm-project/lldb/source/Symbol/LineTable.cpp +++ b/src/llvm-project/lldb/source/Symbol/LineTable.cpp
@@ -1,9 +1,8 @@ //===-- LineTable.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,15 +17,11 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // LineTable constructor -//---------------------------------------------------------------------- LineTable::LineTable(CompileUnit *comp_unit) : m_comp_unit(comp_unit), m_entries() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- LineTable::~LineTable() {} void LineTable::InsertLineEntry(lldb::addr_t file_addr, uint32_t line, @@ -126,7 +121,7 @@ pos++; } -#ifdef LLDB_CONFIGURATION_DEBUG +#ifndef NDEBUG // If we aren't inserting at the beginning, the previous entry should // terminate a sequence. if (pos != begin_pos) { @@ -137,7 +132,6 @@ m_entries.insert(pos, seq->m_entries.begin(), seq->m_entries.end()); } -//---------------------------------------------------------------------- LineTable::Entry::LessThanBinaryPredicate::LessThanBinaryPredicate( LineTable *line_table) : m_line_table(line_table) {} @@ -445,7 +439,7 @@ } LineTable *LineTable::LinkLineTable(const FileRangeMap &file_range_map) { - std::unique_ptr<LineTable> line_table_ap(new LineTable(m_comp_unit)); + std::unique_ptr<LineTable> line_table_up(new LineTable(m_comp_unit)); LineSequenceImpl sequence; const size_t count = m_entries.size(); LineEntry line_entry; @@ -508,7 +502,7 @@ sequence.m_entries.back().is_terminal_entry = true; // Append the sequence since we just terminated the previous one - line_table_ap->InsertSequence(&sequence); + line_table_up->InsertSequence(&sequence); sequence.Clear(); } @@ -524,7 +518,7 @@ // insert this sequence into our new line table. if (!sequence.m_entries.empty() && sequence.m_entries.back().is_terminal_entry) { - line_table_ap->InsertSequence(&sequence); + line_table_up->InsertSequence(&sequence); sequence.Clear(); prev_entry_was_linked = false; } else { @@ -533,7 +527,7 @@ prev_file_addr = entry.file_addr; range_changed = false; } - if (line_table_ap->m_entries.empty()) + if (line_table_up->m_entries.empty()) return nullptr; - return line_table_ap.release(); + return line_table_up.release(); }
diff --git a/src/llvm-project/lldb/source/Host/common/Symbols.cpp b/src/llvm-project/lldb/source/Symbol/LocateSymbolFile.cpp similarity index 89% rename from src/llvm-project/lldb/source/Host/common/Symbols.cpp rename to src/llvm-project/lldb/source/Symbol/LocateSymbolFile.cpp index ed1677c..bfdb6e7 100644 --- a/src/llvm-project/lldb/source/Host/common/Symbols.cpp +++ b/src/llvm-project/lldb/source/Symbol/LocateSymbolFile.cpp
@@ -1,17 +1,17 @@ -//===-- Symbols.cpp ---------------------------------------------*- C++ -*-===// +//===-- LocateSymbolFile.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/Symbols.h" +#include "lldb/Symbol/LocateSymbolFile.h" + +#include "lldb/Core/ModuleList.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/FileSystem.h" #include "lldb/Symbol/ObjectFile.h" -#include "lldb/Target/Target.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/DataBuffer.h" #include "lldb/Utility/DataExtractor.h" @@ -55,9 +55,10 @@ bool got_spec = module_specs.GetModuleSpecAtIndex(i, spec); UNUSED_IF_ASSERT_DISABLED(got_spec); assert(got_spec); - if ((uuid == NULL || (spec.GetUUIDPtr() && spec.GetUUID() == *uuid)) && - (arch == NULL || (spec.GetArchitecturePtr() && - spec.GetArchitecture().IsCompatibleMatch(*arch)))) { + if ((uuid == nullptr || (spec.GetUUIDPtr() && spec.GetUUID() == *uuid)) && + (arch == nullptr || + (spec.GetArchitecturePtr() && + spec.GetArchitecture().IsCompatibleMatch(*arch)))) { return true; } } @@ -67,8 +68,8 @@ // Given a binary exec_fspec, and a ModuleSpec with an architecture/uuid, // return true if there is a matching dSYM bundle next to the exec_fspec, -// and return that value in dsym_fspec. -// If there is a .dSYM.yaa compressed archive next to the exec_fspec, +// and return that value in dsym_fspec. +// If there is a .dSYM.yaa compressed archive next to the exec_fspec, // call through Symbols::DownloadObjectAndSymbolFile to download the // expanded/uncompressed dSYM and return that filepath in dsym_fspec. @@ -100,9 +101,9 @@ // See if we have "../CF.framework" - so we'll look for // CF.framework.dSYM/Contents/Resources/DWARF/CF - // We need to drop the last suffix after '.' to match + // We need to drop the last suffix after '.' to match // 'CF' in the DWARF subdir. - std::string binary_name (filename.AsCString()); + std::string binary_name(filename.AsCString()); auto last_dot = binary_name.find_last_of('.'); if (last_dot != std::string::npos) { binary_name.erase(last_dot); @@ -153,11 +154,13 @@ Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); const FileSpec &exec_fspec = module_spec.GetFileSpec(); if (exec_fspec) { - if (::LookForDsymNextToExecutablePath (module_spec, exec_fspec, dsym_fspec)) { - if (log) { - log->Printf("dSYM with matching UUID & arch found at %s", dsym_fspec.GetPath().c_str()); - } - return true; + if (::LookForDsymNextToExecutablePath(module_spec, exec_fspec, + dsym_fspec)) { + if (log) { + log->Printf("dSYM with matching UUID & arch found at %s", + dsym_fspec.GetPath().c_str()); + } + return true; } else { FileSpec parent_dirs = exec_fspec; @@ -183,7 +186,8 @@ if (fn == nullptr) break; if (::strchr(fn, '.') != nullptr) { - if (::LookForDsymNextToExecutablePath (module_spec, parent_dirs, dsym_fspec)) { + if (::LookForDsymNextToExecutablePath(module_spec, parent_dirs, + dsym_fspec)) { if (log) { log->Printf("dSYM with matching UUID & arch found at %s", dsym_fspec.GetPath().c_str()); @@ -249,7 +253,9 @@ // Keep "symbols.enable-external-lookup" description in sync with this function. -FileSpec Symbols::LocateExecutableSymbolFile(const ModuleSpec &module_spec) { +FileSpec +Symbols::LocateExecutableSymbolFile(const ModuleSpec &module_spec, + const FileSpecList &default_search_paths) { FileSpec symbol_file_spec = module_spec.GetSymbolFileSpec(); if (symbol_file_spec.IsAbsolute() && FileSystem::Instance().Exists(symbol_file_spec)) @@ -257,15 +263,15 @@ const char *symbol_filename = symbol_file_spec.GetFilename().AsCString(); if (symbol_filename && symbol_filename[0]) { - FileSpecList debug_file_search_paths( - Target::GetDefaultDebugFileSearchPaths()); + FileSpecList debug_file_search_paths = default_search_paths; // Add module directory. FileSpec module_file_spec = module_spec.GetFileSpec(); // We keep the unresolved pathname if it fails. - FileSystem::Instance().ResolveSymbolicLink(module_file_spec, module_file_spec); + FileSystem::Instance().ResolveSymbolicLink(module_file_spec, + module_file_spec); - const ConstString &file_dir = module_file_spec.GetDirectory(); + ConstString file_dir = module_file_spec.GetDirectory(); { FileSpec file_spec(file_dir.AsCString(".")); FileSystem::Instance().Resolve(file_spec); @@ -307,7 +313,7 @@ // /usr/lib/debug/.build-id/ff/e7fe727889ad82bb153de2ad065b2189693315.debug uuid_str = module_uuid.GetAsString(""); std::transform(uuid_str.begin(), uuid_str.end(), uuid_str.begin(), - ::tolower); + ::tolower); uuid_str.insert(2, 1, '/'); uuid_str = uuid_str + ".debug"; }
diff --git a/src/llvm-project/lldb/source/Host/macosx/Symbols.cpp b/src/llvm-project/lldb/source/Symbol/LocateSymbolFileMacOSX.cpp similarity index 93% rename from src/llvm-project/lldb/source/Host/macosx/Symbols.cpp rename to src/llvm-project/lldb/source/Symbol/LocateSymbolFileMacOSX.cpp index 980bbc3..4e16382 100644 --- a/src/llvm-project/lldb/source/Host/macosx/Symbols.cpp +++ b/src/llvm-project/lldb/source/Symbol/LocateSymbolFileMacOSX.cpp
@@ -1,15 +1,15 @@ -//===-- Symbols.cpp ---------------------------------------------*- C++ -*-===// +//===-- LocateSymbolFileMacOSX.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Host/Symbols.h" +#include "lldb/Symbol/LocateSymbolFile.h" #include <dirent.h> +#include <dlfcn.h> #include <pwd.h> #include <CoreFoundation/CoreFoundation.h> @@ -38,14 +38,8 @@ using namespace lldb; using namespace lldb_private; -#if !defined(__arm__) && !defined(__arm64__) && \ - !defined(__aarch64__) // No DebugSymbols on the iOS devices -extern "C" { - -CFURLRef DBGCopyFullDSYMURLForUUID(CFUUIDRef uuid, CFURLRef exec_url); -CFDictionaryRef DBGCopyDSYMPropertyLists(CFURLRef dsym_url); -} -#endif +static CFURLRef (*g_dlsym_DBGCopyFullDSYMURLForUUID)(CFUUIDRef uuid, CFURLRef exec_url) = nullptr; +static CFDictionaryRef (*g_dlsym_DBGCopyDSYMPropertyLists)(CFURLRef dsym_url) = nullptr; int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec &module_spec, ModuleSpec &return_module_spec) { @@ -55,15 +49,26 @@ log->Printf("Spotlight lookup for .dSYM bundles is disabled."); return 0; } - + return_module_spec = module_spec; return_module_spec.GetFileSpec().Clear(); return_module_spec.GetSymbolFileSpec().Clear(); int items_found = 0; -#if !defined(__arm__) && !defined(__arm64__) && \ - !defined(__aarch64__) // No DebugSymbols on the iOS devices + if (g_dlsym_DBGCopyFullDSYMURLForUUID == nullptr || + g_dlsym_DBGCopyDSYMPropertyLists == nullptr) { + void *handle = dlopen ("/System/Library/PrivateFrameworks/DebugSymbols.framework/DebugSymbols", RTLD_LAZY | RTLD_LOCAL); + if (handle) { + g_dlsym_DBGCopyFullDSYMURLForUUID = (CFURLRef (*)(CFUUIDRef, CFURLRef)) dlsym (handle, "DBGCopyFullDSYMURLForUUID"); + g_dlsym_DBGCopyDSYMPropertyLists = (CFDictionaryRef (*)(CFURLRef)) dlsym (handle, "DBGCopyDSYMPropertyLists"); + } + } + + if (g_dlsym_DBGCopyFullDSYMURLForUUID == nullptr || + g_dlsym_DBGCopyDSYMPropertyLists == nullptr) { + return items_found; + } const UUID *uuid = module_spec.GetUUIDPtr(); const ArchSpec *arch = module_spec.GetArchitecturePtr(); @@ -90,7 +95,7 @@ } CFCReleaser<CFURLRef> dsym_url( - ::DBGCopyFullDSYMURLForUUID(module_uuid_ref.get(), exec_url.get())); + g_dlsym_DBGCopyFullDSYMURLForUUID(module_uuid_ref.get(), exec_url.get())); char path[PATH_MAX]; if (dsym_url.get()) { @@ -126,7 +131,7 @@ } CFCReleaser<CFDictionaryRef> dict( - ::DBGCopyDSYMPropertyLists(dsym_url.get())); + g_dlsym_DBGCopyDSYMPropertyLists(dsym_url.get())); CFDictionaryRef uuid_dict = NULL; if (dict.get()) { CFCString uuid_cfstr(uuid->GetAsString().c_str()); @@ -237,8 +242,6 @@ } } } -#endif // #if !defined (__arm__) && !defined (__arm64__) && !defined - // (__aarch64__) return items_found; } @@ -423,8 +426,8 @@ source_path.RemoveLastPathComponent(); source_path.RemoveLastPathComponent(); module_spec.GetSourceMappingList().Append( - ConstString(build_path.GetPath().c_str()), - ConstString(source_path.GetPath().c_str()), true); + ConstString(build_path.GetPath().c_str()), + ConstString(source_path.GetPath().c_str()), true); } } } @@ -435,7 +438,6 @@ } } - // If we have a DBGBuildSourcePath + DBGSourcePath pair, append them to the // source remappings list. @@ -593,7 +595,7 @@ &signo, // Signal int * &command_output, // Command output std::chrono::seconds( - 30), // Large timeout to allow for long dsym download times + 120), // Large timeout to allow for long dsym download times false); // Don't run in a shell (we don't need shell expansion) if (error.Success() && exit_status == 0 && !command_output.empty()) { CFCData data(CFDataCreateWithBytesNoCopy(
diff --git a/src/llvm-project/lldb/source/Symbol/ObjectFile.cpp b/src/llvm-project/lldb/source/Symbol/ObjectFile.cpp index 86c18c7..172d2b3 100644 --- a/src/llvm-project/lldb/source/Symbol/ObjectFile.cpp +++ b/src/llvm-project/lldb/source/Symbol/ObjectFile.cpp
@@ -1,9 +1,8 @@ //===-- ObjectFile.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -57,13 +56,13 @@ PluginManager::GetObjectContainerCreateCallbackAtIndex( idx)) != nullptr; ++idx) { - std::unique_ptr<ObjectContainer> object_container_ap( + std::unique_ptr<ObjectContainer> object_container_up( create_object_container_callback(module_sp, data_sp, data_offset, file, file_offset, file_size)); - if (object_container_ap.get()) - object_file_sp = object_container_ap->GetObjectFile(file); + if (object_container_up) + object_file_sp = object_container_up->GetObjectFile(file); if (object_file_sp.get()) return object_file_sp; @@ -106,13 +105,13 @@ PluginManager::GetObjectContainerCreateCallbackAtIndex( idx)) != nullptr; ++idx) { - std::unique_ptr<ObjectContainer> object_container_ap( + std::unique_ptr<ObjectContainer> object_container_up( create_object_container_callback(module_sp, data_sp, data_offset, file, file_offset, file_size)); - if (object_container_ap.get()) - object_file_sp = object_container_ap->GetObjectFile(file); + if (object_container_up) + object_file_sp = object_container_up->GetObjectFile(file); if (object_file_sp.get()) return object_file_sp; @@ -148,12 +147,12 @@ PluginManager::GetObjectContainerCreateCallbackAtIndex( idx)) != nullptr; ++idx) { - std::unique_ptr<ObjectContainer> object_container_ap( + std::unique_ptr<ObjectContainer> object_container_up( create_object_container_callback(module_sp, data_sp, data_offset, file, file_offset, file_size)); - if (object_container_ap.get()) - object_file_sp = object_container_ap->GetObjectFile(file); + if (object_container_up) + object_file_sp = object_container_up->GetObjectFile(file); if (object_file_sp.get()) return object_file_sp; @@ -264,9 +263,8 @@ : ModuleChild(module_sp), m_file(), // This file could be different from the original module's file m_type(eTypeInvalid), m_strata(eStrataInvalid), - m_file_offset(file_offset), m_length(length), m_data(), - m_unwind_table(*this), m_process_wp(), - m_memory_addr(LLDB_INVALID_ADDRESS), m_sections_ap(), m_symtab_ap(), + m_file_offset(file_offset), m_length(length), m_data(), m_process_wp(), + m_memory_addr(LLDB_INVALID_ADDRESS), m_sections_up(), m_symtab_up(), m_synthetic_symbol_idx(0) { if (file_spec_ptr) m_file = *file_spec_ptr; @@ -287,9 +285,8 @@ DataBufferSP &header_data_sp) : ModuleChild(module_sp), m_file(), m_type(eTypeInvalid), m_strata(eStrataInvalid), m_file_offset(0), m_length(0), m_data(), - m_unwind_table(*this), m_process_wp(process_sp), - m_memory_addr(header_addr), m_sections_ap(), m_symtab_ap(), - m_synthetic_symbol_idx(0) { + m_process_wp(process_sp), m_memory_addr(header_addr), m_sections_up(), + m_symtab_up(), m_synthetic_symbol_idx(0) { if (header_data_sp) m_data.SetData(header_data_sp, 0, header_data_sp->GetByteSize()); Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); @@ -368,6 +365,7 @@ case eSectionTypeDWARFDebugStrOffsets: case eSectionTypeDWARFDebugStrOffsetsDwo: case eSectionTypeDWARFDebugTypes: + case eSectionTypeDWARFDebugTypesDwo: case eSectionTypeDWARFAppleNames: case eSectionTypeDWARFAppleTypes: case eSectionTypeDWARFAppleNamespaces: @@ -464,12 +462,12 @@ lldb::addr_t addr, size_t byte_size) { DataBufferSP data_sp; if (process_sp) { - std::unique_ptr<DataBufferHeap> data_ap(new DataBufferHeap(byte_size, 0)); + std::unique_ptr<DataBufferHeap> data_up(new DataBufferHeap(byte_size, 0)); Status error; const size_t bytes_read = process_sp->ReadMemory( - addr, data_ap->GetBytes(), data_ap->GetByteSize(), error); + addr, data_up->GetBytes(), data_up->GetByteSize(), error); if (bytes_read == byte_size) - data_sp.reset(data_ap.release()); + data_sp.reset(data_up.release()); } return data_sp; } @@ -536,9 +534,7 @@ return 0; } -//---------------------------------------------------------------------- // Get the section data the file on disk -//---------------------------------------------------------------------- size_t ObjectFile::ReadSectionData(Section *section, DataExtractor §ion_data) { // If some other objectfile owns this data, pass this to them. @@ -602,13 +598,13 @@ if (log) log->Printf("%p ObjectFile::ClearSymtab () symtab = %p", static_cast<void *>(this), - static_cast<void *>(m_symtab_ap.get())); - m_symtab_ap.reset(); + static_cast<void *>(m_symtab_up.get())); + m_symtab_up.reset(); } } SectionList *ObjectFile::GetSectionList(bool update_module_section_list) { - if (m_sections_ap.get() == nullptr) { + if (m_sections_up == nullptr) { if (update_module_section_list) { ModuleSP module_sp(GetModule()); if (module_sp) { @@ -620,7 +616,7 @@ CreateSections(unified_section_list); } } - return m_sections_ap.get(); + return m_sections_up.get(); } lldb::SymbolType
diff --git a/src/llvm-project/lldb/source/Symbol/PostfixExpression.cpp b/src/llvm-project/lldb/source/Symbol/PostfixExpression.cpp new file mode 100644 index 0000000..1486535 --- /dev/null +++ b/src/llvm-project/lldb/source/Symbol/PostfixExpression.cpp
@@ -0,0 +1,227 @@ +//===-- PostfixExpression.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 +// +//===----------------------------------------------------------------------===// +// +// This file implements support for postfix expressions found in several symbol +// file formats, and their conversion to DWARF. +// +//===----------------------------------------------------------------------===// + +#include "lldb/Symbol/PostfixExpression.h" +#include "lldb/Core/dwarf.h" +#include "lldb/Utility/Stream.h" +#include "llvm/ADT/StringExtras.h" + +using namespace lldb_private; +using namespace lldb_private::postfix; + +static llvm::Optional<BinaryOpNode::OpType> +GetBinaryOpType(llvm::StringRef token) { + if (token.size() != 1) + return llvm::None; + switch (token[0]) { + case '@': + return BinaryOpNode::Align; + case '-': + return BinaryOpNode::Minus; + case '+': + return BinaryOpNode::Plus; + } + return llvm::None; +} + +static llvm::Optional<UnaryOpNode::OpType> +GetUnaryOpType(llvm::StringRef token) { + if (token == "^") + return UnaryOpNode::Deref; + return llvm::None; +} + +Node *postfix::Parse(llvm::StringRef expr, llvm::BumpPtrAllocator &alloc) { + llvm::SmallVector<Node *, 4> stack; + + llvm::StringRef token; + while (std::tie(token, expr) = getToken(expr), !token.empty()) { + if (auto op_type = GetBinaryOpType(token)) { + // token is binary operator + if (stack.size() < 2) + return nullptr; + + Node *right = stack.pop_back_val(); + Node *left = stack.pop_back_val(); + stack.push_back(MakeNode<BinaryOpNode>(alloc, *op_type, *left, *right)); + continue; + } + + if (auto op_type = GetUnaryOpType(token)) { + // token is unary operator + if (stack.empty()) + return nullptr; + + Node *operand = stack.pop_back_val(); + stack.push_back(MakeNode<UnaryOpNode>(alloc, *op_type, *operand)); + continue; + } + + int64_t value; + if (to_integer(token, value, 10)) { + // token is integer literal + stack.push_back(MakeNode<IntegerNode>(alloc, value)); + continue; + } + + stack.push_back(MakeNode<SymbolNode>(alloc, token)); + } + + if (stack.size() != 1) + return nullptr; + + return stack.back(); +} + +namespace { +class SymbolResolver : public Visitor<bool> { +public: + SymbolResolver(llvm::function_ref<Node *(SymbolNode &symbol)> replacer) + : m_replacer(replacer) {} + + using Visitor<bool>::Dispatch; + +private: + bool Visit(BinaryOpNode &binary, Node *&) override { + return Dispatch(binary.Left()) && Dispatch(binary.Right()); + } + + bool Visit(InitialValueNode &, Node *&) override { return true; } + bool Visit(IntegerNode &, Node *&) override { return true; } + bool Visit(RegisterNode &, Node *&) override { return true; } + + bool Visit(SymbolNode &symbol, Node *&ref) override { + if (Node *replacement = m_replacer(symbol)) { + ref = replacement; + if (replacement != &symbol) + return Dispatch(ref); + return true; + } + return false; + } + + bool Visit(UnaryOpNode &unary, Node *&) override { + return Dispatch(unary.Operand()); + } + + llvm::function_ref<Node *(SymbolNode &symbol)> m_replacer; +}; + +class DWARFCodegen : public Visitor<> { +public: + DWARFCodegen(Stream &stream) : m_out_stream(stream) {} + + using Visitor<>::Dispatch; + +private: + void Visit(BinaryOpNode &binary, Node *&) override; + + void Visit(InitialValueNode &val, Node *&) override; + + void Visit(IntegerNode &integer, Node *&) override { + m_out_stream.PutHex8(DW_OP_consts); + m_out_stream.PutSLEB128(integer.GetValue()); + ++m_stack_depth; + } + + void Visit(RegisterNode ®, Node *&) override; + + void Visit(SymbolNode &symbol, Node *&) override { + llvm_unreachable("Symbols should have been resolved by now!"); + } + + void Visit(UnaryOpNode &unary, Node *&) override; + + Stream &m_out_stream; + + /// The number keeping track of the evaluation stack depth at any given + /// moment. Used for implementing InitialValueNodes. We start with + /// m_stack_depth = 1, assuming that the initial value is already on the + /// stack. This initial value will be the value of all InitialValueNodes. If + /// the expression does not contain InitialValueNodes, then m_stack_depth is + /// not used, and the generated expression will run correctly even without an + /// initial value. + size_t m_stack_depth = 1; +}; +} // namespace + +void DWARFCodegen::Visit(BinaryOpNode &binary, Node *&) { + Dispatch(binary.Left()); + Dispatch(binary.Right()); + + switch (binary.GetOpType()) { + case BinaryOpNode::Plus: + m_out_stream.PutHex8(DW_OP_plus); + // NOTE: can be optimized by using DW_OP_plus_uconst opcpode + // if right child node is constant value + break; + case BinaryOpNode::Minus: + m_out_stream.PutHex8(DW_OP_minus); + break; + case BinaryOpNode::Align: + // emit align operator a @ b as + // a & ~(b - 1) + // NOTE: implicitly assuming that b is power of 2 + m_out_stream.PutHex8(DW_OP_lit1); + m_out_stream.PutHex8(DW_OP_minus); + m_out_stream.PutHex8(DW_OP_not); + + m_out_stream.PutHex8(DW_OP_and); + break; + } + --m_stack_depth; // Two pops, one push. +} + +void DWARFCodegen::Visit(InitialValueNode &, Node *&) { + // We never go below the initial stack, so we can pick the initial value from + // the bottom of the stack at any moment. + assert(m_stack_depth >= 1); + m_out_stream.PutHex8(DW_OP_pick); + m_out_stream.PutHex8(m_stack_depth - 1); + ++m_stack_depth; +} + +void DWARFCodegen::Visit(RegisterNode ®, Node *&) { + uint32_t reg_num = reg.GetRegNum(); + assert(reg_num != LLDB_INVALID_REGNUM); + + if (reg_num > 31) { + m_out_stream.PutHex8(DW_OP_bregx); + m_out_stream.PutULEB128(reg_num); + } else + m_out_stream.PutHex8(DW_OP_breg0 + reg_num); + + m_out_stream.PutSLEB128(0); + ++m_stack_depth; +} + +void DWARFCodegen::Visit(UnaryOpNode &unary, Node *&) { + Dispatch(unary.Operand()); + + switch (unary.GetOpType()) { + case UnaryOpNode::Deref: + m_out_stream.PutHex8(DW_OP_deref); + break; + } + // Stack depth unchanged. +} + +bool postfix::ResolveSymbols( + Node *&node, llvm::function_ref<Node *(SymbolNode &)> replacer) { + return SymbolResolver(replacer).Dispatch(node); +} + +void postfix::ToDWARF(Node &node, Stream &stream) { + Node *ptr = &node; + DWARFCodegen(stream).Dispatch(ptr); +}
diff --git a/src/llvm-project/lldb/source/Symbol/RustASTContext.cpp b/src/llvm-project/lldb/source/Symbol/RustASTContext.cpp deleted file mode 100644 index 6adf144d..0000000 --- a/src/llvm-project/lldb/source/Symbol/RustASTContext.cpp +++ /dev/null
@@ -1,2226 +0,0 @@ -//===-- RustASTContext.cpp ----------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include <mutex> -#include <utility> -#include <vector> - -#include "lldb/Core/Module.h" -#include "lldb/Core/PluginManager.h" -#include "lldb/Core/StreamFile.h" -#include "lldb/Core/UniqueCStringMap.h" -#include "lldb/Core/ValueObject.h" -#include "lldb/DataFormatters/StringPrinter.h" -#include "lldb/Symbol/CompilerType.h" -#include "lldb/Symbol/RustASTContext.h" -#include "lldb/Symbol/ObjectFile.h" -#include "lldb/Symbol/SymbolFile.h" -#include "lldb/Symbol/Type.h" -#include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/Target.h" -#include "lldb/Core/DumpDataExtractor.h" - -#include "llvm/Support/Threading.h" - -#include "Plugins/ExpressionParser/Rust/RustUserExpression.h" -#include "Plugins/SymbolFile/DWARF/DWARFASTParserRust.h" - -#include <unordered_map> - -using namespace lldb; - -namespace lldb_private { - -class RustAggregateBase; -class RustArray; -class RustBool; -class RustCLikeEnum; -class RustEnum; -class RustFunction; -class RustIntegral; -class RustPointer; -class RustStruct; -class RustTuple; -class RustTypedef; - -class RustType { -protected: - - RustType(const ConstString &name) : m_name(name) {} - DISALLOW_COPY_AND_ASSIGN (RustType); - -public: - - virtual ~RustType() {} - - ConstString Name() const { return m_name; } - - virtual lldb::Format Format() const { - return eFormatBytes; - } - - virtual std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) = 0; - - virtual uint32_t TypeInfo(CompilerType *element_type) const = 0; - virtual lldb::TypeClass TypeClass() const = 0; - virtual uint64_t ByteSize() const = 0; - - virtual RustAggregateBase *AsAggregate() { return nullptr; } - virtual RustArray *AsArray() { return nullptr; } - virtual RustBool *AsBool() { return nullptr; } - virtual RustCLikeEnum *AsCLikeEnum() { return nullptr; } - virtual RustEnum *AsEnum() { return nullptr; } - virtual RustFunction *AsFunction() { return nullptr; } - virtual RustIntegral *AsInteger () { return nullptr; } - virtual RustPointer *AsPointer () { return nullptr; } - virtual RustTuple *AsTuple() { return nullptr; } - virtual RustTypedef *AsTypedef() { return nullptr; } - - virtual bool IsAggregateType() const { return false; } - virtual bool IsCharType() const { return false; } - virtual bool IsFloatType() const { return false; } - -private: - ConstString m_name; -}; - -class RustBool : public RustType { -public: - RustBool(const ConstString &name) : RustType(name) {} - DISALLOW_COPY_AND_ASSIGN(RustBool); - - RustBool *AsBool() override { - return this; - } - - lldb::Format Format() const override { - return eFormatBoolean; - } - - uint32_t TypeInfo(CompilerType *) const override { - return eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassBuiltin; - } - - uint64_t ByteSize() const override { - return 1; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - return "bool " + varname; - } -}; - -class RustIntegral : public RustType { -public: - RustIntegral(const ConstString &name, bool is_signed, uint64_t byte_size, - bool is_char = false) - : RustType(name), - m_is_signed(is_signed), - m_byte_size(byte_size), - m_is_char(is_char) - {} - DISALLOW_COPY_AND_ASSIGN(RustIntegral); - - lldb::Format Format() const override { - if (m_is_char) - return eFormatUnicode32; - return m_is_signed ? eFormatDecimal : eFormatUnsigned; - } - - bool IsSigned() const { return m_is_signed; } - uint64_t ByteSize() const override { return m_byte_size; } - - RustIntegral *AsInteger () override { return this; } - - bool IsCharType() const override { return m_is_char; } - - uint32_t TypeInfo(CompilerType *) const override { - uint32_t result = eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar | eTypeIsInteger; - if (m_is_signed) - result |= eTypeIsSigned; - return result; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassBuiltin; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - // These names are predefined by clang. - std::string result = "__"; - if (!m_is_signed) { - result += "U"; - } - result += "INT" + std::to_string(8 * m_byte_size) + "_TYPE__ " + varname; - return result; - } - -private: - - bool m_is_signed; - uint64_t m_byte_size; - bool m_is_char; -}; - -class RustCLikeEnum : public RustType { -public: - RustCLikeEnum(const ConstString &name, const CompilerType &underlying_type, - std::map<uint64_t, std::string> &&values) - : RustType(name), - m_underlying_type(underlying_type), - m_values(std::move(values)) - { - } - DISALLOW_COPY_AND_ASSIGN(RustCLikeEnum); - - RustCLikeEnum *AsCLikeEnum() override { return this; } - - lldb::Format Format() const override { - return eFormatEnum; - } - - uint32_t TypeInfo(CompilerType *) const override { - return eTypeHasValue | eTypeIsEnumeration | eTypeIsScalar; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassEnumeration; - } - - uint64_t ByteSize() const override { - return m_underlying_type.GetByteSize(nullptr).getValueOr(0); - } - - bool IsSigned() const { - bool is_signed; - return m_underlying_type.IsIntegerType(is_signed) && is_signed; - } - - bool FindName(uint64_t val, std::string &name) { - auto iter = m_values.find(val); - if (iter == m_values.end()) { - return false; - } - name = iter->second; - return true; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - RustType *type = (RustType *) m_underlying_type.GetOpaqueQualType(); - return type->GetCABITypeDeclaration(name_map, varname); - } - -private: - - CompilerType m_underlying_type; - std::map<uint64_t, std::string> m_values; -}; - -class RustFloat : public RustType { -public: - RustFloat(const ConstString &name, uint64_t byte_size) - : RustType(name), - m_byte_size(byte_size) - {} - DISALLOW_COPY_AND_ASSIGN(RustFloat); - - lldb::Format Format() const override { - return eFormatFloat; - } - - bool IsFloatType() const override { return true; } - - uint32_t TypeInfo(CompilerType *) const override { - return eTypeIsBuiltIn | eTypeHasValue | eTypeIsFloat; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassBuiltin; - } - - uint64_t ByteSize() const override { return m_byte_size; } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - return (m_byte_size == 4 ? "float " : "double ") + varname; - } - -private: - - uint64_t m_byte_size; -}; - -class RustPointer : public RustType { -public: - // Pointers and references are handled similarly. - RustPointer(const ConstString &name, const CompilerType &pointee, uint64_t byte_size) - : RustType(name), - m_pointee(pointee), - m_byte_size(byte_size) - {} - DISALLOW_COPY_AND_ASSIGN(RustPointer); - - lldb::Format Format() const override { - return eFormatPointer; - } - - CompilerType PointeeType() const { return m_pointee; } - - RustPointer *AsPointer() override { return this; } - - uint32_t TypeInfo(CompilerType *elem) const override { - if (elem) - *elem = m_pointee; - return eTypeIsBuiltIn | eTypeHasValue | eTypeIsPointer; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassPointer; - } - - uint64_t ByteSize() const override { - return m_byte_size; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - RustType *p_type = (RustType *) m_pointee.GetOpaqueQualType(); - if (p_type->AsFunction()) { - // This does the right thing, see the implementation. - return p_type->GetCABITypeDeclaration(name_map, varname); - } - return p_type->GetCABITypeDeclaration(name_map, "") + "* " + varname; - } - -private: - - CompilerType m_pointee; - uint64_t m_byte_size; -}; - -class RustArray : public RustType { -public: - RustArray(const ConstString &name, uint64_t length, const CompilerType &elem) - : RustType(name), - m_length(length), - m_elem(elem) - {} - DISALLOW_COPY_AND_ASSIGN(RustArray); - - uint64_t Length() const { return m_length; } - RustArray *AsArray() override { return this; } - CompilerType ElementType() const { return m_elem; } - bool IsAggregateType() const override { return true; } - - uint32_t TypeInfo(CompilerType *elem) const override { - if (elem) - *elem = m_elem; - return eTypeHasChildren | eTypeIsArray; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassArray; - } - - uint64_t ByteSize() const override { - return m_elem.GetByteSize(nullptr).getValueOr(0) * m_length; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - RustType *type = (RustType *) m_elem.GetOpaqueQualType(); - return type->GetCABITypeDeclaration(name_map, varname) - + "[" + std::to_string(m_length) + "]"; - } - -private: - uint64_t m_length; - CompilerType m_elem; -}; - -// Base type for struct, tuple, and tuple struct. -class RustAggregateBase : public RustType { -protected: - RustAggregateBase(const ConstString &name, uint64_t byte_size, bool has_discriminant = false) - : RustType(name), - m_byte_size(byte_size), - m_has_discriminant(has_discriminant) - {} - - DISALLOW_COPY_AND_ASSIGN(RustAggregateBase); - -public: - - RustAggregateBase *AsAggregate() override { return this; } - - bool IsAggregateType() const override { return true; } - - size_t FieldCount() const { return m_fields.size(); } - - uint32_t TypeInfo(CompilerType *) const override { - return eTypeHasChildren | eTypeIsStructUnion; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassStruct; - } - - uint64_t ByteSize() const override { - return m_byte_size; - } - - struct Field { - Field(const ConstString &name, const CompilerType &type, uint64_t offset) - : m_name(name), - m_type(type), - m_offset(offset) - { - } - - ConstString m_name; - CompilerType m_type; - uint64_t m_offset; - }; - - void AddField(const ConstString &name, const CompilerType &type, uint64_t offset) { - m_fields.emplace_back(name, type, offset); - } - - void AddTemplateParameter(const CompilerType &ctype) { - m_template_args.push_back(ctype); - } - - virtual void FinishInitialization() { - } - - bool HasDiscriminant() const { - return m_has_discriminant; - } - - // With the old-style enum encoding, after the discriminant's - // location is computed the member types no longer need to have - // theirs, so they are dropped. - virtual void DropDiscriminant() { - if (m_has_discriminant) { - m_has_discriminant = false; - m_fields.erase(m_fields.begin()); - } - } - - const Field *FieldAt(size_t idx) { - if (idx >= m_fields.size()) - return nullptr; - return &m_fields[idx]; - } - - size_t GetNumTemplateArguments() const { - return m_template_args.size(); - } - - CompilerType GetTypeTemplateArgument(size_t idx) const { - return m_template_args[idx]; - } - - typedef std::vector<Field>::const_iterator const_iterator; - - const_iterator begin() const { - return m_fields.begin(); - } - - const_iterator end() const { - return m_fields.end(); - } - - // Type-printing support. - virtual const char *Tag() const = 0; - - virtual const char *TagName() const { - return Name().AsCString(); - } - - virtual const char *Opener() const = 0; - virtual const char *Closer() const = 0; - -protected: - - std::string GetFieldsCABITypeDeclaration(RustASTContext::TypeNameMap *name_map) { - int argno = 0; - std::string result; - for (const Field &f : m_fields) { - RustType *rtype = static_cast<RustType *>(f.m_type.GetOpaqueQualType()); - std::string name; - if (f.m_name.IsEmpty()) { - name = "__" + std::to_string(argno++); - } else { - name = std::string("_") + f.m_name.AsCString(); - } - result += rtype->GetCABITypeDeclaration(name_map, name) + "; "; - } - return result; - } - - Field *MutableFieldAt(size_t idx) { - if (idx >= m_fields.size()) - return nullptr; - return &m_fields[idx]; - } - -private: - - uint64_t m_byte_size; - std::vector<Field> m_fields; - bool m_has_discriminant; - std::vector<CompilerType> m_template_args; -}; - -class RustTuple : public RustAggregateBase { -public: - RustTuple(const ConstString &name, uint64_t byte_size, bool has_discriminant) - : RustAggregateBase(name, byte_size, has_discriminant) - {} - - DISALLOW_COPY_AND_ASSIGN(RustTuple); - - RustTuple *AsTuple() override { return this; } - - void AddField(const CompilerType &type, uint64_t offset) { - RustAggregateBase::AddField(ConstString(), type, offset); - } - - const char *Tag() const override { - return IsTuple() ? "" : "struct "; - } - const char *TagName() const override { - if (IsTuple()) { - return ""; - } - return Name().AsCString(); - } - const char *Opener() const override { - return "("; - } - const char *Closer() const override { - return ")"; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - std::string tagname; - if (name_map->Tag(this, &tagname)) { - std::string def = " struct " + tagname + "{" - + GetFieldsCABITypeDeclaration(name_map) + " };\n"; - name_map->typedefs.append(def); - } - return tagname + " " + varname; - } - - void DropDiscriminant() override { - RustAggregateBase::DropDiscriminant(); - // Rename the fields, because we dropped the first one. - for (size_t i = 0; i < FieldCount(); ++i) { - Field *f = MutableFieldAt(i); - char buf[32]; - snprintf (buf, sizeof (buf), "%u", unsigned(i)); - f->m_name = ConstString(buf); - } - } - -private: - - // As opposed to a tuple struct. - bool IsTuple() const { - ConstString name = Name(); - // For the time being we must examine the name, because the DWARF - // doesn't provide anything else. - return name.IsEmpty() || name.AsCString()[0] == '('; - } -}; - -class RustStruct : public RustAggregateBase { -public: - RustStruct(const ConstString &name, uint64_t byte_size, bool has_discriminant) - : RustAggregateBase(name, byte_size, has_discriminant) - {} - - DISALLOW_COPY_AND_ASSIGN(RustStruct); - - const char *Tag() const override { - return "struct "; - } - const char *Opener() const override { - return "{"; - } - const char *Closer() const override { - return "}"; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - std::string tagname; - if (name_map->Tag(this, &tagname)) { - std::string def = " struct " + tagname + "{" - + GetFieldsCABITypeDeclaration(name_map) + " };\n"; - name_map->typedefs.append(def); - } - return tagname + " " + varname; - } -}; - -class RustUnion : public RustAggregateBase { -public: - RustUnion(const ConstString &name, uint64_t byte_size) - : RustAggregateBase(name, byte_size) - {} - - DISALLOW_COPY_AND_ASSIGN(RustUnion); - - const char *Tag() const override { - return "union "; - } - const char *Opener() const override { - return "{"; - } - const char *Closer() const override { - return "}"; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - std::string tagname; - if (name_map->Tag(this, &tagname)) { - std::string def = " union " + tagname + "{" - + GetFieldsCABITypeDeclaration(name_map) + " };\n"; - name_map->typedefs.append(def); - } - return tagname + " " + varname; - } -}; - -// A Rust enum, not a C-like enum. -class RustEnum : public RustAggregateBase { -public: - RustEnum(const ConstString &name, uint64_t byte_size, - uint32_t discr_offset, uint32_t discr_byte_size) - : RustAggregateBase(name, byte_size), - m_discr_offset(discr_offset), - m_discr_byte_size(discr_byte_size), - m_default(-1) - {} - - DISALLOW_COPY_AND_ASSIGN(RustEnum); - - RustEnum *AsEnum() override { return this; } - - const char *Tag() const override { - return "enum "; - } - const char *Opener() const override { - return "{"; - } - const char *Closer() const override { - return "}"; - } - - // Record the discriminant for the most recently added field. - void RecordDiscriminant(bool is_default, uint64_t discriminant) { - int value = int(FieldCount() - 1); - if (is_default) { - m_default = value; - } else { - m_discriminants[discriminant] = value; - } - } - - void GetDiscriminantLocation(uint64_t &discr_offset, uint64_t &discr_byte_size) { - discr_offset = m_discr_offset; - discr_byte_size = m_discr_byte_size; - } - - CompilerType FindEnumVariant(uint64_t discriminant) { - auto iter = m_discriminants.find(discriminant); - int idx = m_default; - if (iter != m_discriminants.end()) { - idx = iter->second; - } else if (idx == -1) { - // If the DWARF was bad somehow, we could end up not finding the - // discriminant and not having a default. - return CompilerType(); - } - return FieldAt(idx)->m_type; - } - - void FinishInitialization() override { - for (auto&& iter : *this) { - RustType *rtype = static_cast<RustType *>(iter.m_type.GetOpaqueQualType()); - if (RustAggregateBase* agg = rtype->AsAggregate()) { - agg->DropDiscriminant(); - } - } - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - std::string tagname; - if (name_map->Tag(this, &tagname)) { - std::string def = "struct " + tagname + "{ "; - // If the discriminant comes first, then it is a hidden field, - // which we'll emit. Otherwise, it is in a hole somewhere, or - // perhaps overlaid with some other field, so we don't bother. - // (This is unwarranted compiler knowledge - FIXME.) If there are - // zero or one fields then there is no discriminant. - if (FieldCount() > 1 && m_discr_offset == 0) { - def += "int" + std::to_string(8 * m_discr_byte_size) + "_t __discr; "; - } - def += GetFieldsCABITypeDeclaration(name_map) + " };\n"; - name_map->typedefs.append(def); - } - return tagname + " " + varname; - } - -private: - - // The offset and byte size of the discriminant. Note that, as a - // special case, if there is only a single field then the - // discriminant will be assumed not to exist. - uint32_t m_discr_offset; - uint32_t m_discr_byte_size; - - // The index in m_fields of the default variant. -1 if there is no - // default variant. - int m_default; - - // This maps from discriminant values to indices in m_fields. This - // is used to find the correct variant given a discriminant value. - std::unordered_map<uint64_t, int> m_discriminants; -}; - -class RustFunction : public RustType { -public: - RustFunction (const ConstString &name, uint64_t byte_size, - const CompilerType &return_type, - const std::vector<CompilerType> &&arguments, - const std::vector<CompilerType> &&template_arguments) - : RustType(name), - m_byte_size(byte_size), - m_return_type(return_type), - m_arguments(std::move(arguments)), - m_template_args(std::move(template_arguments)) - { - } - DISALLOW_COPY_AND_ASSIGN(RustFunction); - - // do we care about the names? - void AddArgument(const CompilerType &type) { - m_arguments.push_back(type); - } - - RustFunction *AsFunction() override { return this; } - - CompilerType ReturnType() const { return m_return_type; } - size_t ArgumentCount() { return m_arguments.size(); } - CompilerType Argument(size_t i) { return m_arguments[i]; } - - uint32_t TypeInfo(CompilerType *) const override { - return eTypeIsFuncPrototype | eTypeHasValue; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassFunction; - } - - uint64_t ByteSize() const override { - return m_byte_size; - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - RustType *type = (RustType *) m_return_type.GetOpaqueQualType(); - - std::string result = type->GetCABITypeDeclaration(name_map, "") + " (*" + - varname + ")("; - bool first = true; - for (CompilerType &iter : m_arguments) { - RustType *type = (RustType *) iter.GetOpaqueQualType(); - if (!first) { - result += ", "; - } - first = false; - result += type->GetCABITypeDeclaration(name_map, ""); - } - - return result + ")"; - } - - size_t GetNumTemplateArguments() const { - return m_template_args.size(); - } - - CompilerType GetTypeTemplateArgument(size_t idx) const { - return m_template_args[idx]; - } - -private: - - uint64_t m_byte_size; - CompilerType m_return_type; - std::vector<CompilerType> m_arguments; - std::vector<CompilerType> m_template_args; -}; - -class RustTypedef : public RustType { -public: - - RustTypedef(const ConstString &name, const CompilerType &type) - : RustType(name), - m_type(type) - { - } - - DISALLOW_COPY_AND_ASSIGN(RustTypedef); - - RustTypedef *AsTypedef() override { return this; } - CompilerType UnderlyingType() const { return m_type; } - - uint32_t TypeInfo(CompilerType *) const override { - return eTypeIsTypedef; - } - - lldb::TypeClass TypeClass() const override { - return eTypeClassTypedef; - } - - uint64_t ByteSize() const override { - return m_type.GetByteSize(nullptr).getValueOr(0); - } - - std::string GetCABITypeDeclaration(RustASTContext::TypeNameMap *name_map, - const std::string &varname) override { - RustType *type = (RustType *) m_type.GetOpaqueQualType(); - return type->GetCABITypeDeclaration(name_map, varname); - } - -private: - CompilerType m_type; -}; - -class RustDecl; -class RustDeclContext; - -class RustDeclBase { -public: - - ConstString Name() const { - return m_name; - } - - ConstString QualifiedName() { - if (!m_parent) { - return m_name; - } - if (!m_full_name) { - ConstString basename = m_parent->QualifiedName(); - if (basename) { - std::string qual = std::string(basename.AsCString()) + "::" + m_name.AsCString(); - m_full_name = ConstString(qual.c_str()); - } else { - m_full_name = m_name; - } - } - return m_full_name; - } - - RustDeclContext *Context() const { - // Always succeeds. - return m_parent->AsDeclContext(); - } - - virtual RustDecl *AsDecl() { return nullptr; } - virtual RustDeclContext *AsDeclContext() { return nullptr; } - - virtual ~RustDeclBase() { } - -protected: - - RustDeclBase(const ConstString &name, RustDeclBase *parent) - : m_name(name), - m_parent(parent) - { - } - -private: - - ConstString m_name; - // This is really a RustDeclContext. - RustDeclBase *m_parent; - ConstString m_full_name; -}; - -class RustDeclContext : public RustDeclBase { -public: - RustDeclContext(const ConstString &name, RustDeclContext *parent) - : RustDeclBase(name, parent) - { - } - - RustDeclContext *AsDeclContext() override { return this; } - - RustDeclBase *FindByName(const ConstString &name) { - auto iter = m_decls.find(name); - if (iter == m_decls.end()) { - return nullptr; - } - return iter->second.get(); - } - - void AddItem(std::unique_ptr<RustDeclBase> &&item) { - ConstString name = item->Name(); - m_decls[name] = std::move(item); - } - -private: - std::map<ConstString, std::unique_ptr<RustDeclBase>> m_decls; -}; - -class RustDecl : public RustDeclBase { -public: - RustDecl(const ConstString &name, const ConstString &mangled, RustDeclContext *parent) - : RustDeclBase(name, parent), - m_mangled(mangled) - { - assert(parent); - } - - RustDecl *AsDecl() override { return this; } - - ConstString MangledName() const { - return m_mangled; - } - -private: - - ConstString m_mangled; -}; - -} // namespace lldb_private -using namespace lldb_private; - -RustASTContext::RustASTContext() - : TypeSystem(eKindRust), - m_pointer_byte_size(0) -{ -} - -RustASTContext::~RustASTContext() {} - -//------------------------------------------------------------------ -// PluginInterface functions -//------------------------------------------------------------------ - -ConstString RustASTContext::GetPluginNameStatic() { - return ConstString("rust"); -} - -ConstString RustASTContext::GetPluginName() { - return RustASTContext::GetPluginNameStatic(); -} - -uint32_t RustASTContext::GetPluginVersion() { - return 1; -} - -lldb::TypeSystemSP RustASTContext::CreateInstance(lldb::LanguageType language, - Module *module, - Target *target) { - if (language == eLanguageTypeRust) { - ArchSpec arch; - std::shared_ptr<RustASTContext> astc; - if (module) { - arch = module->GetArchitecture(); - astc = std::shared_ptr<RustASTContext>(new RustASTContext); - } else if (target) { - arch = target->GetArchitecture(); - astc = std::shared_ptr<RustASTContextForExpr>( - new RustASTContextForExpr(target->shared_from_this())); - } - - if (arch.IsValid()) { - astc->SetAddressByteSize(arch.GetAddressByteSize()); - return astc; - } - } - return lldb::TypeSystemSP(); -} - -void RustASTContext::EnumerateSupportedLanguages( - std::set<lldb::LanguageType> &languages_for_types, - std::set<lldb::LanguageType> &languages_for_expressions) { - static std::vector<lldb::LanguageType> s_supported_languages_for_types( - {lldb::eLanguageTypeRust}); - - static std::vector<lldb::LanguageType> s_supported_languages_for_expressions( - {}); - - languages_for_types.insert(s_supported_languages_for_types.begin(), - s_supported_languages_for_types.end()); - languages_for_expressions.insert( - s_supported_languages_for_expressions.begin(), - s_supported_languages_for_expressions.end()); -} - -void RustASTContext::Initialize() { - PluginManager::RegisterPlugin(GetPluginNameStatic(), "Rust AST context plug-in", - CreateInstance, EnumerateSupportedLanguages); -} - -void RustASTContext::Terminate() { - PluginManager::UnregisterPlugin(CreateInstance); -} - -//---------------------------------------------------------------------- -// Tests -//---------------------------------------------------------------------- - -bool RustASTContext::IsArrayType(lldb::opaque_compiler_type_t type, - CompilerType *element_type, uint64_t *size, - bool *is_incomplete) { - if (element_type) - element_type->Clear(); - if (size) - *size = 0; - if (is_incomplete) - *is_incomplete = false; - RustArray *array = static_cast<RustType *>(type)->AsArray(); - if (array) { - if (size) - *size = array->Length(); - if (element_type) - *element_type = array->ElementType(); - return true; - } - return false; -} - -bool RustASTContext::IsVectorType(lldb::opaque_compiler_type_t type, - CompilerType *element_type, uint64_t *size) { - if (element_type) - element_type->Clear(); - if (size) - *size = 0; - return false; -} - -bool RustASTContext::IsAggregateType(lldb::opaque_compiler_type_t type) { - return static_cast<RustType *>(type)->IsAggregateType(); -} - -bool RustASTContext::IsBeingDefined(lldb::opaque_compiler_type_t type) { - return false; -} - -bool RustASTContext::IsCharType(lldb::opaque_compiler_type_t type) { - return static_cast<RustType *>(type)->IsCharType(); -} - -bool RustASTContext::IsCompleteType(lldb::opaque_compiler_type_t type) { - return bool(type); -} - -bool RustASTContext::IsConst(lldb::opaque_compiler_type_t type) { - return false; -} - -bool RustASTContext::IsCStringType(lldb::opaque_compiler_type_t type, - uint32_t &length) { - return false; -} - -bool RustASTContext::IsDefined(lldb::opaque_compiler_type_t type) { - return type != nullptr; -} - -bool RustASTContext::IsFloatingPointType(lldb::opaque_compiler_type_t type, - uint32_t &count, bool &is_complex) { - is_complex = false; - if (static_cast<RustType *>(type)->IsFloatType()) { - count = 1; - return true; - } - count = 0; - return false; -} - -bool RustASTContext::IsFunctionType(lldb::opaque_compiler_type_t type, - bool *is_variadic_ptr) { - if (is_variadic_ptr) - *is_variadic_ptr = false; - return static_cast<RustType *>(type)->AsFunction() != nullptr; -} - -uint32_t RustASTContext::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type, - CompilerType *base_type_ptr) { - // FIXME should detect "homogeneous floating-point aggregates". - return false; -} - -size_t -RustASTContext::GetNumberOfFunctionArguments(lldb::opaque_compiler_type_t type) { - RustFunction *func = static_cast<RustType *>(type)->AsFunction(); - if (func) { - return func->ArgumentCount(); - } - return -1; -} - -CompilerType -RustASTContext::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type, - const size_t index) { - RustFunction *func = static_cast<RustType *>(type)->AsFunction(); - if (func) { - return func->Argument(index); - } - return CompilerType(); -} - -bool RustASTContext::IsFunctionPointerType(lldb::opaque_compiler_type_t type) { - CompilerType pointee; - if (!IsPointerType(type, &pointee)) { - return false; - } - return pointee.IsFunctionType(); -} - -bool RustASTContext::IsBlockPointerType(lldb::opaque_compiler_type_t type, - CompilerType *function_pointer_type_ptr) { - return false; -} - -bool RustASTContext::IsIntegerType(lldb::opaque_compiler_type_t type, - bool &is_signed) { - if (!type) - return false; - - RustIntegral *inttype = static_cast<RustType *>(type)->AsInteger(); - if (inttype) { - is_signed = inttype->IsSigned(); - return true; - } - return false; -} - -bool RustASTContext::IsPolymorphicClass(lldb::opaque_compiler_type_t type) { - return false; -} - -bool RustASTContext::IsPossibleDynamicType(lldb::opaque_compiler_type_t type, - CompilerType *target_type, // Can pass NULL - bool check_cplusplus, bool check_objc) { - if (target_type) - target_type->Clear(); - // FIXME eventually we'll handle trait object pointers here - if (static_cast<RustType *>(type)->AsEnum()) { - return true; - } - return false; -} - -bool RustASTContext::IsRuntimeGeneratedType(lldb::opaque_compiler_type_t type) { - return false; -} - -bool RustASTContext::IsPointerType(lldb::opaque_compiler_type_t type, - CompilerType *pointee_type) { - if (!type) - return false; - if (RustPointer *ptr = static_cast<RustType *>(type)->AsPointer()) { - if (pointee_type) - *pointee_type = ptr->PointeeType(); - return true; - } - return false; -} - -bool RustASTContext::IsPointerOrReferenceType(lldb::opaque_compiler_type_t type, - CompilerType *pointee_type) { - return IsPointerType(type, pointee_type); -} - -bool RustASTContext::IsReferenceType(lldb::opaque_compiler_type_t type, - CompilerType *pointee_type, - bool *is_rvalue) { - return false; -} - -bool RustASTContext::IsScalarType(lldb::opaque_compiler_type_t type) { - return !IsAggregateType(type); -} - -bool RustASTContext::IsTypedefType(lldb::opaque_compiler_type_t type) { - if (type) - return static_cast<RustType *>(type)->AsTypedef() != nullptr; - return false; -} - -bool RustASTContext::IsBooleanType(lldb::opaque_compiler_type_t type) { - if (type) - return static_cast<RustType *>(type)->AsBool() != nullptr; - return false; -} - -bool RustASTContext::IsVoidType(lldb::opaque_compiler_type_t type) { - if (!type) - return false; - RustTuple *tuple = static_cast<RustType *>(type)->AsTuple(); - return tuple && !tuple->Name().IsEmpty() && - strcmp(tuple->Name().AsCString(), "()") == 0 && tuple->FieldCount() == 0; -} - -bool RustASTContext::SupportsLanguage(lldb::LanguageType language) { - return language == eLanguageTypeRust; -} - -//---------------------------------------------------------------------- -// Type Completion -//---------------------------------------------------------------------- - -bool RustASTContext::GetCompleteType(lldb::opaque_compiler_type_t type) { - return bool(type); -} - -//---------------------------------------------------------------------- -// AST related queries -//---------------------------------------------------------------------- - -uint32_t RustASTContext::GetPointerByteSize() { - return m_pointer_byte_size; -} - -//---------------------------------------------------------------------- -// Accessors -//---------------------------------------------------------------------- - -ConstString RustASTContext::GetTypeName(lldb::opaque_compiler_type_t type) { - if (type) - return static_cast<RustType *>(type)->Name(); - return ConstString(); -} - -uint32_t -RustASTContext::GetTypeInfo(lldb::opaque_compiler_type_t type, - CompilerType *pointee_or_element_compiler_type) { - if (pointee_or_element_compiler_type) - pointee_or_element_compiler_type->Clear(); - if (!type) - return 0; - return static_cast<RustType *>(type)->TypeInfo(pointee_or_element_compiler_type); -} - -lldb::TypeClass RustASTContext::GetTypeClass(lldb::opaque_compiler_type_t type) { - if (!type) - return eTypeClassInvalid; - return static_cast<RustType *>(type)->TypeClass(); -} - -lldb::BasicType -RustASTContext::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) { - ConstString name = GetTypeName(type); - if (name.IsEmpty()) { - // Nothing. - } else if (strcmp(name.AsCString(), "()") == 0) { - return eBasicTypeVoid; - } else if (strcmp(name.AsCString(), "bool") == 0) { - return eBasicTypeBool; - } - return eBasicTypeInvalid; -} - -lldb::LanguageType -RustASTContext::GetMinimumLanguage(lldb::opaque_compiler_type_t type) { - return lldb::eLanguageTypeRust; -} - -unsigned RustASTContext::GetTypeQualifiers(lldb::opaque_compiler_type_t type) { - return 0; -} - -//---------------------------------------------------------------------- -// Creating related types -//---------------------------------------------------------------------- - -CompilerType -RustASTContext::GetArrayElementType(lldb::opaque_compiler_type_t type, - uint64_t *stride) { - RustArray *array = static_cast<RustType *>(type)->AsArray(); - if (array) { - if (stride) { - *stride = array->ElementType().GetByteSize(nullptr).getValueOr(0); - } - return array->ElementType(); - } - return CompilerType(); -} - -CompilerType RustASTContext::GetCanonicalType(lldb::opaque_compiler_type_t type) { - RustTypedef *t = static_cast<RustType *>(type)->AsTypedef(); - if (t) - return t->UnderlyingType(); - return CompilerType(this, type); -} - -CompilerType -RustASTContext::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) { - return CompilerType(this, type); -} - -// Returns -1 if this isn't a function or if the function doesn't have a -// prototype. -// Returns a value >= 0 if there is a prototype. -int RustASTContext::GetFunctionArgumentCount(lldb::opaque_compiler_type_t type) { - return GetNumberOfFunctionArguments(type); -} - -CompilerType -RustASTContext::GetFunctionArgumentTypeAtIndex(lldb::opaque_compiler_type_t type, - size_t idx) { - return GetFunctionArgumentAtIndex(type, idx); -} - -CompilerType -RustASTContext::GetFunctionReturnType(lldb::opaque_compiler_type_t type) { - if (type) { - RustFunction *t = static_cast<RustType *>(type)->AsFunction(); - if (t) { - return t->ReturnType(); - } - } - return CompilerType(); -} - -size_t RustASTContext::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) { - return 0; -} - -TypeMemberFunctionImpl -RustASTContext::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type, - size_t idx) { - return TypeMemberFunctionImpl(); -} - -CompilerType -RustASTContext::GetNonReferenceType(lldb::opaque_compiler_type_t type) { - return CompilerType(this, type); -} - -CompilerType RustASTContext::GetPointeeType(lldb::opaque_compiler_type_t type) { - if (!type) - return CompilerType(); - RustPointer *p = static_cast<RustType *>(type)->AsPointer(); - if (p) - return p->PointeeType(); - return CompilerType(); -} - -CompilerType RustASTContext::GetPointerType(lldb::opaque_compiler_type_t type) { - ConstString type_name = GetTypeName(type); - // Arbitrarily look for a raw pointer here. - ConstString pointer_name(std::string("*mut ") + type_name.GetCString()); - return CreatePointerType(pointer_name, CompilerType(this, type), m_pointer_byte_size); -} - -// If the current object represents a typedef type, get the underlying type -CompilerType RustASTContext::GetTypedefedType(lldb::opaque_compiler_type_t type) { - if (type) { - RustTypedef *t = static_cast<RustType *>(type)->AsTypedef(); - if (t) - return t->UnderlyingType(); - } - return CompilerType(); -} - -//---------------------------------------------------------------------- -// Create related types using the current type's AST -//---------------------------------------------------------------------- -CompilerType RustASTContext::GetBasicTypeFromAST(lldb::BasicType basic_type) { - return CompilerType(); -} - -CompilerType -RustASTContext::GetBuiltinTypeForEncodingAndBitSize(lldb::Encoding encoding, - size_t bit_size) { - return CompilerType(); -} - -//---------------------------------------------------------------------- -// Exploring the type -//---------------------------------------------------------------------- - -uint64_t RustASTContext::GetBitSize(lldb::opaque_compiler_type_t type, - ExecutionContextScope *exe_scope) { - if (!type) - return 0; - RustType *t = static_cast<RustType *>(type); - return t->ByteSize() * 8; -} - -lldb::Encoding RustASTContext::GetEncoding(lldb::opaque_compiler_type_t type, - uint64_t &count) { - count = 1; - bool is_signed; - if (IsIntegerType(type, is_signed)) { - return is_signed ? eEncodingSint : eEncodingUint; - } - if (IsBooleanType(type)) { - return eEncodingUint; - } - bool is_complex; - uint32_t complex_count; - if (IsFloatingPointType(type, complex_count, is_complex)) { - count = complex_count; - return eEncodingIEEE754; - } - if (IsPointerType(type)) - return eEncodingUint; - return eEncodingInvalid; -} - -lldb::Format RustASTContext::GetFormat(lldb::opaque_compiler_type_t type) { - if (!type) - return eFormatDefault; - return static_cast<RustType *>(type)->Format(); -} - -size_t RustASTContext::GetTypeBitAlign(lldb::opaque_compiler_type_t type) { - return 0; -} - -uint32_t RustASTContext::GetNumChildren(lldb::opaque_compiler_type_t type, - bool omit_empty_base_classes, - const ExecutionContext *exe_ctx) { - if (!type) - return 0; - - RustType *t = static_cast<RustType *>(type); - uint32_t result = 0; - if (RustPointer *ptr = t->AsPointer()) { - result = ptr->PointeeType().GetNumChildren(omit_empty_base_classes, exe_ctx); - // If the pointee is not an aggregate, return 1 because the - // pointer has a child. Not totally sure this makes sense. - if (result == 0) - result = 1; - } else if (RustArray *array = t->AsArray()) { - result = array->Length(); - } else if (RustTypedef *typ = t->AsTypedef()) { - result = typ->UnderlyingType().GetNumChildren(omit_empty_base_classes, exe_ctx); - } else if (RustAggregateBase *agg = t->AsAggregate()) { - result = agg->FieldCount(); - } - - return result; -} - -uint32_t RustASTContext::GetNumFields(lldb::opaque_compiler_type_t type) { - if (!type) - return 0; - RustType *t = static_cast<RustType *>(type); - if (RustTypedef *tdef = t->AsTypedef()) - return tdef->UnderlyingType().GetNumFields(); - if (RustAggregateBase *a = t->AsAggregate()) - return a->FieldCount(); - return 0; -} - -CompilerType RustASTContext::GetFieldAtIndex(lldb::opaque_compiler_type_t type, - size_t idx, std::string &name, - uint64_t *bit_offset_ptr, - uint32_t *bitfield_bit_size_ptr, - bool *is_bitfield_ptr) { - if (bit_offset_ptr) - *bit_offset_ptr = 0; - if (bitfield_bit_size_ptr) - *bitfield_bit_size_ptr = 0; - if (is_bitfield_ptr) - *is_bitfield_ptr = false; - - if (!type || !GetCompleteType(type)) - return CompilerType(); - - RustType *t = static_cast<RustType *>(type); - if (RustTypedef *typ = t->AsTypedef()) - return typ->UnderlyingType().GetFieldAtIndex( - idx, name, bit_offset_ptr, bitfield_bit_size_ptr, is_bitfield_ptr); - - if (RustAggregateBase *s = t->AsAggregate()) { - const auto *field = s->FieldAt(idx); - if (field) { - name = field->m_name.GetStringRef(); - if (bit_offset_ptr) - *bit_offset_ptr = field->m_offset * 8; - return field->m_type; - } - } - return CompilerType(); -} - -CompilerType RustASTContext::GetChildCompilerTypeAtIndex( - lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx, - bool transparent_pointers, bool omit_empty_base_classes, - bool ignore_array_bounds, std::string &child_name, - uint32_t &child_byte_size, int32_t &child_byte_offset, - uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset, - bool &child_is_base_class, bool &child_is_deref_of_parent, - ValueObject *valobj, uint64_t &language_flags) { - child_name.clear(); - child_byte_size = 0; - child_byte_offset = 0; - child_bitfield_bit_size = 0; - child_bitfield_bit_offset = 0; - child_is_base_class = false; - child_is_deref_of_parent = false; - language_flags = 0; - - if (!type || !GetCompleteType(type)) - return CompilerType(); - - RustType *t = static_cast<RustType *>(type); - if (t->AsAggregate()) { - uint64_t bit_offset; - CompilerType ret = - GetFieldAtIndex(type, idx, child_name, &bit_offset, nullptr, nullptr); - llvm::Optional<uint64_t> size = ret.GetByteSize( - exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr); - if (!size) - return {}; - child_byte_size = *size; - child_byte_offset = bit_offset / 8; - return ret; - } else if (RustPointer *ptr = t->AsPointer()) { - CompilerType pointee = ptr->PointeeType(); - if (!pointee.IsValid() || pointee.IsVoidType()) - return CompilerType(); - if (transparent_pointers && pointee.IsAggregateType()) { - bool tmp_child_is_deref_of_parent = false; - return pointee.GetChildCompilerTypeAtIndex( - exe_ctx, idx, transparent_pointers, omit_empty_base_classes, - ignore_array_bounds, child_name, child_byte_size, child_byte_offset, - child_bitfield_bit_size, child_bitfield_bit_offset, - child_is_base_class, tmp_child_is_deref_of_parent, valobj, - language_flags); - } else { - child_is_deref_of_parent = true; - const char *parent_name = valobj ? valobj->GetName().GetCString() : NULL; - if (parent_name) { - child_name.assign(1, '*'); - child_name += parent_name; - } - - // We have a pointer to an simple type - if (idx == 0 && pointee.GetCompleteType()) { - llvm::Optional<uint64_t> size = pointee.GetByteSize( - exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL); - if (!size) - return {}; - child_byte_size = *size; - child_byte_offset = 0; - return pointee; - } - } - } else if (RustArray *a = t->AsArray()) { - if (ignore_array_bounds || idx < a->Length()) { - CompilerType element_type = a->ElementType(); - if (element_type.GetCompleteType()) { - char element_name[64]; - ::snprintf(element_name, sizeof(element_name), "[%zu]", idx); - child_name.assign(element_name); - llvm::Optional<uint64_t> size = element_type.GetByteSize( - exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL); - if (!size) - return {}; - child_byte_size = *size; - child_byte_offset = (int32_t)idx * (int32_t)child_byte_size; - return element_type; - } - } - } else if (RustTypedef *typ = t->AsTypedef()) { - return typ->UnderlyingType().GetChildCompilerTypeAtIndex( - exe_ctx, idx, transparent_pointers, omit_empty_base_classes, - ignore_array_bounds, child_name, child_byte_size, child_byte_offset, - child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class, - child_is_deref_of_parent, valobj, language_flags); - } - return CompilerType(); -} - -// Lookup a child given a name. This function will match base class names -// and member member names in "clang_type" only, not descendants. -uint32_t -RustASTContext::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type, - const char *name, - bool omit_empty_base_classes) { - if (!type || !GetCompleteType(type)) - return UINT_MAX; - - RustType *t = static_cast<RustType *>(type); - if (RustAggregateBase *agg = t->AsAggregate()) { - for (uint32_t i = 0; i < agg->FieldCount(); ++i) { - const RustAggregateBase::Field *f = agg->FieldAt(i); - if (f->m_name.GetStringRef() == name) - return i; - } - } else if (RustPointer *typ = t->AsPointer()) { - return typ->PointeeType().GetIndexOfChildWithName(name, omit_empty_base_classes); - } - return UINT_MAX; -} - -// Lookup a child member given a name. This function will match member names -// only and will descend into "clang_type" children in search for the first -// member in this class, or any base class that matches "name". -// TODO: Return all matches for a given name by returning a -// vector<vector<uint32_t>> -// so we catch all names that match a given child name, not just the first. -size_t RustASTContext::GetIndexOfChildMemberWithName( - lldb::opaque_compiler_type_t type, const char *name, - bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) { - uint32_t index = GetIndexOfChildWithName(type, name, omit_empty_base_classes); - if (index == UINT_MAX) - return 0; - child_indexes.push_back(index); - return 1; -} - -// Converts "s" to a floating point value and place resulting floating -// point bytes in the "dst" buffer. -size_t -RustASTContext::ConvertStringToFloatValue(lldb::opaque_compiler_type_t type, - const char *s, uint8_t *dst, - size_t dst_size) { - assert(false); - return 0; -} - -//---------------------------------------------------------------------- -// Dumping types -//---------------------------------------------------------------------- -#define DEPTH_INCREMENT 2 - -void RustASTContext::DumpValue(lldb::opaque_compiler_type_t type, - ExecutionContext *exe_ctx, Stream *s, - lldb::Format format, const DataExtractor &data, - lldb::offset_t data_byte_offset, - size_t data_byte_size, uint32_t bitfield_bit_size, - uint32_t bitfield_bit_offset, bool show_types, - bool show_summary, bool verbose, uint32_t depth) { - // This doesn't seem to be needed. - assert(false && "Not implemented"); -} - -bool RustASTContext::DumpTypeValue(lldb::opaque_compiler_type_t type, Stream *s, - lldb::Format format, const DataExtractor &data, - lldb::offset_t byte_offset, size_t byte_size, - uint32_t bitfield_bit_size, - uint32_t bitfield_bit_offset, - ExecutionContextScope *exe_scope) { - if (!type) - return false; - if (IsAggregateType(type)) { - return false; - } else { - RustType *t = static_cast<RustType *>(type); - if (RustTypedef *typ = t->AsTypedef()) { - CompilerType typedef_compiler_type = typ->UnderlyingType(); - if (format == eFormatDefault) - format = typedef_compiler_type.GetFormat(); - llvm::Optional<uint64_t> typedef_byte_size = - typedef_compiler_type.GetByteSize(exe_scope); - if (!typedef_byte_size) - return false; - - return typedef_compiler_type.DumpTypeValue( - s, - format, // The format with which to display the element - data, // Data buffer containing all bytes for this type - byte_offset, // Offset into "data" where to grab value from - *typedef_byte_size,// Size of this type in bytes - bitfield_bit_size, // Size in bits of a bitfield value, if zero don't - // treat as a bitfield - bitfield_bit_offset, // Offset in bits of a bitfield value if - // bitfield_bit_size != 0 - exe_scope); - } - - if (format == eFormatEnum || format == eFormatDefault) { - if (RustCLikeEnum *clike = t->AsCLikeEnum()) { - uint64_t value; - if (clike->IsSigned()) { - int64_t svalue = data.GetMaxS64Bitfield(&byte_offset, byte_size, - bitfield_bit_size, - bitfield_bit_offset); - value = uint64_t(svalue); - } else { - value = data.GetMaxU64Bitfield(&byte_offset, byte_size, - bitfield_bit_size, - bitfield_bit_offset); - } - - std::string name; - if (clike->FindName(value, name)) { - s->Printf("%s::%s", clike->Name().AsCString(), name.c_str()); - } else { - // If the value couldn't be found, then something went wrong - // we should inform the user. - s->Printf("(invalid enum value) %" PRIu64, value); - } - return true; - } - } else if (format == eFormatUnicode32) { - if (RustIntegral *intlike = t->AsInteger()) { - if (intlike->IsCharType()) { - uint64_t value = data.GetMaxU64Bitfield(&byte_offset, byte_size, - bitfield_bit_size, - bitfield_bit_offset); - switch (value) { - case '\n': - s->PutCString("'\\n'"); - break; - case '\r': - s->PutCString("'\\r'"); - break; - case '\t': - s->PutCString("'\\t'"); - break; - case '\\': - s->PutCString("'\\\\'"); - break; - case '\0': - s->PutCString("'\\0'"); - break; - case '\'': - s->PutCString("'\\''"); - break; - - default: - if (value < 128 && isprint(value)) { - s->Printf("'%c'", char(value)); - } else { - s->Printf("'\\u{%x}'", unsigned(value)); - } - break; - } - - return true; - } - } - } - - uint32_t item_count = 1; - switch (format) { - default: - case eFormatBoolean: - case eFormatBinary: - case eFormatComplex: - case eFormatCString: - case eFormatDecimal: - case eFormatEnum: - case eFormatHex: - case eFormatHexUppercase: - case eFormatFloat: - case eFormatOctal: - case eFormatOSType: - case eFormatUnsigned: - case eFormatPointer: - case eFormatVectorOfChar: - case eFormatVectorOfSInt8: - case eFormatVectorOfUInt8: - case eFormatVectorOfSInt16: - case eFormatVectorOfUInt16: - case eFormatVectorOfSInt32: - case eFormatVectorOfUInt32: - case eFormatVectorOfSInt64: - case eFormatVectorOfUInt64: - case eFormatVectorOfFloat32: - case eFormatVectorOfFloat64: - case eFormatVectorOfUInt128: - break; - - case eFormatChar: - case eFormatCharPrintable: - case eFormatCharArray: - case eFormatBytes: - case eFormatBytesWithASCII: - item_count = byte_size; - byte_size = 1; - break; - - case eFormatUnicode16: - item_count = byte_size / 2; - byte_size = 2; - break; - - case eFormatUnicode32: - item_count = byte_size / 4; - byte_size = 4; - break; - } - return DumpDataExtractor(data, s, byte_offset, format, byte_size, item_count, - UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size, - bitfield_bit_offset, exe_scope); - } - return 0; -} - -void RustASTContext::DumpSummary(lldb::opaque_compiler_type_t type, - ExecutionContext *exe_ctx, Stream *s, - const DataExtractor &data, - lldb::offset_t data_offset, - size_t data_byte_size) { - // Apparently there is nothing to do here. -} - -void RustASTContext::DumpTypeDescription(lldb::opaque_compiler_type_t type) { - // Dump to stdout - StreamFile s(stdout, false); - DumpTypeDescription(type, &s); -} - -void RustASTContext::DumpTypeDescription(lldb::opaque_compiler_type_t type, Stream *s) { - if (!type) - return; - ConstString name = GetTypeName(type); - RustType *t = static_cast<RustType *>(type); - - if (RustAggregateBase *agg = t->AsAggregate()) { - s->PutCString(agg->Tag()); - const char *name = agg->TagName(); - s->PutCString(name); - if (*name) { - s->PutCString(" "); - } - s->PutCString(agg->Opener()); - if (agg->FieldCount() == 0) { - s->PutCString(agg->Closer()); - return; - } - s->IndentMore(); - // A trailing comma looks weird for tuples, so we keep track and - // don't emit it. - bool first = true; - for (auto &&field : *agg) { - if (!first) { - s->PutChar(','); - } - first = false; - s->PutChar('\n'); - s->Indent(); - if (!field.m_name.IsEmpty()) { - s->PutCString(field.m_name.AsCString()); - s->PutCString(": "); - } - s->PutCString(field.m_type.GetTypeName().AsCString()); - } - s->IndentLess(); - s->PutChar('\n'); - s->Indent(agg->Closer()); - return; - } - - s->PutCString(name.AsCString()); -} - -CompilerType RustASTContext::CacheType(RustType *new_type) { - m_types.insert(std::unique_ptr<RustType>(new_type)); - return CompilerType(this, new_type); -} - -CompilerType RustASTContext::CreateBoolType(const lldb_private::ConstString &name) { - RustType *type = new RustBool(name); - return CacheType(type); -} - -CompilerType RustASTContext::CreateIntegralType(const lldb_private::ConstString &name, - bool is_signed, - uint64_t byte_size, - bool is_char_type) { - RustType *type = new RustIntegral(name, is_signed, byte_size, is_char_type); - return CacheType(type); -} - -CompilerType RustASTContext::CreateIntrinsicIntegralType(bool is_signed, uint64_t byte_size) { - char name[100]; - snprintf(name, sizeof(name), "%s%d", is_signed ? "i" : "u", int(byte_size * 8)); - - ConstString cname(name); - return CreateIntegralType(cname, is_signed, byte_size); -} - -CompilerType RustASTContext::CreateCharType() { - ConstString cname("char"); - return CreateIntegralType(cname, false, 4, true); -} - -CompilerType RustASTContext::CreateFloatType(const lldb_private::ConstString &name, - uint64_t byte_size) { - RustType *type = new RustFloat(name, byte_size); - return CacheType(type); -} - -CompilerType RustASTContext::CreateArrayType(const CompilerType &element_type, - uint64_t length) { - std::string name = std::string("[") + element_type.GetTypeName().AsCString(); - if (length != 0) { - name = name + "; " + std::to_string(length); - } - name += "]"; - ConstString newname(name); - - RustType *type = new RustArray(newname, length, element_type); - return CacheType(type); -} - -CompilerType RustASTContext::CreateTypedefType(const ConstString &name, CompilerType impl) { - RustType *type = new RustTypedef(name, impl); - return CacheType(type); -} - -CompilerType -RustASTContext::CreateStructType(const lldb_private::ConstString &name, uint32_t byte_size, - bool has_discriminant) { - RustType *type = new RustStruct(name, byte_size, has_discriminant); - return CacheType(type); -} - -CompilerType -RustASTContext::CreateTupleType(const lldb_private::ConstString &name, uint32_t byte_size, - bool has_discriminant) { - RustType *type = new RustTuple(name, byte_size, has_discriminant); - return CacheType(type); -} - -CompilerType -RustASTContext::CreateUnionType(const lldb_private::ConstString &name, uint32_t byte_size) { - RustType *type = new RustUnion(name, byte_size); - return CacheType(type); -} - -CompilerType -RustASTContext::CreatePointerType(const lldb_private::ConstString &name, - const CompilerType &pointee_type, - uint32_t byte_size) { - RustType *type = new RustPointer(name, pointee_type, byte_size); - return CacheType(type); -} - -void RustASTContext::AddFieldToStruct(const CompilerType &struct_type, - const lldb_private::ConstString &name, - const CompilerType &field_type, - uint32_t byte_offset, - bool is_default, uint64_t discriminant) { - if (!struct_type) - return; - RustASTContext *ast = - llvm::dyn_cast_or_null<RustASTContext>(struct_type.GetTypeSystem()); - if (!ast) - return; - RustType *type = static_cast<RustType *>(struct_type.GetOpaqueQualType()); - if (RustAggregateBase *a = type->AsAggregate()) { - a->AddField(name, field_type, byte_offset); - if (RustEnum *e = type->AsEnum()) { - e->RecordDiscriminant(is_default, discriminant); - } - } -} - -CompilerType -RustASTContext::CreateFunctionType(const lldb_private::ConstString &name, - const CompilerType &return_type, - const std::vector<CompilerType> &¶ms, - const std::vector<CompilerType> &&template_params) { - RustType *type = new RustFunction(name, m_pointer_byte_size, return_type, std::move(params), - std::move(template_params)); - return CacheType(type); -} - -CompilerType -RustASTContext::CreateVoidType() { - ConstString name("()"); - RustType *type = new RustTuple(name, 0, false); - return CacheType(type); -} - -CompilerType -RustASTContext::CreateEnumType(const lldb_private::ConstString &name, - uint64_t byte_size, uint32_t discr_offset, - uint32_t discr_byte_size) { - RustType *type = new RustEnum(name, byte_size, discr_offset, discr_byte_size); - return CacheType(type); -} - -CompilerType -RustASTContext::CreateCLikeEnumType(const lldb_private::ConstString &name, - const CompilerType &underlying_type, - std::map<uint64_t, std::string> &&values) { - RustType *type = new RustCLikeEnum(name, underlying_type, std::move(values)); - return CacheType(type); -} - -bool -RustASTContext::IsTupleType(const CompilerType &type) { - if (!type) - return false; - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!ast) - return false; - RustType *rtype = static_cast<RustType *>(type.GetOpaqueQualType()); - return bool(rtype->AsTuple()); -} - -bool -RustASTContext::TypeHasDiscriminant(const CompilerType &type) { - if (!type) - return false; - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!ast) - return false; - RustType *rtype = static_cast<RustType *>(type.GetOpaqueQualType()); - if (RustAggregateBase *a = rtype->AsAggregate()) - return a->HasDiscriminant(); - return false; -} - -bool -RustASTContext::GetEnumDiscriminantLocation(const CompilerType &type, uint64_t &discr_offset, - uint64_t &discr_byte_size) { - if (!type) - return false; - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!ast) - return false; - RustType *rtype = static_cast<RustType *>(type.GetOpaqueQualType()); - if (RustEnum *e = rtype->AsEnum()) { - e->GetDiscriminantLocation(discr_offset, discr_byte_size); - return true; - } - return false; -} - -CompilerType -RustASTContext::FindEnumVariant(const CompilerType &type, uint64_t discriminant) { - if (!type) - return CompilerType(); - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!ast) - return CompilerType(); - RustType *rtype = static_cast<RustType *>(type.GetOpaqueQualType()); - if (RustEnum *e = rtype->AsEnum()) { - return e->FindEnumVariant(discriminant); - } - return CompilerType(); -} - -void -RustASTContext::FinishAggregateInitialization(const CompilerType &type) { - if (!type) - return; - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!ast) - return; - RustType *rtype = static_cast<RustType *>(type.GetOpaqueQualType()); - if (RustAggregateBase *a = rtype->AsAggregate()) - a->FinishInitialization(); -} - -DWARFASTParser *RustASTContext::GetDWARFParser() { - if (!m_dwarf_ast_parser_ap) - m_dwarf_ast_parser_ap.reset(new DWARFASTParserRust(*this)); - return m_dwarf_ast_parser_ap.get(); -} - -UserExpression *RustASTContextForExpr::GetUserExpression( - llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, - Expression::ResultType desired_type, - const EvaluateExpressionOptions &options) { - TargetSP target = m_target_wp.lock(); - if (target) - return new RustUserExpression(*target, expr, prefix, language, desired_type, - options); - return nullptr; -} - -ConstString RustASTContext::DeclGetName(void *opaque_decl) { - RustDecl *dc = (RustDecl *) opaque_decl; - return dc->Name(); -} - -ConstString RustASTContext::DeclGetMangledName(void *opaque_decl) { - RustDecl *dc = (RustDecl *) opaque_decl; - return dc->MangledName(); -} - -CompilerDeclContext RustASTContext::DeclGetDeclContext(void *opaque_decl) { - RustDecl *dc = (RustDecl *) opaque_decl; - return CompilerDeclContext(this, dc->Context()); -} - -ConstString RustASTContext::DeclContextGetName(void *opaque_decl_ctx) { - RustDeclContext *dc = (RustDeclContext *) opaque_decl_ctx; - return dc->Name(); -} - -ConstString RustASTContext::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) { - RustDeclContext *dc = (RustDeclContext *) opaque_decl_ctx; - return dc->QualifiedName(); -} - -bool RustASTContext::DeclContextIsStructUnionOrClass(void *opaque_decl_ctx) { - // This is not actually correct -- for example an enum arm is nested - // in its containing enum -- but as far as I can tell this result - // doesn't matter for Rust. - return false; -} - -bool RustASTContext::DeclContextIsClassMethod(void *opaque_decl_ctx, - lldb::LanguageType *language_ptr, - bool *is_instance_method_ptr, - ConstString *language_object_name_ptr) { - return false; -} - -std::vector<CompilerDecl> -RustASTContext::DeclContextFindDeclByName(void *opaque_decl_ctx, ConstString name, - const bool ignore_imported_decls) { - std::vector<CompilerDecl> result; - SymbolFile *symbol_file = GetSymbolFile(); - if (symbol_file) { - symbol_file->ParseDeclsForContext(CompilerDeclContext(this, opaque_decl_ctx)); - - RustDeclContext *dc = (RustDeclContext *) opaque_decl_ctx; - RustDeclBase *base = dc->FindByName(name); - if (RustDecl *decl = base ? base->AsDecl() : nullptr) { - result.push_back(CompilerDecl(this, decl)); - } - } - return result; -} - -CompilerDeclContext RustASTContext::GetTranslationUnitDecl() { - if (!m_tu_decl) { - m_tu_decl.reset(new RustDeclContext(ConstString(""), nullptr)); - } - return CompilerDeclContext(this, m_tu_decl.get()); -} - -CompilerDeclContext -RustASTContext::GetNamespaceDecl(CompilerDeclContext parent, const ConstString &name) { - if (!parent) - return CompilerDeclContext(); - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(parent.GetTypeSystem()); - if (!ast) - return CompilerDeclContext(); - - RustDeclContext *dc = (RustDeclContext *) parent.GetOpaqueDeclContext(); - RustDeclBase *base = dc->FindByName(name); - if (base) { - if (RustDeclContext *ctx = base->AsDeclContext()) { - return CompilerDeclContext(this, ctx); - } - } - - RustDeclContext *new_ns = new RustDeclContext(name, dc); - dc->AddItem(std::unique_ptr<RustDeclBase>(new_ns)); - return CompilerDeclContext(this, new_ns); -} - -CompilerDeclContext -RustASTContext::GetDeclContextDeclContext(CompilerDeclContext child) { - if (!child) - return CompilerDeclContext(); - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(child.GetTypeSystem()); - if (!ast) - return CompilerDeclContext(); - - RustDeclContext *dc = (RustDeclContext *) child.GetOpaqueDeclContext(); - return CompilerDeclContext(this, dc->Context()); -} - -CompilerDecl RustASTContext::GetDecl(CompilerDeclContext parent, const ConstString &name, - const ConstString &mangled) { - if (!parent) - return CompilerDecl(); - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(parent.GetTypeSystem()); - if (!ast) - return CompilerDecl(); - - RustDeclContext *dc = (RustDeclContext *) parent.GetOpaqueDeclContext(); - RustDeclBase *base = dc->FindByName(name); - if (base) { - if (RustDecl *ctx = base->AsDecl()) { - return CompilerDecl(this, ctx); - } - } - - RustDecl *new_ns = new RustDecl(name, mangled, dc); - dc->AddItem(std::unique_ptr<RustDeclBase>(new_ns)); - return CompilerDecl(this, new_ns); -} - -bool RustASTContext::GetCABITypeDeclaration(CompilerType type, const std::string &varname, - RustASTContext::TypeNameMap *name_map, - std::string *result) { - if (!type) - return false; - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!ast) - return false; - RustType *rtype = static_cast<RustType *>(type.GetOpaqueQualType()); - *result = rtype->GetCABITypeDeclaration(name_map, varname); - return true; -} - -CompilerType RustASTContext::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type, - size_t idx) { - if (type) { - RustType *t = static_cast<RustType *>(type); - if (RustAggregateBase *a = t->AsAggregate()) { - return a->GetTypeTemplateArgument(idx); - } else if (RustFunction *f = t->AsFunction()) { - return f->GetTypeTemplateArgument(idx); - } - } - return CompilerType(); -} - -size_t RustASTContext::GetNumTemplateArguments(lldb::opaque_compiler_type_t type) { - if (type) { - RustType *t = static_cast<RustType *>(type); - if (RustAggregateBase *a = t->AsAggregate()) { - return a->GetNumTemplateArguments(); - } else if (RustFunction *f = t->AsFunction()) { - return f->GetNumTemplateArguments(); - } - } - return 0; -} - -void RustASTContext::AddTemplateParameter(const CompilerType &type, const CompilerType ¶m) { - if (!type) - return; - RustASTContext *ast = llvm::dyn_cast_or_null<RustASTContext>(type.GetTypeSystem()); - if (!ast) - return; - RustType *t = static_cast<RustType *>(type.GetOpaqueQualType()); - if (RustAggregateBase *a = t->AsAggregate()) { - a->AddTemplateParameter(param); - } -}
diff --git a/src/llvm-project/lldb/source/Symbol/Symbol.cpp b/src/llvm-project/lldb/source/Symbol/Symbol.cpp index 8d055c1..589f692 100644 --- a/src/llvm-project/lldb/source/Symbol/Symbol.cpp +++ b/src/llvm-project/lldb/source/Symbol/Symbol.cpp
@@ -1,9 +1,8 @@ //===-- Symbol.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,7 +28,8 @@ m_is_external(false), m_size_is_sibling(false), m_size_is_synthesized(false), m_size_is_valid(false), m_demangled_is_synthesized(false), m_contains_linker_annotations(false), - m_type(eSymbolTypeInvalid), m_mangled(), m_addr_range(), m_flags() {} + m_is_weak(false), m_type(eSymbolTypeInvalid), m_mangled(), m_addr_range(), + m_flags() {} Symbol::Symbol(uint32_t symID, const char *name, bool name_is_mangled, SymbolType type, bool external, bool is_debug, @@ -42,7 +42,8 @@ m_is_debug(is_debug), m_is_external(external), m_size_is_sibling(false), m_size_is_synthesized(false), m_size_is_valid(size_is_valid || size > 0), m_demangled_is_synthesized(false), - m_contains_linker_annotations(contains_linker_annotations), m_type(type), + m_contains_linker_annotations(contains_linker_annotations), + m_is_weak(false), m_type(type), m_mangled(ConstString(name), name_is_mangled), m_addr_range(section_sp, offset, size), m_flags(flags) {} @@ -57,8 +58,9 @@ m_size_is_synthesized(false), m_size_is_valid(size_is_valid || range.GetByteSize() > 0), m_demangled_is_synthesized(false), - m_contains_linker_annotations(contains_linker_annotations), m_type(type), - m_mangled(mangled), m_addr_range(range), m_flags(flags) {} + m_contains_linker_annotations(contains_linker_annotations), + m_is_weak(false), m_type(type), m_mangled(mangled), m_addr_range(range), + m_flags(flags) {} Symbol::Symbol(const Symbol &rhs) : SymbolContextScope(rhs), m_uid(rhs.m_uid), m_type_data(rhs.m_type_data), @@ -69,7 +71,7 @@ m_size_is_valid(rhs.m_size_is_valid), m_demangled_is_synthesized(rhs.m_demangled_is_synthesized), m_contains_linker_annotations(rhs.m_contains_linker_annotations), - m_type(rhs.m_type), m_mangled(rhs.m_mangled), + m_is_weak(rhs.m_is_weak), m_type(rhs.m_type), m_mangled(rhs.m_mangled), m_addr_range(rhs.m_addr_range), m_flags(rhs.m_flags) {} const Symbol &Symbol::operator=(const Symbol &rhs) { @@ -86,6 +88,7 @@ m_size_is_valid = rhs.m_size_is_valid; m_demangled_is_synthesized = rhs.m_demangled_is_synthesized; m_contains_linker_annotations = rhs.m_contains_linker_annotations; + m_is_weak = rhs.m_is_weak; m_type = rhs.m_type; m_mangled = rhs.m_mangled; m_addr_range = rhs.m_addr_range; @@ -107,6 +110,7 @@ m_size_is_valid = false; m_demangled_is_synthesized = false; m_contains_linker_annotations = false; + m_is_weak = false; m_type = eSymbolTypeInvalid; m_flags = 0; m_addr_range.Clear(); @@ -146,7 +150,7 @@ return FileSpec(); } -void Symbol::SetReExportedSymbolName(const ConstString &name) { +void Symbol::SetReExportedSymbolName(ConstString name) { SetType(eSymbolTypeReExported); // For eSymbolTypeReExported, the "const char *" from a ConstString is used // as the offset in the address range base address. @@ -326,7 +330,7 @@ return 0; } -bool Symbol::Compare(const ConstString &name, SymbolType type) const { +bool Symbol::Compare(ConstString name, SymbolType type) const { if (type == eSymbolTypeAny || m_type == type) return m_mangled.GetMangledName() == name || m_mangled.GetDemangledName(GetLanguage()) == name;
diff --git a/src/llvm-project/lldb/source/Symbol/SymbolContext.cpp b/src/llvm-project/lldb/source/Symbol/SymbolContext.cpp index da00875..a0b35cf 100644 --- a/src/llvm-project/lldb/source/Symbol/SymbolContext.cpp +++ b/src/llvm-project/lldb/source/Symbol/SymbolContext.cpp
@@ -1,9 +1,8 @@ //===-- SymbolContext.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -48,11 +47,6 @@ line_entry = *le; } -SymbolContext::SymbolContext(const SymbolContext &rhs) - : target_sp(rhs.target_sp), module_sp(rhs.module_sp), - comp_unit(rhs.comp_unit), function(rhs.function), block(rhs.block), - line_entry(rhs.line_entry), symbol(rhs.symbol), variable(rhs.variable) {} - SymbolContext::SymbolContext(SymbolContextScope *sc_scope) : target_sp(), module_sp(), comp_unit(nullptr), function(nullptr), block(nullptr), line_entry(), symbol(nullptr), variable(nullptr) { @@ -507,7 +501,7 @@ } #ifdef LLDB_CONFIGURATION_DEBUG else { - ObjectFile *objfile = NULL; + ObjectFile *objfile = nullptr; if (module_sp) { SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor(); if (symbol_vendor) { @@ -587,10 +581,8 @@ curr_block->GetContainingInlinedBlock() != nullptr) isInlinedblock = true; - //---------------------------------------------------------------------- // Find all types that match the current block if we have one and put them // first in the list. Keep iterating up through all blocks. - //---------------------------------------------------------------------- while (curr_block != nullptr && !isInlinedblock) { type_map.ForEach( [curr_block, &type_list](const lldb::TypeSP &type_sp) -> bool { @@ -608,10 +600,8 @@ }); curr_block = curr_block->GetParent(); } - //---------------------------------------------------------------------- // Find all types that match the current function, if we have onem, and put // them next in the list. - //---------------------------------------------------------------------- if (function != nullptr && !type_map.Empty()) { const size_t old_type_list_size = type_list.GetSize(); type_map.ForEach([this, &type_list](const lldb::TypeSP &type_sp) -> bool { @@ -629,10 +619,8 @@ type_map.Remove(type_list.GetTypeAtIndex(i)); } } - //---------------------------------------------------------------------- // Find all types that match the current compile unit, if we have one, and // put them next in the list. - //---------------------------------------------------------------------- if (comp_unit != nullptr && !type_map.Empty()) { const size_t old_type_list_size = type_list.GetSize(); @@ -651,10 +639,8 @@ type_map.Remove(type_list.GetTypeAtIndex(i)); } } - //---------------------------------------------------------------------- // Find all types that match the current module, if we have one, and put them // next in the list. - //---------------------------------------------------------------------- if (module_sp && !type_map.Empty()) { const size_t old_type_list_size = type_list.GetSize(); type_map.ForEach([this, &type_list](const lldb::TypeSP &type_sp) -> bool { @@ -671,9 +657,7 @@ type_map.Remove(type_list.GetTypeAtIndex(i)); } } - //---------------------------------------------------------------------- // Any types that are left get copied into the list an any order. - //---------------------------------------------------------------------- if (!type_map.Empty()) { type_map.ForEach([&type_list](const lldb::TypeSP &type_sp) -> bool { type_list.Insert(type_sp); @@ -745,7 +729,7 @@ uint32_t line_index = 0; bool found = false; - while (1) { + while (true) { LineEntry this_line; line_index = comp_unit->FindLineEntry(line_index, line_entry.line, nullptr, false, &this_line); @@ -794,7 +778,7 @@ } const Symbol * -SymbolContext::FindBestGlobalDataSymbol(const ConstString &name, Status &error) { +SymbolContext::FindBestGlobalDataSymbol(ConstString name, Status &error) { error.Clear(); if (!target_sp) { @@ -950,16 +934,14 @@ } -//---------------------------------------------------------------------- // // SymbolContextSpecifier // -//---------------------------------------------------------------------- SymbolContextSpecifier::SymbolContextSpecifier(const TargetSP &target_sp) - : m_target_sp(target_sp), m_module_spec(), m_module_sp(), m_file_spec_ap(), + : m_target_sp(target_sp), m_module_spec(), m_module_sp(), m_file_spec_up(), m_start_line(0), m_end_line(0), m_function_spec(), m_class_name(), - m_address_range_ap(), m_type(eNothingSpecified) {} + m_address_range_up(), m_type(eNothingSpecified) {} SymbolContextSpecifier::~SymbolContextSpecifier() {} @@ -1008,7 +990,7 @@ // CompUnits can't necessarily be resolved here, since an inlined function // might show up in a number of CompUnits. Instead we just convert to a // FileSpec and store it away. - m_file_spec_ap.reset(new FileSpec(spec_string)); + m_file_spec_up.reset(new FileSpec(spec_string)); m_type |= eFileSpecified; break; case eLineStartSpecified: @@ -1040,12 +1022,12 @@ void SymbolContextSpecifier::Clear() { m_module_spec.clear(); - m_file_spec_ap.reset(); + m_file_spec_up.reset(); m_function_spec.clear(); m_class_name.clear(); m_start_line = 0; m_end_line = 0; - m_address_range_ap.reset(); + m_address_range_up.reset(); m_type = eNothingSpecified; } @@ -1071,7 +1053,7 @@ } } if (m_type & eFileSpecified) { - if (m_file_spec_ap.get()) { + if (m_file_spec_up) { // If we don't have a block or a comp_unit, then we aren't going to match // a source file. if (sc.block == nullptr && sc.comp_unit == nullptr) @@ -1085,7 +1067,7 @@ if (inline_info != nullptr) { was_inlined = true; if (!FileSpec::Equal(inline_info->GetDeclaration().GetFile(), - *(m_file_spec_ap.get()), false)) + *(m_file_spec_up.get()), false)) return false; } } @@ -1093,7 +1075,7 @@ // Next check the comp unit, but only if the SymbolContext was not // inlined. if (!was_inlined && sc.comp_unit != nullptr) { - if (!FileSpec::Equal(*(sc.comp_unit), *(m_file_spec_ap.get()), false)) + if (!FileSpec::Equal(*(sc.comp_unit), *(m_file_spec_up.get()), false)) return false; } } @@ -1166,8 +1148,8 @@ s->Printf("Module: %s\n", m_module_spec.c_str()); } - if (m_type == eFileSpecified && m_file_spec_ap.get() != nullptr) { - m_file_spec_ap->GetPath(path_str, PATH_MAX); + if (m_type == eFileSpecified && m_file_spec_up != nullptr) { + m_file_spec_up->GetPath(path_str, PATH_MAX); s->Indent(); s->Printf("File: %s", path_str); if (m_type == eLineStartSpecified) { @@ -1204,21 +1186,19 @@ s->Printf("Class name: %s.\n", m_class_name.c_str()); } - if (m_type == eAddressRangeSpecified && m_address_range_ap.get() != nullptr) { + if (m_type == eAddressRangeSpecified && m_address_range_up != nullptr) { s->Indent(); s->PutCString("Address range: "); - m_address_range_ap->Dump(s, m_target_sp.get(), + m_address_range_up->Dump(s, m_target_sp.get(), Address::DumpStyleLoadAddress, Address::DumpStyleFileAddress); s->PutCString("\n"); } } -//---------------------------------------------------------------------- // // SymbolContextList // -//---------------------------------------------------------------------- SymbolContextList::SymbolContextList() : m_symbol_contexts() {}
diff --git a/src/llvm-project/lldb/source/Symbol/SymbolFile.cpp b/src/llvm-project/lldb/source/Symbol/SymbolFile.cpp index 6087374..77ab222 100644 --- a/src/llvm-project/lldb/source/Symbol/SymbolFile.cpp +++ b/src/llvm-project/lldb/source/Symbol/SymbolFile.cpp
@@ -1,9 +1,8 @@ //===-- SymbolFile.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -32,7 +31,7 @@ } SymbolFile *SymbolFile::FindPlugin(ObjectFile *obj_file) { - std::unique_ptr<SymbolFile> best_symfile_ap; + std::unique_ptr<SymbolFile> best_symfile_up; if (obj_file != nullptr) { // We need to test the abilities of this section list. So create what it @@ -58,13 +57,13 @@ (create_callback = PluginManager::GetSymbolFileCreateCallbackAtIndex( idx)) != nullptr; ++idx) { - std::unique_ptr<SymbolFile> curr_symfile_ap(create_callback(obj_file)); + std::unique_ptr<SymbolFile> curr_symfile_up(create_callback(obj_file)); - if (curr_symfile_ap.get()) { - const uint32_t sym_file_abilities = curr_symfile_ap->GetAbilities(); + if (curr_symfile_up) { + const uint32_t sym_file_abilities = curr_symfile_up->GetAbilities(); if (sym_file_abilities > best_symfile_abilities) { best_symfile_abilities = sym_file_abilities; - best_symfile_ap.reset(curr_symfile_ap.release()); + best_symfile_up.reset(curr_symfile_up.release()); // If any symbol file parser has all of the abilities, then we should // just stop looking. if ((kAllAbilities & sym_file_abilities) == kAllAbilities) @@ -72,13 +71,13 @@ } } } - if (best_symfile_ap.get()) { + if (best_symfile_up) { // Let the winning symbol file parser initialize itself more completely // now that it has been chosen - best_symfile_ap->InitializeObject(); + best_symfile_up->InitializeObject(); } } - return best_symfile_ap.release(); + return best_symfile_up.release(); } TypeList *SymbolFile::GetTypeList() { @@ -103,7 +102,7 @@ } uint32_t -SymbolFile::FindGlobalVariables(const ConstString &name, +SymbolFile::FindGlobalVariables(ConstString name, const CompilerDeclContext *parent_decl_ctx, uint32_t max_matches, VariableList &variables) { return 0; @@ -115,7 +114,7 @@ return 0; } -uint32_t SymbolFile::FindFunctions(const ConstString &name, +uint32_t SymbolFile::FindFunctions(ConstString name, const CompilerDeclContext *parent_decl_ctx, lldb::FunctionNameType name_type_mask, bool include_inlines, bool append, @@ -140,7 +139,7 @@ } uint32_t SymbolFile::FindTypes( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeMap &types) { @@ -169,3 +168,5 @@ "Module is not locked"); #endif } + +SymbolFile::RegisterInfoResolver::~RegisterInfoResolver() = default;
diff --git a/src/llvm-project/lldb/source/Symbol/SymbolVendor.cpp b/src/llvm-project/lldb/source/Symbol/SymbolVendor.cpp index a9badc1..b9f3a5f 100644 --- a/src/llvm-project/lldb/source/Symbol/SymbolVendor.cpp +++ b/src/llvm-project/lldb/source/Symbol/SymbolVendor.cpp
@@ -1,9 +1,8 @@ //===-- SymbolVendor.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,61 +18,60 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // FindPlugin // // Platforms can register a callback to use when creating symbol vendors to // allow for complex debug information file setups, and to also allow for // finding separate debug information files. -//---------------------------------------------------------------------- SymbolVendor *SymbolVendor::FindPlugin(const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm) { - std::unique_ptr<SymbolVendor> instance_ap; + std::unique_ptr<SymbolVendor> instance_up; SymbolVendorCreateInstance create_callback; for (size_t idx = 0; (create_callback = PluginManager::GetSymbolVendorCreateCallbackAtIndex( idx)) != nullptr; ++idx) { - instance_ap.reset(create_callback(module_sp, feedback_strm)); + instance_up.reset(create_callback(module_sp, feedback_strm)); - if (instance_ap.get()) { - return instance_ap.release(); + if (instance_up) { + return instance_up.release(); } } // The default implementation just tries to create debug information using // the file representation for the module. - instance_ap.reset(new SymbolVendor(module_sp)); - if (instance_ap.get()) { - ObjectFile *objfile = module_sp->GetObjectFile(); - if (objfile) - instance_ap->AddSymbolFileRepresentation(objfile->shared_from_this()); + ObjectFileSP sym_objfile_sp; + FileSpec sym_spec = module_sp->GetSymbolFileFileSpec(); + if (sym_spec && sym_spec != module_sp->GetObjectFile()->GetFileSpec()) { + DataBufferSP data_sp; + offset_t data_offset = 0; + sym_objfile_sp = ObjectFile::FindPlugin( + module_sp, &sym_spec, 0, FileSystem::Instance().GetByteSize(sym_spec), + data_sp, data_offset); } - return instance_ap.release(); + if (!sym_objfile_sp) + sym_objfile_sp = module_sp->GetObjectFile()->shared_from_this(); + instance_up.reset(new SymbolVendor(module_sp)); + instance_up->AddSymbolFileRepresentation(sym_objfile_sp); + return instance_up.release(); } -//---------------------------------------------------------------------- // SymbolVendor constructor -//---------------------------------------------------------------------- SymbolVendor::SymbolVendor(const lldb::ModuleSP &module_sp) - : ModuleChild(module_sp), m_type_list(), m_compile_units(), - m_sym_file_ap(), m_symtab() {} + : ModuleChild(module_sp), m_type_list(), m_compile_units(), m_sym_file_up(), + m_symtab() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- SymbolVendor::~SymbolVendor() {} -//---------------------------------------------------------------------- // Add a representation given an object file. -//---------------------------------------------------------------------- void SymbolVendor::AddSymbolFileRepresentation(const ObjectFileSP &objfile_sp) { ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); if (objfile_sp) { m_objfile_sp = objfile_sp; - m_sym_file_ap.reset(SymbolFile::FindPlugin(objfile_sp.get())); + m_sym_file_up.reset(SymbolFile::FindPlugin(objfile_sp.get())); } } } @@ -106,12 +104,12 @@ if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); if (m_compile_units.empty()) { - if (m_sym_file_ap.get()) { + if (m_sym_file_up) { // Resize our array of compile unit shared pointers -- which will each // remain NULL until someone asks for the actual compile unit // information. When this happens, the symbol file will be asked to // parse this compile unit information. - m_compile_units.resize(m_sym_file_ap->GetNumCompileUnits()); + m_compile_units.resize(m_sym_file_up->GetNumCompileUnits()); } } } @@ -122,8 +120,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseLanguage(comp_unit); + if (m_sym_file_up) + return m_sym_file_up->ParseLanguage(comp_unit); } return eLanguageTypeUnknown; } @@ -132,8 +130,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseFunctions(comp_unit); + if (m_sym_file_up) + return m_sym_file_up->ParseFunctions(comp_unit); } return 0; } @@ -142,8 +140,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseLineTable(comp_unit); + if (m_sym_file_up) + return m_sym_file_up->ParseLineTable(comp_unit); } return false; } @@ -152,8 +150,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseDebugMacros(comp_unit); + if (m_sym_file_up) + return m_sym_file_up->ParseDebugMacros(comp_unit); } return false; } @@ -162,8 +160,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseSupportFiles(comp_unit, support_files); + if (m_sym_file_up) + return m_sym_file_up->ParseSupportFiles(comp_unit, support_files); } return false; } @@ -172,19 +170,19 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseIsOptimized(comp_unit); + if (m_sym_file_up) + return m_sym_file_up->ParseIsOptimized(comp_unit); } return false; } bool SymbolVendor::ParseImportedModules( - const SymbolContext &sc, std::vector<ConstString> &imported_modules) { + const SymbolContext &sc, std::vector<SourceModule> &imported_modules) { ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseImportedModules(sc, imported_modules); + if (m_sym_file_up) + return m_sym_file_up->ParseImportedModules(sc, imported_modules); } return false; } @@ -193,8 +191,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseBlocksRecursive(func); + if (m_sym_file_up) + return m_sym_file_up->ParseBlocksRecursive(func); } return 0; } @@ -203,8 +201,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseTypes(comp_unit); + if (m_sym_file_up) + return m_sym_file_up->ParseTypes(comp_unit); } return 0; } @@ -213,8 +211,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ParseVariablesForContext(sc); + if (m_sym_file_up) + return m_sym_file_up->ParseVariablesForContext(sc); } return 0; } @@ -223,8 +221,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ResolveTypeUID(type_uid); + if (m_sym_file_up) + return m_sym_file_up->ResolveTypeUID(type_uid); } return nullptr; } @@ -235,8 +233,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ResolveSymbolContext(so_addr, resolve_scope, sc); + if (m_sym_file_up) + return m_sym_file_up->ResolveSymbolContext(so_addr, resolve_scope, sc); } return 0; } @@ -248,22 +246,22 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->ResolveSymbolContext(file_spec, line, check_inlines, + if (m_sym_file_up) + return m_sym_file_up->ResolveSymbolContext(file_spec, line, check_inlines, resolve_scope, sc_list); } return 0; } size_t -SymbolVendor::FindGlobalVariables(const ConstString &name, +SymbolVendor::FindGlobalVariables(ConstString name, const CompilerDeclContext *parent_decl_ctx, size_t max_matches, VariableList &variables) { ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->FindGlobalVariables(name, parent_decl_ctx, + if (m_sym_file_up) + return m_sym_file_up->FindGlobalVariables(name, parent_decl_ctx, max_matches, variables); } return 0; @@ -275,13 +273,13 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->FindGlobalVariables(regex, max_matches, variables); + if (m_sym_file_up) + return m_sym_file_up->FindGlobalVariables(regex, max_matches, variables); } return 0; } -size_t SymbolVendor::FindFunctions(const ConstString &name, +size_t SymbolVendor::FindFunctions(ConstString name, const CompilerDeclContext *parent_decl_ctx, FunctionNameType name_type_mask, bool include_inlines, bool append, @@ -289,8 +287,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->FindFunctions(name, parent_decl_ctx, name_type_mask, + if (m_sym_file_up) + return m_sym_file_up->FindFunctions(name, parent_decl_ctx, name_type_mask, include_inlines, append, sc_list); } return 0; @@ -302,23 +300,23 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->FindFunctions(regex, include_inlines, append, + if (m_sym_file_up) + return m_sym_file_up->FindFunctions(regex, include_inlines, append, sc_list); } return 0; } size_t SymbolVendor::FindTypes( - const ConstString &name, const CompilerDeclContext *parent_decl_ctx, + ConstString name, const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeMap &types) { ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->FindTypes(name, parent_decl_ctx, append, + if (m_sym_file_up) + return m_sym_file_up->FindTypes(name, parent_decl_ctx, append, max_matches, searched_symbol_files, types); } @@ -332,8 +330,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->FindTypes(context, append, types); + if (m_sym_file_up) + return m_sym_file_up->FindTypes(context, append, types); } if (!append) types.Clear(); @@ -345,21 +343,21 @@ ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - return m_sym_file_ap->GetTypes(sc_scope, type_mask, type_list); + if (m_sym_file_up) + return m_sym_file_up->GetTypes(sc_scope, type_mask, type_list); } return 0; } CompilerDeclContext -SymbolVendor::FindNamespace(const ConstString &name, +SymbolVendor::FindNamespace(ConstString name, const CompilerDeclContext *parent_decl_ctx) { CompilerDeclContext namespace_decl_ctx; ModuleSP module_sp(GetModule()); if (module_sp) { std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); - if (m_sym_file_ap.get()) - namespace_decl_ctx = m_sym_file_ap->FindNamespace(name, parent_decl_ctx); + if (m_sym_file_up) + namespace_decl_ctx = m_sym_file_up->FindNamespace(name, parent_decl_ctx); } return namespace_decl_ctx; } @@ -374,9 +372,9 @@ s->Printf("%p: ", static_cast<void *>(this)); s->Indent(); s->PutCString("SymbolVendor"); - if (m_sym_file_ap.get()) { - *s << " " << m_sym_file_ap->GetPluginName(); - ObjectFile *objfile = m_sym_file_ap->GetObjectFile(); + if (m_sym_file_up) { + *s << " " << m_sym_file_up->GetPluginName(); + ObjectFile *objfile = m_sym_file_up->GetObjectFile(); if (objfile) { const FileSpec &objfile_file_spec = objfile->GetFileSpec(); if (objfile_file_spec) { @@ -387,8 +385,8 @@ } } s->EOL(); - if (m_sym_file_ap) - m_sym_file_ap->Dump(*s); + if (m_sym_file_up) + m_sym_file_up->Dump(*s); s->IndentMore(); m_type_list.Dump(s, show_context); @@ -396,7 +394,7 @@ cu_end = m_compile_units.end(); for (cu_pos = m_compile_units.begin(); cu_pos != cu_end; ++cu_pos) { // We currently only dump the compile units that have been parsed - if (cu_pos->get()) + if (*cu_pos) (*cu_pos)->Dump(s, show_context); } @@ -416,7 +414,7 @@ if (idx < num_compile_units) { cu_sp = m_compile_units[idx]; if (cu_sp.get() == nullptr) { - m_compile_units[idx] = m_sym_file_ap->ParseCompileUnitAtIndex(idx); + m_compile_units[idx] = m_sym_file_up->ParseCompileUnitAtIndex(idx); cu_sp = m_compile_units[idx]; } } @@ -425,8 +423,8 @@ } FileSpec SymbolVendor::GetMainFileSpec() const { - if (m_sym_file_ap.get()) { - const ObjectFile *symfile_objfile = m_sym_file_ap->GetObjectFile(); + if (m_sym_file_up) { + const ObjectFile *symfile_objfile = m_sym_file_up->GetObjectFile(); if (symfile_objfile) return symfile_objfile->GetFileSpec(); } @@ -449,8 +447,8 @@ return nullptr; m_symtab = objfile->GetSymtab(); - if (m_symtab && m_sym_file_ap) - m_sym_file_ap->AddSymbols(*m_symtab); + if (m_symtab && m_sym_file_up) + m_sym_file_up->AddSymbols(*m_symtab); return m_symtab; } @@ -470,8 +468,8 @@ ModuleSP module_sp(GetModule()); if (module_sp) { ObjectFile *module_objfile = module_sp->GetObjectFile(); - if (m_sym_file_ap.get()) { - ObjectFile *symfile_objfile = m_sym_file_ap->GetObjectFile(); + if (m_sym_file_up) { + ObjectFile *symfile_objfile = m_sym_file_up->GetObjectFile(); if (symfile_objfile != module_objfile) symfile_objfile->SectionFileAddressesChanged(); } @@ -482,9 +480,7 @@ } } -//------------------------------------------------------------------ // PluginInterface protocol -//------------------------------------------------------------------ lldb_private::ConstString SymbolVendor::GetPluginName() { static ConstString g_name("vendor-default"); return g_name;
diff --git a/src/llvm-project/lldb/source/Symbol/Symtab.cpp b/src/llvm-project/lldb/source/Symbol/Symtab.cpp index 2472580..29c390e 100644 --- a/src/llvm-project/lldb/source/Symbol/Symtab.cpp +++ b/src/llvm-project/lldb/source/Symbol/Symtab.cpp
@@ -1,9 +1,8 @@ //===-- Symtab.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -217,9 +216,6 @@ return nullptr; } -//---------------------------------------------------------------------- -// InitNameIndexes -//---------------------------------------------------------------------- static bool lldb_skip_name(llvm::StringRef mangled, Mangled::ManglingScheme scheme) { switch (scheme) { @@ -262,25 +258,7 @@ Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); // Create the name index vector to be able to quickly search by name const size_t num_symbols = m_symbols.size(); -#if 1 m_name_to_index.Reserve(num_symbols); -#else - // TODO: benchmark this to see if we save any memory. Otherwise we - // will always keep the memory reserved in the vector unless we pull some - // STL swap magic and then recopy... - uint32_t actual_count = 0; - for (const_iterator pos = m_symbols.begin(), end = m_symbols.end(); - pos != end; ++pos) { - const Mangled &mangled = pos->GetMangled(); - if (mangled.GetMangledName()) - ++actual_count; - - if (mangled.GetDemangledName()) - ++actual_count; - } - - m_name_to_index.Reserve(actual_count); -#endif // The "const char *" in "class_contexts" and backlog::value_type::second // must come from a ConstString::GetCString() @@ -291,10 +269,8 @@ // Instantiation of the demangler is expensive, so better use a single one // for all entries during batch processing. RichManglingContext rmc; - NameToIndexMap::Entry entry; - - for (entry.value = 0; entry.value < num_symbols; ++entry.value) { - Symbol *symbol = &m_symbols[entry.value]; + for (uint32_t value = 0; value < num_symbols; ++value) { + Symbol *symbol = &m_symbols[value]; // Don't let trampolines get into the lookup by name map If we ever need // the trampoline symbols to be searchable by name we can remove this and @@ -306,52 +282,46 @@ // If the symbol's name string matched a Mangled::ManglingScheme, it is // stored in the mangled field. Mangled &mangled = symbol->GetMangled(); - entry.cstring = mangled.GetMangledName(); - if (entry.cstring) { - m_name_to_index.Append(entry); + if (ConstString name = mangled.GetMangledName()) { + m_name_to_index.Append(name, value); if (symbol->ContainsLinkerAnnotations()) { // If the symbol has linker annotations, also add the version without // the annotations. - entry.cstring = ConstString(m_objfile->StripLinkerSymbolAnnotations( - entry.cstring.GetStringRef())); - m_name_to_index.Append(entry); + ConstString stripped = ConstString( + m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef())); + m_name_to_index.Append(stripped, value); } const SymbolType type = symbol->GetType(); if (type == eSymbolTypeCode || type == eSymbolTypeResolver) { if (mangled.DemangleWithRichManglingInfo(rmc, lldb_skip_name)) - RegisterMangledNameEntry(entry, class_contexts, backlog, rmc); + RegisterMangledNameEntry(value, class_contexts, backlog, rmc); } } // Symbol name strings that didn't match a Mangled::ManglingScheme, are // stored in the demangled field. - entry.cstring = mangled.GetDemangledName(symbol->GetLanguage()); - if (entry.cstring) { - m_name_to_index.Append(entry); + if (ConstString name = mangled.GetDemangledName(symbol->GetLanguage())) { + m_name_to_index.Append(name, value); if (symbol->ContainsLinkerAnnotations()) { // If the symbol has linker annotations, also add the version without // the annotations. - entry.cstring = ConstString(m_objfile->StripLinkerSymbolAnnotations( - entry.cstring.GetStringRef())); - m_name_to_index.Append(entry); + name = ConstString( + m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef())); + m_name_to_index.Append(name, value); } - } - // If the demangled name turns out to be an ObjC name, and is a category - // name, add the version without categories to the index too. - ObjCLanguage::MethodName objc_method(entry.cstring.GetStringRef(), true); - if (objc_method.IsValid(true)) { - entry.cstring = objc_method.GetSelector(); - m_selector_to_index.Append(entry); + // If the demangled name turns out to be an ObjC name, and is a category + // name, add the version without categories to the index too. + ObjCLanguage::MethodName objc_method(name.GetStringRef(), true); + if (objc_method.IsValid(true)) { + m_selector_to_index.Append(objc_method.GetSelector(), value); - ConstString objc_method_no_category( - objc_method.GetFullNameWithoutCategory(true)); - if (objc_method_no_category) { - entry.cstring = objc_method_no_category; - m_name_to_index.Append(entry); + if (ConstString objc_method_no_category = + objc_method.GetFullNameWithoutCategory(true)) + m_name_to_index.Append(objc_method_no_category, value); } } } @@ -372,7 +342,7 @@ } void Symtab::RegisterMangledNameEntry( - NameToIndexMap::Entry &entry, std::set<const char *> &class_contexts, + uint32_t value, std::set<const char *> &class_contexts, std::vector<std::pair<NameToIndexMap::Entry, const char *>> &backlog, RichManglingContext &rmc) { // Only register functions that have a base name. @@ -382,7 +352,7 @@ return; // The base name will be our entry's name. - entry.cstring = ConstString(base_name); + NameToIndexMap::Entry entry(ConstString(base_name), value); rmc.ParseFunctionDeclContextName(); llvm::StringRef decl_context = rmc.GetBufferRef(); @@ -450,24 +420,21 @@ std::lock_guard<std::recursive_mutex> guard(m_mutex); // Create the name index vector to be able to quickly search by name - NameToIndexMap::Entry entry; const size_t num_indexes = indexes.size(); for (size_t i = 0; i < num_indexes; ++i) { - entry.value = indexes[i]; + uint32_t value = indexes[i]; assert(i < m_symbols.size()); - const Symbol *symbol = &m_symbols[entry.value]; + const Symbol *symbol = &m_symbols[value]; const Mangled &mangled = symbol->GetMangled(); if (add_demangled) { - entry.cstring = mangled.GetDemangledName(symbol->GetLanguage()); - if (entry.cstring) - name_to_index_map.Append(entry); + if (ConstString name = mangled.GetDemangledName(symbol->GetLanguage())) + name_to_index_map.Append(name, value); } if (add_mangled) { - entry.cstring = mangled.GetMangledName(); - if (entry.cstring) - name_to_index_map.Append(entry); + if (ConstString name = mangled.GetMangledName()) + name_to_index_map.Append(name, value); } } } @@ -626,7 +593,7 @@ } } -uint32_t Symtab::AppendSymbolIndexesWithName(const ConstString &symbol_name, +uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name, std::vector<uint32_t> &indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -641,7 +608,7 @@ return 0; } -uint32_t Symtab::AppendSymbolIndexesWithName(const ConstString &symbol_name, +uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name, Debug symbol_debug_type, Visibility symbol_visibility, std::vector<uint32_t> &indexes) { @@ -668,7 +635,7 @@ } uint32_t -Symtab::AppendSymbolIndexesWithNameAndType(const ConstString &symbol_name, +Symtab::AppendSymbolIndexesWithNameAndType(ConstString symbol_name, SymbolType symbol_type, std::vector<uint32_t> &indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -687,7 +654,7 @@ } uint32_t Symtab::AppendSymbolIndexesWithNameAndType( - const ConstString &symbol_name, SymbolType symbol_type, + ConstString symbol_name, SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility, std::vector<uint32_t> &indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -772,7 +739,7 @@ } size_t -Symtab::FindAllSymbolsWithNameAndType(const ConstString &name, +Symtab::FindAllSymbolsWithNameAndType(ConstString name, SymbolType symbol_type, std::vector<uint32_t> &symbol_indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -793,7 +760,7 @@ } size_t Symtab::FindAllSymbolsWithNameAndType( - const ConstString &name, SymbolType symbol_type, Debug symbol_debug_type, + ConstString name, SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility, std::vector<uint32_t> &symbol_indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -824,7 +791,7 @@ return symbol_indexes.size(); } -Symbol *Symtab::FindFirstSymbolWithNameAndType(const ConstString &name, +Symbol *Symtab::FindFirstSymbolWithNameAndType(ConstString name, SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility) { @@ -929,8 +896,14 @@ for (size_t i = 0; i < num_entries; i++) { FileRangeToIndexMap::Entry *entry = m_file_addr_to_index.GetMutableEntryAtIndex(i); - if (entry->GetByteSize() == 0) { - addr_t curr_base_addr = entry->GetRangeBase(); + if (entry->GetByteSize() > 0) + continue; + addr_t curr_base_addr = entry->GetRangeBase(); + // Symbols with non-zero size will show after zero-sized symbols on the + // same address. So do not set size of a non-last zero-sized symbol. + if (i == num_entries - 1 || + m_file_addr_to_index.GetMutableEntryAtIndex(i + 1) + ->GetRangeBase() != curr_base_addr) { const RangeVector<addr_t, addr_t>::Entry *containing_section = section_ranges.FindEntryThatContains(curr_base_addr); @@ -1051,7 +1024,7 @@ } } -size_t Symtab::FindFunctionSymbols(const ConstString &name, +size_t Symtab::FindFunctionSymbols(ConstString name, uint32_t name_type_mask, SymbolContextList &sc_list) { size_t count = 0; @@ -1152,5 +1125,5 @@ return symbol; } } - return NULL; + return nullptr; }
diff --git a/src/llvm-project/lldb/source/Symbol/Type.cpp b/src/llvm-project/lldb/source/Symbol/Type.cpp index 15589b8..4ee8330 100644 --- a/src/llvm-project/lldb/source/Symbol/Type.cpp +++ b/src/llvm-project/lldb/source/Symbol/Type.cpp
@@ -1,9 +1,8 @@ //===-- Type.cpp ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -108,7 +107,7 @@ } Type::Type(lldb::user_id_t uid, SymbolFile *symbol_file, - const ConstString &name, uint64_t byte_size, + ConstString name, llvm::Optional<uint64_t> byte_size, SymbolContextScope *context, user_id_t encoding_uid, EncodingDataType encoding_uid_type, const Declaration &decl, const CompilerType &compiler_type, @@ -116,7 +115,14 @@ : std::enable_shared_from_this<Type>(), UserID(uid), m_name(name), m_symbol_file(symbol_file), m_context(context), m_encoding_type(nullptr), m_encoding_uid(encoding_uid), m_encoding_uid_type(encoding_uid_type), - m_byte_size(byte_size), m_decl(decl), m_compiler_type(compiler_type) { + m_decl(decl), m_compiler_type(compiler_type) { + if (byte_size) { + m_byte_size = *byte_size; + m_byte_size_has_value = true; + } else { + m_byte_size = 0; + m_byte_size_has_value = false; + } m_flags.compiler_type_resolve_state = (compiler_type ? compiler_type_resolve_state : eResolveStateUnresolved); m_flags.is_complete_objc_class = false; @@ -126,32 +132,19 @@ : std::enable_shared_from_this<Type>(), UserID(0), m_name("<INVALID TYPE>"), m_symbol_file(nullptr), m_context(nullptr), m_encoding_type(nullptr), m_encoding_uid(LLDB_INVALID_UID), m_encoding_uid_type(eEncodingInvalid), - m_byte_size(0), m_decl(), m_compiler_type() { + m_byte_size(0), m_byte_size_has_value(false), m_decl(), + m_compiler_type() { m_flags.compiler_type_resolve_state = eResolveStateUnresolved; m_flags.is_complete_objc_class = false; } -Type::Type(const Type &rhs) - : std::enable_shared_from_this<Type>(rhs), UserID(rhs), m_name(rhs.m_name), - m_symbol_file(rhs.m_symbol_file), m_context(rhs.m_context), - m_encoding_type(rhs.m_encoding_type), m_encoding_uid(rhs.m_encoding_uid), - m_encoding_uid_type(rhs.m_encoding_uid_type), - m_byte_size(rhs.m_byte_size), m_decl(rhs.m_decl), - m_compiler_type(rhs.m_compiler_type), m_flags(rhs.m_flags) {} - -const Type &Type::operator=(const Type &rhs) { - if (this != &rhs) { - } - return *this; -} - void Type::GetDescription(Stream *s, lldb::DescriptionLevel level, bool show_name) { *s << "id = " << (const UserID &)*this; // Call the name accessor to make sure we resolve the type name if (show_name) { - const ConstString &type_name = GetName(); + ConstString type_name = GetName(); if (type_name) { *s << ", name = \"" << type_name << '"'; ConstString qualified_type_name(GetQualifiedName()); @@ -214,7 +207,7 @@ if (m_name) *s << ", name = \"" << m_name << "\""; - if (m_byte_size != 0) + if (m_byte_size_has_value) s->Printf(", size = %" PRIu64, m_byte_size); if (show_context && m_context != nullptr) { @@ -270,7 +263,7 @@ s->EOL(); } -const ConstString &Type::GetName() { +ConstString Type::GetName() { if (!m_name) m_name = GetForwardCompilerType().GetConstTypeName(); return m_name; @@ -293,7 +286,7 @@ GetForwardCompilerType().DumpValue( exe_ctx, s, format == lldb::eFormatDefault ? GetFormat() : format, data, - data_byte_offset, GetByteSize(), + data_byte_offset, GetByteSize().getValueOr(0), 0, // Bitfield bit size 0, // Bitfield bit offset show_types, show_summary, verbose, 0); @@ -306,36 +299,46 @@ return m_encoding_type; } -uint64_t Type::GetByteSize() { - if (m_byte_size == 0) { - switch (m_encoding_uid_type) { - case eEncodingInvalid: - case eEncodingIsSyntheticUID: - break; - case eEncodingIsUID: - case eEncodingIsConstUID: - case eEncodingIsRestrictUID: - case eEncodingIsVolatileUID: - case eEncodingIsTypedefUID: { - Type *encoding_type = GetEncodingType(); - if (encoding_type) - m_byte_size = encoding_type->GetByteSize(); - if (m_byte_size == 0) - if (llvm::Optional<uint64_t> size = - GetLayoutCompilerType().GetByteSize(nullptr)) - m_byte_size = *size; - } break; +llvm::Optional<uint64_t> Type::GetByteSize() { + if (m_byte_size_has_value) + return m_byte_size; + + switch (m_encoding_uid_type) { + case eEncodingInvalid: + case eEncodingIsSyntheticUID: + break; + case eEncodingIsUID: + case eEncodingIsConstUID: + case eEncodingIsRestrictUID: + case eEncodingIsVolatileUID: + case eEncodingIsTypedefUID: { + Type *encoding_type = GetEncodingType(); + if (encoding_type) + if (llvm::Optional<uint64_t> size = encoding_type->GetByteSize()) { + m_byte_size = *size; + m_byte_size_has_value = true; + return m_byte_size; + } + + if (llvm::Optional<uint64_t> size = + GetLayoutCompilerType().GetByteSize(nullptr)) { + m_byte_size = *size; + m_byte_size_has_value = true; + return m_byte_size; + } + } break; // If we are a pointer or reference, then this is just a pointer size; case eEncodingIsPointerUID: case eEncodingIsLValueReferenceUID: case eEncodingIsRValueReferenceUID: { - if (ArchSpec arch = m_symbol_file->GetObjectFile()->GetArchitecture()) + if (ArchSpec arch = m_symbol_file->GetObjectFile()->GetArchitecture()) { m_byte_size = arch.GetAddressByteSize(); + m_byte_size_has_value = true; + } } break; - } } - return m_byte_size; + return {}; } uint32_t Type::GetNumChildren(bool omit_empty_base_classes) { @@ -389,7 +392,7 @@ return false; } - const uint64_t byte_size = GetByteSize(); + const uint64_t byte_size = GetByteSize().getValueOr(0); if (data.GetByteSize() < byte_size) { lldb::DataBufferSP data_sp(new DataBufferHeap(byte_size, '\0')); data.SetData(data_sp); @@ -678,39 +681,21 @@ return ModuleSP(); } -TypeAndOrName::TypeAndOrName() : m_type_pair(), m_type_name() {} - -TypeAndOrName::TypeAndOrName(TypeSP &in_type_sp) : m_type_pair(in_type_sp) { - if (in_type_sp) +TypeAndOrName::TypeAndOrName(TypeSP &in_type_sp) { + if (in_type_sp) { + m_compiler_type = in_type_sp->GetForwardCompilerType(); m_type_name = in_type_sp->GetName(); + } } TypeAndOrName::TypeAndOrName(const char *in_type_str) : m_type_name(in_type_str) {} -TypeAndOrName::TypeAndOrName(const TypeAndOrName &rhs) - : m_type_pair(rhs.m_type_pair), m_type_name(rhs.m_type_name) {} - TypeAndOrName::TypeAndOrName(ConstString &in_type_const_string) : m_type_name(in_type_const_string) {} -TypeAndOrName::TypeAndOrName(const CompilerType &type) - : m_type_pair(type) -{ - if (m_type_pair) - m_type_name = m_type_pair.GetName(); -} - -TypeAndOrName &TypeAndOrName::operator=(const TypeAndOrName &rhs) { - if (this != &rhs) { - m_type_name = rhs.m_type_name; - m_type_pair = rhs.m_type_pair; - } - return *this; -} - bool TypeAndOrName::operator==(const TypeAndOrName &other) const { - if (m_type_pair != other.m_type_pair) + if (m_compiler_type != other.m_compiler_type) return false; if (m_type_name != other.m_type_name) return false; @@ -724,12 +709,12 @@ ConstString TypeAndOrName::GetName() const { if (m_type_name) return m_type_name; - if (m_type_pair) - return m_type_pair.GetName(); + if (m_compiler_type) + return m_compiler_type.GetTypeName(); return ConstString("<invalid>"); } -void TypeAndOrName::SetName(const ConstString &type_name) { +void TypeAndOrName::SetName(ConstString type_name) { m_type_name = type_name; } @@ -738,42 +723,34 @@ } void TypeAndOrName::SetTypeSP(lldb::TypeSP type_sp) { - m_type_pair.SetType(type_sp); - if (m_type_pair) - m_type_name = m_type_pair.GetName(); + if (type_sp) { + m_compiler_type = type_sp->GetForwardCompilerType(); + m_type_name = type_sp->GetName(); + } else + Clear(); } void TypeAndOrName::SetCompilerType(CompilerType compiler_type) { - m_type_pair.SetType(compiler_type); - if (m_type_pair) - m_type_name = m_type_pair.GetName(); + m_compiler_type = compiler_type; + if (m_compiler_type) + m_type_name = m_compiler_type.GetTypeName(); } bool TypeAndOrName::IsEmpty() const { - return !((bool)m_type_name || (bool)m_type_pair); + return !((bool)m_type_name || (bool)m_compiler_type); } void TypeAndOrName::Clear() { m_type_name.Clear(); - m_type_pair.Clear(); + m_compiler_type.Clear(); } bool TypeAndOrName::HasName() const { return (bool)m_type_name; } -bool TypeAndOrName::HasTypeSP() const { - return m_type_pair.GetTypeSP().get() != nullptr; -} - bool TypeAndOrName::HasCompilerType() const { - return m_type_pair.GetCompilerType().IsValid(); + return m_compiler_type.IsValid(); } -TypeImpl::TypeImpl() : m_module_wp(), m_static_type(), m_dynamic_type() {} - -TypeImpl::TypeImpl(const TypeImpl &rhs) - : m_module_wp(rhs.m_module_wp), m_static_type(rhs.m_static_type), - m_dynamic_type(rhs.m_dynamic_type) {} - TypeImpl::TypeImpl(const lldb::TypeSP &type_sp) : m_module_wp(), m_static_type(), m_dynamic_type() { SetType(type_sp); @@ -785,7 +762,7 @@ } TypeImpl::TypeImpl(const lldb::TypeSP &type_sp, const CompilerType &dynamic) - : m_module_wp(), m_static_type(type_sp), m_dynamic_type(dynamic) { + : m_module_wp(), m_static_type(), m_dynamic_type(dynamic) { SetType(type_sp, dynamic); } @@ -795,22 +772,19 @@ SetType(static_type, dynamic_type); } -TypeImpl::TypeImpl(const TypePair &pair, const CompilerType &dynamic) - : m_module_wp(), m_static_type(), m_dynamic_type() { - SetType(pair, dynamic); -} - void TypeImpl::SetType(const lldb::TypeSP &type_sp) { - m_static_type.SetType(type_sp); - if (type_sp) + if (type_sp) { + m_static_type = type_sp->GetForwardCompilerType(); m_module_wp = type_sp->GetModule(); - else + } else { + m_static_type.Clear(); m_module_wp = lldb::ModuleWP(); + } } void TypeImpl::SetType(const CompilerType &compiler_type) { m_module_wp = lldb::ModuleWP(); - m_static_type.SetType(compiler_type); + m_static_type = compiler_type; } void TypeImpl::SetType(const lldb::TypeSP &type_sp, @@ -822,25 +796,10 @@ void TypeImpl::SetType(const CompilerType &compiler_type, const CompilerType &dynamic) { m_module_wp = lldb::ModuleWP(); - m_static_type.SetType(compiler_type); + m_static_type = compiler_type; m_dynamic_type = dynamic; } -void TypeImpl::SetType(const TypePair &pair, const CompilerType &dynamic) { - m_module_wp = pair.GetModule(); - m_static_type = pair; - m_dynamic_type = dynamic; -} - -TypeImpl &TypeImpl::operator=(const TypeImpl &rhs) { - if (rhs != *this) { - m_module_wp = rhs.m_module_wp; - m_static_type = rhs.m_static_type; - m_dynamic_type = rhs.m_dynamic_type; - } - return *this; -} - bool TypeImpl::CheckModule(lldb::ModuleSP &module_sp) const { // Check if we have a module for this type. If we do and the shared pointer // is can be successfully initialized with m_module_wp, return true. Else @@ -899,7 +858,7 @@ if (CheckModule(module_sp)) { if (m_dynamic_type) return m_dynamic_type.GetTypeName(); - return m_static_type.GetName(); + return m_static_type.GetTypeName(); } return ConstString(); } @@ -942,10 +901,10 @@ ModuleSP module_sp; if (CheckModule(module_sp)) { if (m_dynamic_type.IsValid()) { - return TypeImpl(m_static_type.GetReferenceType(), + return TypeImpl(m_static_type.GetLValueReferenceType(), m_dynamic_type.GetLValueReferenceType()); } - return TypeImpl(m_static_type.GetReferenceType()); + return TypeImpl(m_static_type.GetLValueReferenceType()); } return TypeImpl(); } @@ -966,10 +925,10 @@ ModuleSP module_sp; if (CheckModule(module_sp)) { if (m_dynamic_type.IsValid()) { - return TypeImpl(m_static_type.GetDereferencedType(), + return TypeImpl(m_static_type.GetNonReferenceType(), m_dynamic_type.GetNonReferenceType()); } - return TypeImpl(m_static_type.GetDereferencedType()); + return TypeImpl(m_static_type.GetNonReferenceType()); } return TypeImpl(); } @@ -978,10 +937,10 @@ ModuleSP module_sp; if (CheckModule(module_sp)) { if (m_dynamic_type.IsValid()) { - return TypeImpl(m_static_type.GetUnqualifiedType(), + return TypeImpl(m_static_type.GetFullyUnqualifiedType(), m_dynamic_type.GetFullyUnqualifiedType()); } - return TypeImpl(m_static_type.GetUnqualifiedType()); + return TypeImpl(m_static_type.GetFullyUnqualifiedType()); } return TypeImpl(); } @@ -1005,7 +964,7 @@ if (m_dynamic_type.IsValid()) return m_dynamic_type; } - return m_static_type.GetCompilerType(); + return m_static_type; } return CompilerType(); } @@ -1017,9 +976,9 @@ if (m_dynamic_type.IsValid()) return m_dynamic_type.GetTypeSystem(); } - return m_static_type.GetCompilerType().GetTypeSystem(); + return m_static_type.GetTypeSystem(); } - return NULL; + return nullptr; } bool TypeImpl::GetDescription(lldb_private::Stream &strm, @@ -1031,7 +990,7 @@ m_dynamic_type.DumpTypeDescription(&strm); strm.Printf("\nStatic:\n"); } - m_static_type.GetCompilerType().DumpTypeDescription(&strm); + m_static_type.DumpTypeDescription(&strm); } else { strm.PutCString("Invalid TypeImpl module for type has been deleted\n"); } @@ -1099,7 +1058,7 @@ } TypeEnumMemberImpl::TypeEnumMemberImpl(const lldb::TypeImplSP &integer_type_sp, - const ConstString &name, + ConstString name, const llvm::APSInt &value) : m_integer_type_sp(integer_type_sp), m_name(name), m_value(value), m_valid((bool)name && (bool)integer_type_sp)
diff --git a/src/llvm-project/lldb/source/Symbol/TypeList.cpp b/src/llvm-project/lldb/source/Symbol/TypeList.cpp index 26a646e..1813e8e 100644 --- a/src/llvm-project/lldb/source/Symbol/TypeList.cpp +++ b/src/llvm-project/lldb/source/Symbol/TypeList.cpp
@@ -1,9 +1,8 @@ //===-- TypeList.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,9 +21,7 @@ TypeList::TypeList() : m_types() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- TypeList::~TypeList() {} void TypeList::Insert(const TypeSP &type_sp) { @@ -34,9 +31,7 @@ m_types.push_back(type_sp); } -//---------------------------------------------------------------------- // Find a base type by its unique ID. -//---------------------------------------------------------------------- // TypeSP // TypeList::FindType(lldb::user_id_t uid) //{ @@ -46,11 +41,9 @@ // return TypeSP(); //} -//---------------------------------------------------------------------- // Find a type by name. -//---------------------------------------------------------------------- // TypeList -// TypeList::FindTypes (const ConstString &name) +// TypeList::FindTypes (ConstString name) //{ // // Do we ever need to make a lookup by name map? Here we are doing // // a linear search which isn't going to be fast.
diff --git a/src/llvm-project/lldb/source/Symbol/TypeMap.cpp b/src/llvm-project/lldb/source/Symbol/TypeMap.cpp index 337278c..bc6e272 100644 --- a/src/llvm-project/lldb/source/Symbol/TypeMap.cpp +++ b/src/llvm-project/lldb/source/Symbol/TypeMap.cpp
@@ -1,9 +1,8 @@ //===-- TypeMap.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,9 +34,7 @@ TypeMap::TypeMap() : m_types() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- TypeMap::~TypeMap() {} void TypeMap::Insert(const TypeSP &type_sp) { @@ -62,9 +59,7 @@ return true; } -//---------------------------------------------------------------------- // Find a base type by its unique ID. -//---------------------------------------------------------------------- // TypeSP // TypeMap::FindType(lldb::user_id_t uid) //{ @@ -74,11 +69,9 @@ // return TypeSP(); //} -//---------------------------------------------------------------------- // Find a type by name. -//---------------------------------------------------------------------- // TypeMap -// TypeMap::FindTypes (const ConstString &name) +// TypeMap::FindTypes (ConstString name) //{ // // Do we ever need to make a lookup by name map? Here we are doing // // a linear search which isn't going to be fast.
diff --git a/src/llvm-project/lldb/source/Symbol/TypeSystem.cpp b/src/llvm-project/lldb/source/Symbol/TypeSystem.cpp index 91d347e..fb9c8e7 100644 --- a/src/llvm-project/lldb/source/Symbol/TypeSystem.cpp +++ b/src/llvm-project/lldb/source/Symbol/TypeSystem.cpp
@@ -1,9 +1,8 @@ //===-- TypeSystem.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -93,7 +92,7 @@ return CompilerType(); } -CompilerType TypeSystem::GetBuiltinTypeByName(const ConstString &name) { +CompilerType TypeSystem::GetBuiltinTypeByName(ConstString name) { return CompilerType(); }
diff --git a/src/llvm-project/lldb/source/Symbol/UnwindPlan.cpp b/src/llvm-project/lldb/source/Symbol/UnwindPlan.cpp index 0f8d9bf..774f9cb 100644 --- a/src/llvm-project/lldb/source/Symbol/UnwindPlan.cpp +++ b/src/llvm-project/lldb/source/Symbol/UnwindPlan.cpp
@@ -1,16 +1,17 @@ //===-- UnwindPlan.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Symbol/UnwindPlan.h" +#include "lldb/Expression/DWARFExpression.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" +#include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Log.h" @@ -65,6 +66,30 @@ m_location.expr.length = len; } +static llvm::Optional<std::pair<lldb::ByteOrder, uint32_t>> +GetByteOrderAndAddrSize(Thread *thread) { + if (!thread) + return llvm::None; + ProcessSP process_sp = thread->GetProcess(); + if (!process_sp) + return llvm::None; + ArchSpec arch = process_sp->GetTarget().GetArchitecture(); + return std::make_pair(arch.GetByteOrder(), arch.GetAddressByteSize()); +} + +static void DumpDWARFExpr(Stream &s, llvm::ArrayRef<uint8_t> expr, Thread *thread) { + if (auto order_and_width = GetByteOrderAndAddrSize(thread)) { + DataExtractor extractor(expr.data(), expr.size(), order_and_width->first, + order_and_width->second); + if (!DWARFExpression::PrintDWARFExpression(s, extractor, + order_and_width->second, + /*dwarf_ref_size*/ 4, + /*location_expression*/ false)) + s.PutCString("invalid-dwarf-expr"); + } else + s.PutCString("dwarf-expr"); +} + void UnwindPlan::Row::RegisterLocation::Dump(Stream &s, const UnwindPlan *unwind_plan, const UnwindPlan::Row *row, @@ -121,9 +146,12 @@ case isDWARFExpression: { s.PutChar('='); if (m_type == atDWARFExpression) - s.PutCString("[dwarf-expr]"); - else - s.PutCString("dwarf-expr"); + s.PutChar('['); + DumpDWARFExpr( + s, llvm::makeArrayRef(m_location.expr.opcodes, m_location.expr.length), + thread); + if (m_type == atDWARFExpression) + s.PutChar(']'); } break; } } @@ -173,7 +201,9 @@ s.PutChar(']'); break; case isDWARFExpression: - s.PutCString("dwarf-expr"); + DumpDWARFExpr(s, + llvm::makeArrayRef(m_value.expr.opcodes, m_value.expr.length), + thread); break; default: s.PutCString("unspecified");
diff --git a/src/llvm-project/lldb/source/Symbol/UnwindTable.cpp b/src/llvm-project/lldb/source/Symbol/UnwindTable.cpp index 4f0b875..a8f451d 100644 --- a/src/llvm-project/lldb/source/Symbol/UnwindTable.cpp +++ b/src/llvm-project/lldb/source/Symbol/UnwindTable.cpp
@@ -1,9 +1,8 @@ //===-- UnwindTable.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,6 +18,7 @@ #include "lldb/Symbol/FuncUnwinders.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolContext.h" +#include "lldb/Symbol/SymbolVendor.h" // There is one UnwindTable object per ObjectFile. It contains a list of Unwind // objects -- one per function, populated lazily -- for the ObjectFile. Each @@ -27,8 +27,8 @@ using namespace lldb; using namespace lldb_private; -UnwindTable::UnwindTable(ObjectFile &objfile) - : m_object_file(objfile), m_unwinds(), m_initialized(false), m_mutex(), +UnwindTable::UnwindTable(Module &module) + : m_module(module), m_unwinds(), m_initialized(false), m_mutex(), m_eh_frame_up(), m_compact_unwind_up(), m_arm_unwind_up() {} // We can't do some of this initialization when the ObjectFile is running its @@ -43,33 +43,36 @@ if (m_initialized) // check again once we've acquired the lock return; m_initialized = true; + ObjectFile *object_file = m_module.GetObjectFile(); + if (!object_file) + return; - SectionList *sl = m_object_file.GetSectionList(); + SectionList *sl = m_module.GetSectionList(); if (!sl) return; SectionSP sect = sl->FindSectionByType(eSectionTypeEHFrame, true); if (sect.get()) { m_eh_frame_up.reset( - new DWARFCallFrameInfo(m_object_file, sect, DWARFCallFrameInfo::EH)); + new DWARFCallFrameInfo(*object_file, sect, DWARFCallFrameInfo::EH)); } sect = sl->FindSectionByType(eSectionTypeDWARFDebugFrame, true); if (sect) { m_debug_frame_up.reset( - new DWARFCallFrameInfo(m_object_file, sect, DWARFCallFrameInfo::DWARF)); + new DWARFCallFrameInfo(*object_file, sect, DWARFCallFrameInfo::DWARF)); } sect = sl->FindSectionByType(eSectionTypeCompactUnwind, true); if (sect) { - m_compact_unwind_up.reset(new CompactUnwindInfo(m_object_file, sect)); + m_compact_unwind_up.reset(new CompactUnwindInfo(*object_file, sect)); } sect = sl->FindSectionByType(eSectionTypeARMexidx, true); if (sect) { SectionSP sect_extab = sl->FindSectionByType(eSectionTypeARMextab, true); if (sect_extab.get()) { - m_arm_unwind_up.reset(new ArmUnwindInfo(m_object_file, sect, sect_extab)); + m_arm_unwind_up.reset(new ArmUnwindInfo(*object_file, sect, sect_extab)); } } } @@ -149,8 +152,7 @@ void UnwindTable::Dump(Stream &s) { std::lock_guard<std::mutex> guard(m_mutex); - s.Printf("UnwindTable for '%s':\n", - m_object_file.GetFileSpec().GetPath().c_str()); + s.Format("UnwindTable for '{0}':\n", m_module.GetFileSpec()); const_iterator begin = m_unwinds.begin(); const_iterator end = m_unwinds.end(); for (const_iterator pos = begin; pos != end; ++pos) { @@ -180,10 +182,16 @@ return m_arm_unwind_up.get(); } -ArchSpec UnwindTable::GetArchitecture() { - return m_object_file.GetArchitecture(); +SymbolFile *UnwindTable::GetSymbolFile() { + if (SymbolVendor *vendor = m_module.GetSymbolVendor()) + return vendor->GetSymbolFile(); + return nullptr; } +ArchSpec UnwindTable::GetArchitecture() { return m_module.GetArchitecture(); } + bool UnwindTable::GetAllowAssemblyEmulationUnwindPlans() { - return m_object_file.AllowAssemblyEmulationUnwindPlans(); + if (ObjectFile *object_file = m_module.GetObjectFile()) + return object_file->AllowAssemblyEmulationUnwindPlans(); + return false; }
diff --git a/src/llvm-project/lldb/source/Symbol/Variable.cpp b/src/llvm-project/lldb/source/Symbol/Variable.cpp index ffed48a..29a7a51 100644 --- a/src/llvm-project/lldb/source/Symbol/Variable.cpp +++ b/src/llvm-project/lldb/source/Symbol/Variable.cpp
@@ -1,9 +1,8 @@ //===-- Variable.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -36,9 +35,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Variable constructor -//---------------------------------------------------------------------- Variable::Variable( lldb::user_id_t uid, const char *name, const char *mangled, // The mangled or fully qualified name of the variable. @@ -53,9 +50,7 @@ m_artificial(artificial), m_loc_is_const_data(false), m_static_member(static_member) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- Variable::~Variable() {} lldb::LanguageType Variable::GetLanguage() const { @@ -75,7 +70,7 @@ ConstString Variable::GetUnqualifiedName() const { return m_name; } -bool Variable::NameMatches(const ConstString &name) const { +bool Variable::NameMatches(ConstString name) const { if (m_name == name) return true; SymbolContext variable_sc;
diff --git a/src/llvm-project/lldb/source/Symbol/VariableList.cpp b/src/llvm-project/lldb/source/Symbol/VariableList.cpp index e7a482e..5131247 100644 --- a/src/llvm-project/lldb/source/Symbol/VariableList.cpp +++ b/src/llvm-project/lldb/source/Symbol/VariableList.cpp
@@ -1,9 +1,8 @@ //===-- VariableList.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,14 +16,10 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // VariableList constructor -//---------------------------------------------------------------------- VariableList::VariableList() : m_variables() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- VariableList::~VariableList() {} void VariableList::AddVariable(const VariableSP &var_sp) { @@ -74,7 +69,7 @@ return UINT32_MAX; } -VariableSP VariableList::FindVariable(const ConstString &name, +VariableSP VariableList::FindVariable(ConstString name, bool include_static_members) { VariableSP var_sp; iterator pos, end = m_variables.end(); @@ -89,7 +84,7 @@ return var_sp; } -VariableSP VariableList::FindVariable(const ConstString &name, +VariableSP VariableList::FindVariable(ConstString name, lldb::ValueType value_type, bool include_static_members) { VariableSP var_sp;
diff --git a/src/llvm-project/lldb/source/Symbol/VerifyDecl.cpp b/src/llvm-project/lldb/source/Symbol/VerifyDecl.cpp index 96ed47a..1873d3a 100644 --- a/src/llvm-project/lldb/source/Symbol/VerifyDecl.cpp +++ b/src/llvm-project/lldb/source/Symbol/VerifyDecl.cpp
@@ -1,13 +1,15 @@ //===-- VerifyDecl.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Symbol/VerifyDecl.h" #include "clang/AST/DeclBase.h" -void lldb_private::VerifyDecl(clang::Decl *decl) { decl->getAccess(); } +void lldb_private::VerifyDecl(clang::Decl *decl) { + assert(decl && "VerifyDecl called with nullptr?"); + decl->getAccess(); +}
diff --git a/src/llvm-project/lldb/source/Target/ABI.cpp b/src/llvm-project/lldb/source/Target/ABI.cpp index 96e09b7..28cd9ae 100644 --- a/src/llvm-project/lldb/source/Target/ABI.cpp +++ b/src/llvm-project/lldb/source/Target/ABI.cpp
@@ -1,17 +1,16 @@ //===-- ABI.cpp -------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/ABI.h" -#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Value.h" #include "lldb/Core/ValueObjectConstResult.h" +#include "lldb/Expression/ExpressionVariable.h" #include "lldb/Symbol/CompilerType.h" #include "lldb/Symbol/TypeSystem.h" #include "lldb/Target/Target.h" @@ -40,7 +39,7 @@ ABI::~ABI() = default; -bool ABI::GetRegisterInfoByName(const ConstString &name, RegisterInfo &info) { +bool ABI::GetRegisterInfoByName(ConstString name, RegisterInfo &info) { uint32_t count = 0; const RegisterInfo *register_info_array = GetRegisterInfoArray(count); if (register_info_array) { @@ -125,11 +124,11 @@ return_valobj_sp = const_valobj_sp; - ExpressionVariableSP clang_expr_variable_sp( + ExpressionVariableSP expr_variable_sp( persistent_expression_state->CreatePersistentVariable( return_valobj_sp)); - assert(clang_expr_variable_sp); + assert(expr_variable_sp); // Set flags and live data as appropriate @@ -142,21 +141,21 @@ break; case Value::eValueTypeScalar: case Value::eValueTypeVector: - clang_expr_variable_sp->m_flags |= - ClangExpressionVariable::EVIsFreezeDried; - clang_expr_variable_sp->m_flags |= - ClangExpressionVariable::EVIsLLDBAllocated; - clang_expr_variable_sp->m_flags |= - ClangExpressionVariable::EVNeedsAllocation; + expr_variable_sp->m_flags |= + ExpressionVariable::EVIsFreezeDried; + expr_variable_sp->m_flags |= + ExpressionVariable::EVIsLLDBAllocated; + expr_variable_sp->m_flags |= + ExpressionVariable::EVNeedsAllocation; break; case Value::eValueTypeLoadAddress: - clang_expr_variable_sp->m_live_sp = live_valobj_sp; - clang_expr_variable_sp->m_flags |= - ClangExpressionVariable::EVIsProgramReference; + expr_variable_sp->m_live_sp = live_valobj_sp; + expr_variable_sp->m_flags |= + ExpressionVariable::EVIsProgramReference; break; } - return_valobj_sp = clang_expr_variable_sp->GetValueObject(); + return_valobj_sp = expr_variable_sp->GetValueObject(); } return return_valobj_sp; }
diff --git a/src/llvm-project/lldb/source/Target/CMakeLists.txt b/src/llvm-project/lldb/source/Target/CMakeLists.txt index 265b3a8..2f59a48 100644 --- a/src/llvm-project/lldb/source/Target/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Target/CMakeLists.txt
@@ -1,8 +1,6 @@ add_lldb_library(lldbTarget ABI.cpp - CPPLanguageRuntime.cpp ExecutionContext.cpp - FileAction.cpp JITLoader.cpp JITLoaderList.cpp InstrumentationRuntime.cpp @@ -12,18 +10,16 @@ Memory.cpp MemoryHistory.cpp ModuleCache.cpp - ObjCLanguageRuntime.cpp OperatingSystem.cpp PathMappingList.cpp Platform.cpp Process.cpp - ProcessInfo.cpp - ProcessLaunchInfo.cpp Queue.cpp QueueItem.cpp QueueList.cpp RegisterContext.cpp RegisterNumber.cpp + RemoteAwarePlatform.cpp SectionLoadHistory.cpp SectionLoadList.cpp StackFrame.cpp @@ -69,7 +65,6 @@ lldbSymbol lldbUtility lldbPluginExpressionParserClang - lldbPluginObjCLanguage lldbPluginProcessUtility LINK_COMPONENTS
diff --git a/src/llvm-project/lldb/source/Target/ExecutionContext.cpp b/src/llvm-project/lldb/source/Target/ExecutionContext.cpp index 7f1f033..7732737 100644 --- a/src/llvm-project/lldb/source/Target/ExecutionContext.cpp +++ b/src/llvm-project/lldb/source/Target/ExecutionContext.cpp
@@ -1,9 +1,8 @@ //===-- ExecutionContext.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -225,30 +224,22 @@ } Target &ExecutionContext::GetTargetRef() const { -#if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE) assert(m_target_sp); -#endif return *m_target_sp; } Process &ExecutionContext::GetProcessRef() const { -#if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE) assert(m_process_sp); -#endif return *m_process_sp; } Thread &ExecutionContext::GetThreadRef() const { -#if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE) assert(m_thread_sp); -#endif return *m_thread_sp; } StackFrame &ExecutionContext::GetFrameRef() const { -#if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE) assert(m_frame_sp); -#endif return *m_frame_sp; }
diff --git a/src/llvm-project/lldb/source/Target/InstrumentationRuntime.cpp b/src/llvm-project/lldb/source/Target/InstrumentationRuntime.cpp index e948d43..4c2eb06 100644 --- a/src/llvm-project/lldb/source/Target/InstrumentationRuntime.cpp +++ b/src/llvm-project/lldb/source/Target/InstrumentationRuntime.cpp
@@ -1,9 +1,8 @@ //===-- InstrumentationRuntime.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===---------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/InstrumentationRuntimeStopInfo.cpp b/src/llvm-project/lldb/source/Target/InstrumentationRuntimeStopInfo.cpp index dbbd4f4..f2767ff 100644 --- a/src/llvm-project/lldb/source/Target/InstrumentationRuntimeStopInfo.cpp +++ b/src/llvm-project/lldb/source/Target/InstrumentationRuntimeStopInfo.cpp
@@ -1,9 +1,8 @@ //===-- InstrumentationRuntimeStopInfo.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/JITLoader.cpp b/src/llvm-project/lldb/source/Target/JITLoader.cpp index ddadcfa..e7c13bd 100644 --- a/src/llvm-project/lldb/source/Target/JITLoader.cpp +++ b/src/llvm-project/lldb/source/Target/JITLoader.cpp
@@ -1,9 +1,8 @@ //===-- JITLoader.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/JITLoaderList.cpp b/src/llvm-project/lldb/source/Target/JITLoaderList.cpp index 1e908bd..4d1f06d 100644 --- a/src/llvm-project/lldb/source/Target/JITLoaderList.cpp +++ b/src/llvm-project/lldb/source/Target/JITLoaderList.cpp
@@ -1,9 +1,8 @@ //===-- JITLoaderList.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/Language.cpp b/src/llvm-project/lldb/source/Target/Language.cpp index 5c7a409..3c3ef28 100644 --- a/src/llvm-project/lldb/source/Target/Language.cpp +++ b/src/llvm-project/lldb/source/Target/Language.cpp
@@ -1,10 +1,9 @@ //===-- Language.cpp -------------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -274,6 +273,24 @@ } } +bool Language::LanguageIsCFamily(LanguageType language) { + switch (language) { + case eLanguageTypeC: + case eLanguageTypeC89: + case eLanguageTypeC99: + case eLanguageTypeC11: + case eLanguageTypeC_plus_plus: + case eLanguageTypeC_plus_plus_03: + case eLanguageTypeC_plus_plus_11: + case eLanguageTypeC_plus_plus_14: + case eLanguageTypeObjC_plus_plus: + case eLanguageTypeObjC: + return true; + default: + return false; + } +} + bool Language::LanguageIsPascal(LanguageType language) { switch (language) { case eLanguageTypePascal83: @@ -331,6 +348,15 @@ } } +std::set<lldb::LanguageType> Language::GetSupportedLanguages() { + std::set<lldb::LanguageType> supported_languages; + ForEach([&](Language *lang) { + supported_languages.emplace(lang->GetLanguageType()); + return true; + }); + return supported_languages; +} + void Language::GetLanguagesSupportingTypeSystems( std::set<lldb::LanguageType> &languages, std::set<lldb::LanguageType> &languages_for_expressions) { @@ -391,7 +417,7 @@ images.FindTypes(nullptr, cs_key, false, UINT32_MAX, searched_sym_files, matches); for (const auto &match : matches.Types()) { - if (match.get()) { + if (match) { CompilerType compiler_type(match->GetFullCompilerType()); compiler_type = AdjustForInclusion(compiler_type); if (!compiler_type) @@ -444,12 +470,8 @@ s.Printf("Exception breakpoint (catch: %s throw: %s)", catch_on ? "on" : "off", throw_on ? "on" : "off"); } -//---------------------------------------------------------------------- // Constructor -//---------------------------------------------------------------------- Language::Language() {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- Language::~Language() {}
diff --git a/src/llvm-project/lldb/source/Target/LanguageRuntime.cpp b/src/llvm-project/lldb/source/Target/LanguageRuntime.cpp index ea6914f..dd44158 100644 --- a/src/llvm-project/lldb/source/Target/LanguageRuntime.cpp +++ b/src/llvm-project/lldb/source/Target/LanguageRuntime.cpp
@@ -1,23 +1,23 @@ //===-- LanguageRuntime.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/LanguageRuntime.h" -#include "Plugins/Language/ObjC/ObjCLanguage.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/SearchFilter.h" #include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Target/ObjCLanguageRuntime.h" +#include "lldb/Target/Language.h" #include "lldb/Target/Target.h" using namespace lldb; using namespace lldb_private; +char LanguageRuntime::ID = 0; + ExceptionSearchFilter::ExceptionSearchFilter(const lldb::TargetSP &target_sp, lldb::LanguageType language, bool update_module_list) @@ -202,7 +202,7 @@ LanguageRuntime *LanguageRuntime::FindPlugin(Process *process, lldb::LanguageType language) { - std::unique_ptr<LanguageRuntime> language_runtime_ap; + std::unique_ptr<LanguageRuntime> language_runtime_up; LanguageRuntimeCreateInstance create_callback; for (uint32_t idx = 0; @@ -210,10 +210,10 @@ PluginManager::GetLanguageRuntimeCreateCallbackAtIndex(idx)) != nullptr; ++idx) { - language_runtime_ap.reset(create_callback(process, language)); + language_runtime_up.reset(create_callback(process, language)); - if (language_runtime_ap) - return language_runtime_ap.release(); + if (language_runtime_up) + return language_runtime_up.release(); } return nullptr; @@ -223,19 +223,24 @@ LanguageRuntime::~LanguageRuntime() = default; -Breakpoint::BreakpointPreconditionSP -LanguageRuntime::CreateExceptionPrecondition(lldb::LanguageType language, - bool catch_bp, bool throw_bp) { - switch (language) { - case eLanguageTypeObjC: - if (throw_bp) - return Breakpoint::BreakpointPreconditionSP( - new ObjCLanguageRuntime::ObjCExceptionPrecondition()); - break; - default: - break; +BreakpointPreconditionSP +LanguageRuntime::GetExceptionPrecondition(LanguageType language, + bool throw_bp) { + LanguageRuntimeCreateInstance create_callback; + for (uint32_t idx = 0; + (create_callback = + PluginManager::GetLanguageRuntimeCreateCallbackAtIndex(idx)) != + nullptr; + idx++) { + if (auto precondition_callback = + PluginManager::GetLanguageRuntimeGetExceptionPreconditionAtIndex( + idx)) { + if (BreakpointPreconditionSP precond = + precondition_callback(language, throw_bp)) + return precond; + } } - return Breakpoint::BreakpointPreconditionSP(); + return BreakpointPreconditionSP(); } BreakpointSP LanguageRuntime::CreateExceptionBreakpoint( @@ -251,10 +256,8 @@ target.CreateBreakpoint(filter_sp, resolver_sp, is_internal, hardware, resolve_indirect_functions)); if (exc_breakpt_sp) { - Breakpoint::BreakpointPreconditionSP precondition_sp = - CreateExceptionPrecondition(language, catch_bp, throw_bp); - if (precondition_sp) - exc_breakpt_sp->SetPrecondition(precondition_sp); + if (auto precond = GetExceptionPrecondition(language, throw_bp)) + exc_breakpt_sp->SetPrecondition(precond); if (is_internal) exc_breakpt_sp->SetBreakpointKind("exception"); @@ -291,7 +294,3 @@ } } } - -lldb::SearchFilterSP LanguageRuntime::CreateExceptionSearchFilter() { - return m_process->GetTarget().GetSearchFilterForModule(nullptr); -}
diff --git a/src/llvm-project/lldb/source/Target/Memory.cpp b/src/llvm-project/lldb/source/Target/Memory.cpp index 190c505..31a3780 100644 --- a/src/llvm-project/lldb/source/Target/Memory.cpp +++ b/src/llvm-project/lldb/source/Target/Memory.cpp
@@ -1,34 +1,31 @@ //===-- Memory.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Memory.h" -#include <inttypes.h> -#include "lldb/Core/RangeMap.h" #include "lldb/Target/Process.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/RangeMap.h" #include "lldb/Utility/State.h" +#include <cinttypes> +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // MemoryCache constructor -//---------------------------------------------------------------------- MemoryCache::MemoryCache(Process &process) : m_mutex(), m_L1_cache(), m_L2_cache(), m_invalid_ranges(), m_process(process), m_L2_cache_line_byte_size(process.GetMemoryCacheLineSize()) {} -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- MemoryCache::~MemoryCache() {} void MemoryCache::Clear(bool clear_invalid_ranges) { @@ -145,7 +142,7 @@ } AddrRange chunk_range(pos->first, pos->second->GetByteSize()); if (chunk_range.Contains(read_range)) { - memcpy(dst, pos->second->GetBytes() + addr - chunk_range.GetRangeBase(), + memcpy(dst, pos->second->GetBytes() + (addr - chunk_range.GetRangeBase()), dst_len); return dst_len; } @@ -227,17 +224,17 @@ if (bytes_left > 0) { assert((curr_addr % cache_line_byte_size) == 0); - std::unique_ptr<DataBufferHeap> data_buffer_heap_ap( + std::unique_ptr<DataBufferHeap> data_buffer_heap_up( new DataBufferHeap(cache_line_byte_size, 0)); size_t process_bytes_read = m_process.ReadMemoryFromInferior( - curr_addr, data_buffer_heap_ap->GetBytes(), - data_buffer_heap_ap->GetByteSize(), error); + curr_addr, data_buffer_heap_up->GetBytes(), + data_buffer_heap_up->GetByteSize(), error); if (process_bytes_read == 0) return dst_len - bytes_left; if (process_bytes_read != cache_line_byte_size) - data_buffer_heap_ap->SetByteSize(process_bytes_read); - m_L2_cache[curr_addr] = DataBufferSP(data_buffer_heap_ap.release()); + data_buffer_heap_up->SetByteSize(process_bytes_read); + m_L2_cache[curr_addr] = DataBufferSP(data_buffer_heap_up.release()); // We have read data and put it into the cache, continue through the // loop again to get the data out of the cache... } @@ -358,8 +355,8 @@ } if (addr != LLDB_INVALID_ADDRESS) { - block_sp.reset( - new AllocatedBlock(addr, page_byte_size, permissions, chunk_size)); + block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size, + permissions, chunk_size); m_memory_map.insert(std::make_pair(permissions, block_sp)); } return block_sp;
diff --git a/src/llvm-project/lldb/source/Target/MemoryHistory.cpp b/src/llvm-project/lldb/source/Target/MemoryHistory.cpp index eae9314..37148e1 100644 --- a/src/llvm-project/lldb/source/Target/MemoryHistory.cpp +++ b/src/llvm-project/lldb/source/Target/MemoryHistory.cpp
@@ -1,9 +1,8 @@ //===-- MemoryHistory.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/ModuleCache.cpp b/src/llvm-project/lldb/source/Target/ModuleCache.cpp index daf787b..444c980 100644 --- a/src/llvm-project/lldb/source/Target/ModuleCache.cpp +++ b/src/llvm-project/lldb/source/Target/ModuleCache.cpp
@@ -1,9 +1,8 @@ //===--------------------- ModuleCache.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/OperatingSystem.cpp b/src/llvm-project/lldb/source/Target/OperatingSystem.cpp index 099bfd0..c78c197 100644 --- a/src/llvm-project/lldb/source/Target/OperatingSystem.cpp +++ b/src/llvm-project/lldb/source/Target/OperatingSystem.cpp
@@ -1,9 +1,8 @@ //===-- OperatingSystem.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,10 +22,10 @@ PluginManager::GetOperatingSystemCreateCallbackForPluginName( const_plugin_name); if (create_callback) { - std::unique_ptr<OperatingSystem> instance_ap( + std::unique_ptr<OperatingSystem> instance_up( create_callback(process, true)); - if (instance_ap) - return instance_ap.release(); + if (instance_up) + return instance_up.release(); } } else { for (uint32_t idx = 0; @@ -34,10 +33,10 @@ PluginManager::GetOperatingSystemCreateCallbackAtIndex(idx)) != nullptr; ++idx) { - std::unique_ptr<OperatingSystem> instance_ap( + std::unique_ptr<OperatingSystem> instance_up( create_callback(process, false)); - if (instance_ap) - return instance_ap.release(); + if (instance_up) + return instance_up.release(); } } return nullptr;
diff --git a/src/llvm-project/lldb/source/Target/PathMappingList.cpp b/src/llvm-project/lldb/source/Target/PathMappingList.cpp index c2249cc..58c2c43 100644 --- a/src/llvm-project/lldb/source/Target/PathMappingList.cpp +++ b/src/llvm-project/lldb/source/Target/PathMappingList.cpp
@@ -1,9 +1,8 @@ //===-- PathMappingList.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -31,15 +30,13 @@ // with the raw path pair, which doesn't work anymore because the paths have // been normalized when the debug info was loaded. So we need to store // nomalized path pairs to ensure things match up. - ConstString NormalizePath(const ConstString &path) { + ConstString NormalizePath(ConstString path) { // If we use "path" to construct a FileSpec, it will normalize the path for // us. We then grab the string and turn it back into a ConstString. return ConstString(FileSpec(path.GetStringRef()).GetPath()); } } -//---------------------------------------------------------------------- // PathMappingList constructor -//---------------------------------------------------------------------- PathMappingList::PathMappingList() : m_pairs(), m_callback(nullptr), m_callback_baton(nullptr), m_mod_id(0) {} @@ -63,8 +60,8 @@ PathMappingList::~PathMappingList() = default; -void PathMappingList::Append(const ConstString &path, - const ConstString &replacement, bool notify) { +void PathMappingList::Append(ConstString path, + ConstString replacement, bool notify) { ++m_mod_id; m_pairs.emplace_back(pair(NormalizePath(path), NormalizePath(replacement))); if (notify && m_callback) @@ -82,8 +79,8 @@ } } -void PathMappingList::Insert(const ConstString &path, - const ConstString &replacement, uint32_t index, +void PathMappingList::Insert(ConstString path, + ConstString replacement, uint32_t index, bool notify) { ++m_mod_id; iterator insert_iter; @@ -97,8 +94,8 @@ m_callback(*this, m_callback_baton); } -bool PathMappingList::Replace(const ConstString &path, - const ConstString &replacement, uint32_t index, +bool PathMappingList::Replace(ConstString path, + ConstString replacement, uint32_t index, bool notify) { if (index >= m_pairs.size()) return false; @@ -147,7 +144,7 @@ m_callback(*this, m_callback_baton); } -bool PathMappingList::RemapPath(const ConstString &path, +bool PathMappingList::RemapPath(ConstString path, ConstString &new_path) const { std::string remapped; if (RemapPath(path.GetStringRef(), remapped)) { @@ -202,32 +199,51 @@ bool PathMappingList::FindFile(const FileSpec &orig_spec, FileSpec &new_spec) const { - if (!m_pairs.empty()) { - char orig_path[PATH_MAX]; - const size_t orig_path_len = - orig_spec.GetPath(orig_path, sizeof(orig_path)); - if (orig_path_len > 0) { - const_iterator pos, end = m_pairs.end(); - for (pos = m_pairs.begin(); pos != end; ++pos) { - const size_t prefix_len = pos->first.GetLength(); + if (m_pairs.empty()) + return false; + + std::string orig_path = orig_spec.GetPath(); + + if (orig_path.empty()) + return false; + + bool orig_is_relative = orig_spec.IsRelative(); - if (orig_path_len >= prefix_len) { - if (::strncmp(pos->first.GetCString(), orig_path, prefix_len) == 0) { - new_spec.SetFile(pos->second.GetCString(), FileSpec::Style::native); - new_spec.AppendPathComponent(orig_path + prefix_len); - if (FileSystem::Instance().Exists(new_spec)) - return true; - } - } - } + for (auto entry : m_pairs) { + llvm::StringRef orig_ref(orig_path); + llvm::StringRef prefix_ref = entry.first.GetStringRef(); + if (orig_ref.size() < prefix_ref.size()) + continue; + // We consider a relative prefix or one of just "." to + // mean "only apply to relative paths". + bool prefix_is_relative = false; + + if (prefix_ref == ".") { + prefix_is_relative = true; + // Remove the "." since it will have been removed from the + // FileSpec paths already. + prefix_ref = prefix_ref.drop_front(); + } else { + FileSpec prefix_spec(prefix_ref, FileSpec::Style::native); + prefix_is_relative = prefix_spec.IsRelative(); + } + if (prefix_is_relative != orig_is_relative) + continue; + + if (orig_ref.consume_front(prefix_ref)) { + new_spec.SetFile(entry.second.GetCString(), FileSpec::Style::native); + new_spec.AppendPathComponent(orig_ref); + if (FileSystem::Instance().Exists(new_spec)) + return true; } } + new_spec.Clear(); return false; } -bool PathMappingList::Replace(const ConstString &path, - const ConstString &new_path, bool notify) { +bool PathMappingList::Replace(ConstString path, + ConstString new_path, bool notify) { uint32_t idx = FindIndexForPath(path); if (idx < m_pairs.size()) { ++m_mod_id; @@ -239,7 +255,7 @@ return false; } -bool PathMappingList::Remove(const ConstString &path, bool notify) { +bool PathMappingList::Remove(ConstString path, bool notify) { iterator pos = FindIteratorForPath(path); if (pos != m_pairs.end()) { ++m_mod_id; @@ -252,7 +268,7 @@ } PathMappingList::const_iterator -PathMappingList::FindIteratorForPath(const ConstString &path) const { +PathMappingList::FindIteratorForPath(ConstString path) const { const_iterator pos; const_iterator begin = m_pairs.begin(); const_iterator end = m_pairs.end(); @@ -265,7 +281,7 @@ } PathMappingList::iterator -PathMappingList::FindIteratorForPath(const ConstString &path) { +PathMappingList::FindIteratorForPath(ConstString path) { iterator pos; iterator begin = m_pairs.begin(); iterator end = m_pairs.end(); @@ -287,7 +303,7 @@ return false; } -uint32_t PathMappingList::FindIndexForPath(const ConstString &orig_path) const { +uint32_t PathMappingList::FindIndexForPath(ConstString orig_path) const { const ConstString path = NormalizePath(orig_path); const_iterator pos; const_iterator begin = m_pairs.begin();
diff --git a/src/llvm-project/lldb/source/Target/Platform.cpp b/src/llvm-project/lldb/source/Target/Platform.cpp index 400b3c9..710f82e 100644 --- a/src/llvm-project/lldb/source/Target/Platform.cpp +++ b/src/llvm-project/lldb/source/Target/Platform.cpp
@@ -1,15 +1,15 @@ //===-- Platform.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <csignal> #include <fstream> +#include <memory> #include <vector> #include "llvm/Support/FileSystem.h" @@ -79,7 +79,7 @@ } PlatformProperties::PlatformProperties() { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); + m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); m_collection_sp->Initialize(g_properties); auto module_cache_dir = GetModuleCacheDirectory(); @@ -117,7 +117,6 @@ nullptr, ePropertyModuleCacheDirectory, dir_spec); } -//------------------------------------------------------------------ /// Get the native host platform plug-in. /// /// There should only be one of these for each host that LLDB runs @@ -126,7 +125,6 @@ /// /// This platform will be used as the default platform when launching /// or attaching to processes unless another platform is specified. -//------------------------------------------------------------------ PlatformSP Platform::GetHostPlatform() { return GetHostPlatformSP(); } static std::vector<PlatformSP> &GetPlatformList() { @@ -180,7 +178,7 @@ } // PlatformSP -// Platform::FindPlugin (Process *process, const ConstString &plugin_name) +// Platform::FindPlugin (Process *process, ConstString plugin_name) //{ // PlatformCreateInstance create_callback = nullptr; // if (plugin_name) @@ -267,7 +265,7 @@ module_spec); } -PlatformSP Platform::Find(const ConstString &name) { +PlatformSP Platform::Find(ConstString name) { if (name) { static ConstString g_host_platform_name("host"); if (name == g_host_platform_name) @@ -282,7 +280,7 @@ return PlatformSP(); } -PlatformSP Platform::Create(const ConstString &name, Status &error) { +PlatformSP Platform::Create(ConstString name, Status &error) { PlatformCreateInstance create_callback = nullptr; lldb::PlatformSP platform_sp; if (name) { @@ -377,29 +375,25 @@ return HostInfo::GetAugmentedArchSpec(triple); } -//------------------------------------------------------------------ /// Default Constructor -//------------------------------------------------------------------ Platform::Platform(bool is_host) : m_is_host(is_host), m_os_version_set_while_connected(false), m_system_arch_set_while_connected(false), m_sdk_sysroot(), m_sdk_build(), m_working_dir(), m_remote_url(), m_name(), m_system_arch(), m_mutex(), - m_uid_map(), m_gid_map(), m_max_uid_name_len(0), m_max_gid_name_len(0), - m_supports_rsync(false), m_rsync_opts(), m_rsync_prefix(), - m_supports_ssh(false), m_ssh_opts(), m_ignores_remote_hostname(false), - m_trap_handlers(), m_calculated_trap_handlers(false), + m_max_uid_name_len(0), m_max_gid_name_len(0), m_supports_rsync(false), + m_rsync_opts(), m_rsync_prefix(), m_supports_ssh(false), m_ssh_opts(), + m_ignores_remote_hostname(false), m_trap_handlers(), + m_calculated_trap_handlers(false), m_module_cache(llvm::make_unique<ModuleCache>()) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); if (log) log->Printf("%p Platform::Platform()", static_cast<void *>(this)); } -//------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. -//------------------------------------------------------------------ Platform::~Platform() { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); if (log) @@ -834,34 +828,6 @@ return true; } -const char *Platform::GetUserName(uint32_t uid) { -#if !defined(LLDB_DISABLE_POSIX) - const char *user_name = GetCachedUserName(uid); - if (user_name) - return user_name; - if (IsHost()) { - std::string name; - if (HostInfo::LookupUserName(uid, name)) - return SetCachedUserName(uid, name.c_str(), name.size()); - } -#endif - return nullptr; -} - -const char *Platform::GetGroupName(uint32_t gid) { -#if !defined(LLDB_DISABLE_POSIX) - const char *group_name = GetCachedGroupName(gid); - if (group_name) - return group_name; - if (IsHost()) { - std::string name; - if (HostInfo::LookupGroupName(gid, name)) - return SetCachedGroupName(gid, name.c_str(), name.size()); - } -#endif - return nullptr; -} - bool Platform::SetOSVersion(llvm::VersionTuple version) { if (IsHost()) { // We don't need anyone setting the OS version for the host platform, we @@ -1060,11 +1026,11 @@ uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info); if (log) { const FileSpec &shell = launch_info.GetShell(); - const char *shell_str = (shell) ? shell.GetPath().c_str() : "<null>"; + std::string shell_str = (shell) ? shell.GetPath() : "<null>"; log->Printf( "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32 ", shell is '%s'", - __FUNCTION__, num_resumes, shell_str); + __FUNCTION__, num_resumes, shell_str.c_str()); } if (!launch_info.ConvertArgumentsForLaunchingInShell( @@ -1226,10 +1192,8 @@ return platform_sp; } -//------------------------------------------------------------------ /// Lets a platform answer if it is compatible with a given /// architecture and the target triple contained within. -//------------------------------------------------------------------ bool Platform::IsCompatibleArchitecture(const ArchSpec &arch, bool exact_arch_match, ArchSpec *compatible_arch_ptr) { @@ -1740,9 +1704,9 @@ return s_default_unix_signals_sp; } -const UnixSignalsSP &Platform::GetUnixSignals() { +UnixSignalsSP Platform::GetUnixSignals() { if (IsHost()) - return Host::GetUnixSignals(); + return UnixSignals::CreateForHost(); return GetRemoteUnixSignals(); }
diff --git a/src/llvm-project/lldb/source/Target/Process.cpp b/src/llvm-project/lldb/source/Target/Process.cpp index fb3b758..6c634db 100644 --- a/src/llvm-project/lldb/source/Target/Process.cpp +++ b/src/llvm-project/lldb/source/Target/Process.cpp
@@ -1,13 +1,13 @@ //===-- Process.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <atomic> +#include <memory> #include <mutex> #include "llvm/Support/ScopedPrinter.h" @@ -22,7 +22,7 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Expression/IRDynamicChecks.h" +#include "lldb/Expression/DynamicCheckerFunctions.h" #include "lldb/Expression/UserExpression.h" #include "lldb/Expression/UtilityFunction.h" #include "lldb/Host/ConnectionFileDescriptor.h" @@ -39,15 +39,14 @@ #include "lldb/Symbol/Function.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/ABI.h" -#include "lldb/Target/CPPLanguageRuntime.h" #include "lldb/Target/DynamicLoader.h" #include "lldb/Target/InstrumentationRuntime.h" #include "lldb/Target/JITLoader.h" #include "lldb/Target/JITLoaderList.h" +#include "lldb/Target/Language.h" #include "lldb/Target/LanguageRuntime.h" #include "lldb/Target/MemoryHistory.h" #include "lldb/Target/MemoryRegionInfo.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/OperatingSystem.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" @@ -64,6 +63,7 @@ #include "lldb/Utility/Event.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/NameMatches.h" +#include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/SelectHelper.h" #include "lldb/Utility/State.h" @@ -83,7 +83,7 @@ class ProcessOptionValueProperties : public OptionValueProperties { public: - ProcessOptionValueProperties(const ConstString &name) + ProcessOptionValueProperties(ConstString name) : OptionValueProperties(name) {} // This constructor is used when creating ProcessOptionValueProperties when @@ -143,7 +143,11 @@ "stepping and variable availability may not behave as expected."}, {"stop-on-exec", OptionValue::eTypeBoolean, true, true, nullptr, {}, - "If true, stop when a shared library is loaded or unloaded."}}; + "If true, stop when a shared library is loaded or unloaded."}, + {"utility-expression-timeout", OptionValue::eTypeUInt64, false, 15, + nullptr, {}, + "The time in seconds to wait for LLDB-internal utility expressions."} +}; enum { ePropertyDisableMemCache, @@ -155,7 +159,8 @@ ePropertyDetachKeepsStopped, ePropertyMemCacheLineSize, ePropertyWarningOptimization, - ePropertyStopOnExec + ePropertyStopOnExec, + ePropertyUtilityExpressionTimeout, }; ProcessProperties::ProcessProperties(lldb_private::Process *process) @@ -164,15 +169,15 @@ { if (process == nullptr) { // Global process properties, set them up one time - m_collection_sp.reset( - new ProcessOptionValueProperties(ConstString("process"))); + m_collection_sp = + std::make_shared<ProcessOptionValueProperties>(ConstString("process")); m_collection_sp->Initialize(g_properties); m_collection_sp->AppendProperty( ConstString("thread"), ConstString("Settings specific to threads."), true, Thread::GetGlobalProperties()->GetValueProperties()); } else { - m_collection_sp.reset( - new ProcessOptionValueProperties(Process::GetGlobalProperties().get())); + m_collection_sp = std::make_shared<ProcessOptionValueProperties>( + Process::GetGlobalProperties().get()); m_collection_sp->SetValueChangedCallback( ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this); @@ -278,138 +283,11 @@ nullptr, idx, g_properties[idx].default_uint_value != 0); } -void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const { - const char *cstr; - if (m_pid != LLDB_INVALID_PROCESS_ID) - s.Printf(" pid = %" PRIu64 "\n", m_pid); - - if (m_parent_pid != LLDB_INVALID_PROCESS_ID) - s.Printf(" parent = %" PRIu64 "\n", m_parent_pid); - - if (m_executable) { - s.Printf(" name = %s\n", m_executable.GetFilename().GetCString()); - s.PutCString(" file = "); - m_executable.Dump(&s); - s.EOL(); - } - const uint32_t argc = m_arguments.GetArgumentCount(); - if (argc > 0) { - for (uint32_t i = 0; i < argc; i++) { - const char *arg = m_arguments.GetArgumentAtIndex(i); - if (i < 10) - s.Printf(" arg[%u] = %s\n", i, arg); - else - s.Printf("arg[%u] = %s\n", i, arg); - } - } - - s.Format("{0}", m_environment); - - if (m_arch.IsValid()) { - s.Printf(" arch = "); - m_arch.DumpTriple(s); - s.EOL(); - } - - if (m_uid != UINT32_MAX) { - cstr = platform->GetUserName(m_uid); - s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : ""); - } - if (m_gid != UINT32_MAX) { - cstr = platform->GetGroupName(m_gid); - s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : ""); - } - if (m_euid != UINT32_MAX) { - cstr = platform->GetUserName(m_euid); - s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : ""); - } - if (m_egid != UINT32_MAX) { - cstr = platform->GetGroupName(m_egid); - s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : ""); - } -} - -void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform, - bool show_args, bool verbose) { - const char *label; - if (show_args || verbose) - label = "ARGUMENTS"; - else - label = "NAME"; - - if (verbose) { - s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE " - " %s\n", - label); - s.PutCString("====== ====== ========== ========== ========== ========== " - "======================== ============================\n"); - } else { - s.Printf("PID PARENT USER TRIPLE %s\n", label); - s.PutCString("====== ====== ========== ======================== " - "============================\n"); - } -} - -void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform, - bool show_args, bool verbose) const { - if (m_pid != LLDB_INVALID_PROCESS_ID) { - const char *cstr; - s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid); - - StreamString arch_strm; - if (m_arch.IsValid()) - m_arch.DumpTriple(arch_strm); - - if (verbose) { - cstr = platform->GetUserName(m_uid); - if (cstr && - cstr[0]) // Watch for empty string that indicates lookup failed - s.Printf("%-10s ", cstr); - else - s.Printf("%-10u ", m_uid); - - cstr = platform->GetGroupName(m_gid); - if (cstr && - cstr[0]) // Watch for empty string that indicates lookup failed - s.Printf("%-10s ", cstr); - else - s.Printf("%-10u ", m_gid); - - cstr = platform->GetUserName(m_euid); - if (cstr && - cstr[0]) // Watch for empty string that indicates lookup failed - s.Printf("%-10s ", cstr); - else - s.Printf("%-10u ", m_euid); - - cstr = platform->GetGroupName(m_egid); - if (cstr && - cstr[0]) // Watch for empty string that indicates lookup failed - s.Printf("%-10s ", cstr); - else - s.Printf("%-10u ", m_egid); - - s.Printf("%-24s ", arch_strm.GetData()); - } else { - s.Printf("%-10s %-24s ", platform->GetUserName(m_euid), - arch_strm.GetData()); - } - - if (verbose || show_args) { - const uint32_t argc = m_arguments.GetArgumentCount(); - if (argc > 0) { - for (uint32_t i = 0; i < argc; i++) { - if (i > 0) - s.PutChar(' '); - s.PutCString(m_arguments.GetArgumentAtIndex(i)); - } - } - } else { - s.PutCString(GetName()); - } - - s.EOL(); - } +std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const { + const uint32_t idx = ePropertyUtilityExpressionTimeout; + uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64( + nullptr, idx, g_properties[idx].default_uint_value); + return std::chrono::seconds(value); } Status ProcessLaunchCommandOptions::SetOptionValue( @@ -581,89 +459,6 @@ return llvm::makeArrayRef(g_process_launch_options); } -bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const { - if (m_name_match_type == NameMatch::Ignore || process_name == nullptr) - return true; - const char *match_name = m_match_info.GetName(); - if (!match_name) - return true; - - return lldb_private::NameMatches(process_name, m_name_match_type, match_name); -} - -bool ProcessInstanceInfoMatch::Matches( - const ProcessInstanceInfo &proc_info) const { - if (!NameMatches(proc_info.GetName())) - return false; - - if (m_match_info.ProcessIDIsValid() && - m_match_info.GetProcessID() != proc_info.GetProcessID()) - return false; - - if (m_match_info.ParentProcessIDIsValid() && - m_match_info.GetParentProcessID() != proc_info.GetParentProcessID()) - return false; - - if (m_match_info.UserIDIsValid() && - m_match_info.GetUserID() != proc_info.GetUserID()) - return false; - - if (m_match_info.GroupIDIsValid() && - m_match_info.GetGroupID() != proc_info.GetGroupID()) - return false; - - if (m_match_info.EffectiveUserIDIsValid() && - m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID()) - return false; - - if (m_match_info.EffectiveGroupIDIsValid() && - m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID()) - return false; - - if (m_match_info.GetArchitecture().IsValid() && - !m_match_info.GetArchitecture().IsCompatibleMatch( - proc_info.GetArchitecture())) - return false; - return true; -} - -bool ProcessInstanceInfoMatch::MatchAllProcesses() const { - if (m_name_match_type != NameMatch::Ignore) - return false; - - if (m_match_info.ProcessIDIsValid()) - return false; - - if (m_match_info.ParentProcessIDIsValid()) - return false; - - if (m_match_info.UserIDIsValid()) - return false; - - if (m_match_info.GroupIDIsValid()) - return false; - - if (m_match_info.EffectiveUserIDIsValid()) - return false; - - if (m_match_info.EffectiveGroupIDIsValid()) - return false; - - if (m_match_info.GetArchitecture().IsValid()) - return false; - - if (m_match_all_users) - return false; - - return true; -} - -void ProcessInstanceInfoMatch::Clear() { - m_match_info.Clear(); - m_name_match_type = NameMatch::Ignore; - m_match_all_users = false; -} - ProcessSP Process::FindPlugin(lldb::TargetSP target_sp, llvm::StringRef plugin_name, ListenerSP listener_sp, @@ -734,13 +529,13 @@ m_thread_list(this), m_extended_thread_list(this), m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0), m_notifications(), m_image_tokens(), m_listener_sp(listener_sp), - m_breakpoint_site_list(), m_dynamic_checkers_ap(), + m_breakpoint_site_list(), m_dynamic_checkers_up(), m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(), m_stdio_communication("process.stdio"), m_stdio_communication_mutex(), m_stdin_forward(false), m_stdout_data(), m_stderr_data(), m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0), m_memory_cache(*this), m_allocated_memory_cache(*this), - m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(), + m_should_detach(false), m_next_event_action_up(), m_public_run_lock(), m_private_run_lock(), m_finalizing(false), m_finalize_called(false), m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false), m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false), @@ -848,12 +643,12 @@ // We need to destroy the loader before the derived Process class gets // destroyed since it is very likely that undoing the loader will require // access to the real process. - m_dynamic_checkers_ap.reset(); + m_dynamic_checkers_up.reset(); m_abi_sp.reset(); - m_os_ap.reset(); - m_system_runtime_ap.reset(); - m_dyld_ap.reset(); - m_jit_loaders_ap.reset(); + m_os_up.reset(); + m_system_runtime_up.reset(); + m_dyld_up.reset(); + m_jit_loaders_up.reset(); m_thread_list_real.Destroy(); m_thread_list.Destroy(); m_extended_thread_list.Destroy(); @@ -864,9 +659,12 @@ m_image_tokens.clear(); m_memory_cache.Clear(); m_allocated_memory_cache.Clear(); - m_language_runtimes.clear(); + { + std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); + m_language_runtimes.clear(); + } m_instrumentation_runtimes.clear(); - m_next_event_action_ap.reset(); + m_next_event_action_up.reset(); // Clear the last natural stop ID since it has a strong reference to this // process m_mod_id.SetStopEventForLastNaturalStopID(EventSP()); @@ -1506,12 +1304,12 @@ } void Process::UpdateQueueListIfNeeded() { - if (m_system_runtime_ap) { + if (m_system_runtime_up) { if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID()) { const StateType state = GetPrivateState(); if (StateIsStoppedState(state, true)) { - m_system_runtime_ap->PopulateQueueList(m_queue_list); + m_system_runtime_up->PopulateQueueList(m_queue_list); m_queue_list_stop_id = GetLastNaturalStopID(); } } @@ -1552,16 +1350,6 @@ return m_public_state.GetValue(); } -bool Process::StateChangedIsExternallyHijacked() { - if (IsHijackedForEvent(eBroadcastBitStateChanged)) { - const char *hijacking_name = GetHijackingListenerName(); - if (hijacking_name && - strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack")) - return true; - } - return false; -} - void Process::SetPublicState(StateType new_state, bool restarted) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); @@ -1615,6 +1403,8 @@ return error; } +static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack"; + Status Process::ResumeSynchronous(Stream *stream) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); @@ -1628,13 +1418,13 @@ } ListenerSP listener_sp( - Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack")); + Listener::MakeListener(g_resume_sync_name)); HijackProcessEvents(listener_sp); Status error = PrivateResume(); if (error.Success()) { StateType state = - WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream); + WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream); const bool must_be_alive = false; // eStateExited is ok, so this must be false if (!StateIsStoppedState(state, must_be_alive)) @@ -1652,6 +1442,26 @@ return error; } +bool Process::StateChangedIsExternallyHijacked() { + if (IsHijackedForEvent(eBroadcastBitStateChanged)) { + const char *hijacking_name = GetHijackingListenerName(); + if (hijacking_name && + strcmp(hijacking_name, g_resume_sync_name)) + return true; + } + return false; +} + +bool Process::StateChangedIsHijackedForSynchronousResume() { + if (IsHijackedForEvent(eBroadcastBitStateChanged)) { + const char *hijacking_name = GetHijackingListenerName(); + if (hijacking_name && + strcmp(hijacking_name, g_resume_sync_name) == 0) + return true; + } + return false; +} + StateType Process::GetPrivateState() { return m_private_state.GetValue(); } void Process::SetPrivateState(StateType new_state) { @@ -1736,38 +1546,54 @@ return m_abi_sp; } +std::vector<LanguageRuntime *> +Process::GetLanguageRuntimes(bool retry_if_null) { + std::vector<LanguageRuntime *> language_runtimes; + + if (m_finalizing) + return language_runtimes; + + std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); + // Before we pass off a copy of the language runtimes, we must make sure that + // our collection is properly populated. It's possible that some of the + // language runtimes were not loaded yet, either because nobody requested it + // yet or the proper condition for loading wasn't yet met (e.g. libc++.so + // hadn't been loaded). + for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) { + if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type, retry_if_null)) + language_runtimes.emplace_back(runtime); + } + + return language_runtimes; +} + LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null) { if (m_finalizing) return nullptr; + LanguageRuntime *runtime = nullptr; + + std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); LanguageRuntimeCollection::iterator pos; pos = m_language_runtimes.find(language); - if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) { + if (pos == m_language_runtimes.end() || (retry_if_null && !pos->second)) { lldb::LanguageRuntimeSP runtime_sp( LanguageRuntime::FindPlugin(this, language)); m_language_runtimes[language] = runtime_sp; - return runtime_sp.get(); + runtime = runtime_sp.get(); } else - return (*pos).second.get(); -} + runtime = pos->second.get(); -CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) { - LanguageRuntime *runtime = - GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null); - if (runtime != nullptr && - runtime->GetLanguageType() == eLanguageTypeC_plus_plus) - return static_cast<CPPLanguageRuntime *>(runtime); - return nullptr; -} + if (runtime) + // It's possible that a language runtime can support multiple LanguageTypes, + // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus, + // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the + // primary language type and make sure that our runtime supports it. + assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language)); -ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) { - LanguageRuntime *runtime = - GetLanguageRuntime(eLanguageTypeObjC, retry_if_null); - if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC) - return static_cast<ObjCLanguageRuntime *>(runtime); - return nullptr; + return runtime; } bool Process::IsPossibleDynamicValue(ValueObject &in_value) { @@ -1783,16 +1609,16 @@ return runtime ? runtime->CouldHaveDynamicValue(in_value) : false; } - LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus); - if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value)) - return true; + for (LanguageRuntime *runtime : GetLanguageRuntimes()) { + if (runtime->CouldHaveDynamicValue(in_value)) + return true; + } - LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC); - return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false; + return false; } void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) { - m_dynamic_checkers_ap.reset(dynamic_checkers); + m_dynamic_checkers_up.reset(dynamic_checkers); } BreakpointSiteList &Process::GetBreakpointSiteList() { @@ -2413,67 +2239,64 @@ // may have placed in our tasks memory. BreakpointSiteList bp_sites_in_range; - - if (m_breakpoint_site_list.FindInRange(addr, addr + size, - bp_sites_in_range)) { - // No breakpoint sites overlap - if (bp_sites_in_range.IsEmpty()) - return WriteMemoryPrivate(addr, buf, size, error); - else { - const uint8_t *ubuf = (const uint8_t *)buf; - uint64_t bytes_written = 0; - - bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, - &error](BreakpointSite *bp) -> void { - - if (error.Success()) { - addr_t intersect_addr; - size_t intersect_size; - size_t opcode_offset; - const bool intersects = bp->IntersectsRange( - addr, size, &intersect_addr, &intersect_size, &opcode_offset); - UNUSED_IF_ASSERT_DISABLED(intersects); - assert(intersects); - assert(addr <= intersect_addr && intersect_addr < addr + size); - assert(addr < intersect_addr + intersect_size && - intersect_addr + intersect_size <= addr + size); - assert(opcode_offset + intersect_size <= bp->GetByteSize()); - - // Check for bytes before this breakpoint - const addr_t curr_addr = addr + bytes_written; - if (intersect_addr > curr_addr) { - // There are some bytes before this breakpoint that we need to just - // write to memory - size_t curr_size = intersect_addr - curr_addr; - size_t curr_bytes_written = WriteMemoryPrivate( - curr_addr, ubuf + bytes_written, curr_size, error); - bytes_written += curr_bytes_written; - if (curr_bytes_written != curr_size) { - // We weren't able to write all of the requested bytes, we are - // done looping and will return the number of bytes that we have - // written so far. - if (error.Success()) - error.SetErrorToGenericError(); - } - } - // Now write any bytes that would cover up any software breakpoints - // directly into the breakpoint opcode buffer - ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, - ubuf + bytes_written, intersect_size); - bytes_written += intersect_size; - } - }); - - if (bytes_written < size) - WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written, - size - bytes_written, error); - } - } else { + if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range)) return WriteMemoryPrivate(addr, buf, size, error); - } + + // No breakpoint sites overlap + if (bp_sites_in_range.IsEmpty()) + return WriteMemoryPrivate(addr, buf, size, error); + + const uint8_t *ubuf = (const uint8_t *)buf; + uint64_t bytes_written = 0; + + bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, + &error](BreakpointSite *bp) -> void { + if (error.Fail()) + return; + + addr_t intersect_addr; + size_t intersect_size; + size_t opcode_offset; + const bool intersects = bp->IntersectsRange( + addr, size, &intersect_addr, &intersect_size, &opcode_offset); + UNUSED_IF_ASSERT_DISABLED(intersects); + assert(intersects); + assert(addr <= intersect_addr && intersect_addr < addr + size); + assert(addr < intersect_addr + intersect_size && + intersect_addr + intersect_size <= addr + size); + assert(opcode_offset + intersect_size <= bp->GetByteSize()); + + // Check for bytes before this breakpoint + const addr_t curr_addr = addr + bytes_written; + if (intersect_addr > curr_addr) { + // There are some bytes before this breakpoint that we need to just + // write to memory + size_t curr_size = intersect_addr - curr_addr; + size_t curr_bytes_written = + WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error); + bytes_written += curr_bytes_written; + if (curr_bytes_written != curr_size) { + // We weren't able to write all of the requested bytes, we are + // done looping and will return the number of bytes that we have + // written so far. + if (error.Success()) + error.SetErrorToGenericError(); + } + } + // Now write any bytes that would cover up any software breakpoints + // directly into the breakpoint opcode buffer + ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, + intersect_size); + bytes_written += intersect_size; + }); // Write any remaining bytes after the last breakpoint if we have any left - return 0; // bytes_written; + if (bytes_written < size) + bytes_written += + WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written, + size - bytes_written, error); + + return bytes_written; } size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar, @@ -2708,7 +2531,7 @@ void Process::LoadOperatingSystemPlugin(bool flush) { if (flush) m_thread_list.Clear(); - m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr)); + m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr)); if (flush) Flush(); } @@ -2716,115 +2539,119 @@ Status Process::Launch(ProcessLaunchInfo &launch_info) { Status error; m_abi_sp.reset(); - m_dyld_ap.reset(); - m_jit_loaders_ap.reset(); - m_system_runtime_ap.reset(); - m_os_ap.reset(); + m_dyld_up.reset(); + m_jit_loaders_up.reset(); + m_system_runtime_up.reset(); + m_os_up.reset(); m_process_input_reader.reset(); Module *exe_module = GetTarget().GetExecutableModulePointer(); - if (exe_module) { - char local_exec_file_path[PATH_MAX]; - char platform_exec_file_path[PATH_MAX]; - exe_module->GetFileSpec().GetPath(local_exec_file_path, - sizeof(local_exec_file_path)); - exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, - sizeof(platform_exec_file_path)); - if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) { - // Install anything that might need to be installed prior to launching. - // For host systems, this will do nothing, but if we are connected to a - // remote platform it will install any needed binaries - error = GetTarget().Install(&launch_info); - if (error.Fail()) - return error; + if (!exe_module) { + error.SetErrorString("executable module does not exist"); + return error; + } - if (PrivateStateThreadIsValid()) - PausePrivateStateThread(); + char local_exec_file_path[PATH_MAX]; + char platform_exec_file_path[PATH_MAX]; + exe_module->GetFileSpec().GetPath(local_exec_file_path, + sizeof(local_exec_file_path)); + exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, + sizeof(platform_exec_file_path)); + if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) { + // Install anything that might need to be installed prior to launching. + // For host systems, this will do nothing, but if we are connected to a + // remote platform it will install any needed binaries + error = GetTarget().Install(&launch_info); + if (error.Fail()) + return error; - error = WillLaunch(exe_module); - if (error.Success()) { - const bool restarted = false; - SetPublicState(eStateLaunching, restarted); - m_should_detach = false; + if (PrivateStateThreadIsValid()) + PausePrivateStateThread(); - if (m_public_run_lock.TrySetRunning()) { - // Now launch using these arguments. - error = DoLaunch(exe_module, launch_info); - } else { - // This shouldn't happen - error.SetErrorString("failed to acquire process run lock"); + error = WillLaunch(exe_module); + if (error.Success()) { + const bool restarted = false; + SetPublicState(eStateLaunching, restarted); + m_should_detach = false; + + if (m_public_run_lock.TrySetRunning()) { + // Now launch using these arguments. + error = DoLaunch(exe_module, launch_info); + } else { + // This shouldn't happen + error.SetErrorString("failed to acquire process run lock"); + } + + if (error.Fail()) { + if (GetID() != LLDB_INVALID_PROCESS_ID) { + SetID(LLDB_INVALID_PROCESS_ID); + const char *error_string = error.AsCString(); + if (error_string == nullptr) + error_string = "launch failed"; + SetExitStatus(-1, error_string); } + } else { + EventSP event_sp; - if (error.Fail()) { - if (GetID() != LLDB_INVALID_PROCESS_ID) { - SetID(LLDB_INVALID_PROCESS_ID); - const char *error_string = error.AsCString(); - if (error_string == nullptr) - error_string = "launch failed"; - SetExitStatus(-1, error_string); - } - } else { - EventSP event_sp; + // Now wait for the process to launch and return control to us, and then + // call DidLaunch: + StateType state = WaitForProcessStopPrivate(event_sp, seconds(10)); - // Now wait for the process to launch and return control to us, and then call - // DidLaunch: - StateType state = WaitForProcessStopPrivate(event_sp, seconds(10)); + if (state == eStateInvalid || !event_sp) { + // We were able to launch the process, but we failed to catch the + // initial stop. + error.SetErrorString("failed to catch stop after launch"); + SetExitStatus(0, "failed to catch stop after launch"); + Destroy(false); + } else if (state == eStateStopped || state == eStateCrashed) { + DidLaunch(); - if (state == eStateInvalid || !event_sp) { - // We were able to launch the process, but we failed to catch the - // initial stop. - error.SetErrorString("failed to catch stop after launch"); - SetExitStatus(0, "failed to catch stop after launch"); - Destroy(false); - } else if (state == eStateStopped || state == eStateCrashed) { - DidLaunch(); + DynamicLoader *dyld = GetDynamicLoader(); + if (dyld) + dyld->DidLaunch(); - DynamicLoader *dyld = GetDynamicLoader(); - if (dyld) - dyld->DidLaunch(); + GetJITLoaders().DidLaunch(); - GetJITLoaders().DidLaunch(); + SystemRuntime *system_runtime = GetSystemRuntime(); + if (system_runtime) + system_runtime->DidLaunch(); - SystemRuntime *system_runtime = GetSystemRuntime(); - if (system_runtime) - system_runtime->DidLaunch(); + if (!m_os_up) + LoadOperatingSystemPlugin(false); - if (!m_os_ap) - LoadOperatingSystemPlugin(false); + // We successfully launched the process and stopped, now it the + // right time to set up signal filters before resuming. + UpdateAutomaticSignalFiltering(); - // We successfully launched the process and stopped, now it the - // right time to set up signal filters before resuming. - UpdateAutomaticSignalFiltering(); + // Note, the stop event was consumed above, but not handled. This + // was done to give DidLaunch a chance to run. The target is either + // stopped or crashed. Directly set the state. This is done to + // prevent a stop message with a bunch of spurious output on thread + // status, as well as not pop a ProcessIOHandler. + SetPublicState(state, false); - // Note, the stop event was consumed above, but not handled. This - // was done to give DidLaunch a chance to run. The target is either - // stopped or crashed. Directly set the state. This is done to - // prevent a stop message with a bunch of spurious output on thread - // status, as well as not pop a ProcessIOHandler. - SetPublicState(state, false); + if (PrivateStateThreadIsValid()) + ResumePrivateStateThread(); + else + StartPrivateStateThread(); - if (PrivateStateThreadIsValid()) - ResumePrivateStateThread(); - else - StartPrivateStateThread(); - - // Target was stopped at entry as was intended. Need to notify the - // listeners about it. - if (state == eStateStopped && - launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) - HandlePrivateEvent(event_sp); - } else if (state == eStateExited) { - // We exited while trying to launch somehow. Don't call DidLaunch - // as that's not likely to work, and return an invalid pid. + // Target was stopped at entry as was intended. Need to notify the + // listeners about it. + if (state == eStateStopped && + launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) HandlePrivateEvent(event_sp); - } + } else if (state == eStateExited) { + // We exited while trying to launch somehow. Don't call DidLaunch + // as that's not likely to work, and return an invalid pid. + HandlePrivateEvent(event_sp); } } - } else { - error.SetErrorStringWithFormat("file doesn't exist: '%s'", - local_exec_file_path); } + } else { + error.SetErrorStringWithFormat("file doesn't exist: '%s'", + local_exec_file_path); } + return error; } @@ -2850,7 +2677,7 @@ if (system_runtime) system_runtime->DidAttach(); - if (!m_os_ap) + if (!m_os_up) LoadOperatingSystemPlugin(false); // We successfully loaded a core file, now pretend we stopped so we can @@ -2860,7 +2687,7 @@ // Wait for a stopped event since we just posted one above... lldb::EventSP event_sp; StateType state = - WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp); + WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp); if (!StateIsStoppedState(state, false)) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); @@ -2876,25 +2703,25 @@ } DynamicLoader *Process::GetDynamicLoader() { - if (!m_dyld_ap) - m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr)); - return m_dyld_ap.get(); + if (!m_dyld_up) + m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); + return m_dyld_up.get(); } -const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); } +DataExtractor Process::GetAuxvData() { return DataExtractor(); } JITLoaderList &Process::GetJITLoaders() { - if (!m_jit_loaders_ap) { - m_jit_loaders_ap.reset(new JITLoaderList()); - JITLoader::LoadPlugins(this, *m_jit_loaders_ap); + if (!m_jit_loaders_up) { + m_jit_loaders_up.reset(new JITLoaderList()); + JITLoader::LoadPlugins(this, *m_jit_loaders_up); } - return *m_jit_loaders_ap; + return *m_jit_loaders_up; } SystemRuntime *Process::GetSystemRuntime() { - if (!m_system_runtime_ap) - m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this)); - return m_system_runtime_ap.get(); + if (!m_system_runtime_up) + m_system_runtime_up.reset(SystemRuntime::FindPlugin(this)); + return m_system_runtime_up.get(); } Process::AttachCompletionHandler::AttachCompletionHandler(Process *process, @@ -2984,10 +2811,10 @@ Status Process::Attach(ProcessAttachInfo &attach_info) { m_abi_sp.reset(); m_process_input_reader.reset(); - m_dyld_ap.reset(); - m_jit_loaders_ap.reset(); - m_system_runtime_ap.reset(); - m_os_ap.reset(); + m_dyld_up.reset(); + m_jit_loaders_up.reset(); + m_system_runtime_up.reset(); + m_os_up.reset(); lldb::pid_t attach_pid = attach_info.GetProcessID(); Status error; @@ -3045,11 +2872,10 @@ process_name, sizeof(process_name)); if (num_matches > 1) { StreamString s; - ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true, - false); + ProcessInstanceInfo::DumpTableHeader(s, true, false); for (size_t i = 0; i < num_matches; i++) { process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow( - s, platform_sp.get(), true, false); + s, platform_sp->GetUserIDResolver(), true, false); } error.SetErrorStringWithFormat( "more than one process named %s:\n%s", process_name, @@ -3193,8 +3019,16 @@ } } - if (!m_os_ap) + if (!m_os_up) { LoadOperatingSystemPlugin(false); + if (m_os_up) { + // Somebody might have gotten threads before now, but we need to force the + // update after we've loaded the OperatingSystem plugin or it won't get a + // chance to process the threads. + m_thread_list.Clear(); + UpdateThreadListIfNeeded(); + } + } // Figure out which one is the executable, and set that in our target: const ModuleList &target_modules = GetTarget().GetImages(); std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); @@ -3754,14 +3588,20 @@ // Create the private state thread, and start it running. PrivateStateThreadArgs *args_ptr = new PrivateStateThreadArgs(this, is_secondary_thread); - m_private_state_thread = + llvm::Expected<HostThread> private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, - (void *)args_ptr, nullptr, 8 * 1024 * 1024); - if (m_private_state_thread.IsJoinable()) { - ResumePrivateStateThread(); - return true; - } else + (void *)args_ptr, 8 * 1024 * 1024); + if (!private_state_thread) { + LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), + "failed to launch host thread: {}", + llvm::toString(private_state_thread.takeError())); return false; + } + + assert(private_state_thread->IsJoinable()); + m_private_state_thread = *private_state_thread; + ResumePrivateStateThread(); + return true; } void Process::PausePrivateStateThread() { @@ -3810,10 +3650,10 @@ bool receipt_received = false; if (PrivateStateThreadIsValid()) { while (!receipt_received) { - // Check for a receipt for 2 seconds and then check if the private + // Check for a receipt for n seconds and then check if the private // state thread is still around. receipt_received = - event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2)); + event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout()); if (!receipt_received) { // Check if the private state thread is still around. If it isn't // then we are done waiting @@ -3824,7 +3664,7 @@ } if (signal == eBroadcastInternalStateControlStop) { - thread_result_t result = NULL; + thread_result_t result = {}; m_private_state_thread.Join(&result); m_private_state_thread.Reset(); } @@ -3851,9 +3691,9 @@ Process::ProcessEventData::GetStateFromEvent(event_sp.get()); // First check to see if anybody wants a shot at this event: - if (m_next_event_action_ap) { + if (m_next_event_action_up) { NextEventAction::EventActionResult action_result = - m_next_event_action_ap->PerformAction(event_sp); + m_next_event_action_up->PerformAction(event_sp); if (log) log->Printf("Ran next event action, result was %d.", action_result); @@ -3871,7 +3711,7 @@ // to exit so the next event will kill us. if (new_state != eStateExited) { // FIXME: should cons up an exited event, and discard this one. - SetExitStatus(0, m_next_event_action_ap->GetExitString()); + SetExitStatus(0, m_next_event_action_up->GetExitString()); SetNextEventAction(nullptr); return; } @@ -4099,12 +3939,10 @@ // it was doing yet, so don't try to change it on the way out. if (!is_secondary_thread) m_public_run_lock.SetStopped(); - return NULL; + return {}; } -//------------------------------------------------------------------ // Process Event Data -//------------------------------------------------------------------ Process::ProcessEventData::ProcessEventData() : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false), @@ -4120,12 +3958,12 @@ Process::ProcessEventData::~ProcessEventData() = default; -const ConstString &Process::ProcessEventData::GetFlavorString() { +ConstString Process::ProcessEventData::GetFlavorString() { static ConstString g_flavor("Process::ProcessEventData"); return g_flavor; } -const ConstString &Process::ProcessEventData::GetFlavor() const { +ConstString Process::ProcessEventData::GetFlavor() const { return ProcessEventData::GetFlavorString(); } @@ -4260,15 +4098,24 @@ // public resume. process_sp->PrivateResume(); } else { - // If we didn't restart, run the Stop Hooks here: They might also - // restart the target, so watch for that. - process_sp->GetTarget().RunStopHooks(); - if (process_sp->GetPrivateState() == eStateRunning) - SetRestarted(true); + bool hijacked = + process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) && + !process_sp->StateChangedIsHijackedForSynchronousResume(); + + if (!hijacked) { + // If we didn't restart, run the Stop Hooks here. + // Don't do that if state changed events aren't hooked up to the + // public (or SyncResume) broadcasters. StopHooks are just for + // real public stops. They might also restart the target, + // so watch for that. + process_sp->GetTarget().RunStopHooks(); + if (process_sp->GetPrivateState() == eStateRunning) + SetRestarted(true); } } } } +} void Process::ProcessEventData::Dump(Stream *s) const { ProcessSP process_sp(m_process_wp.lock()); @@ -4439,7 +4286,7 @@ } StructuredDataPluginSP -Process::GetStructuredDataPlugin(const ConstString &type_name) const { +Process::GetStructuredDataPlugin(ConstString type_name) const { auto find_it = m_structured_data_plugin_map.find(type_name); if (find_it != m_structured_data_plugin_map.end()) return find_it->second; @@ -4471,9 +4318,7 @@ return bytes_available; } -//------------------------------------------------------------------ // Process STDIO -//------------------------------------------------------------------ size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) { std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); @@ -4658,11 +4503,11 @@ void Process::SetSTDIOFileDescriptor(int fd) { // First set up the Read Thread for reading/handling process I/O - std::unique_ptr<ConnectionFileDescriptor> conn_ap( + std::unique_ptr<ConnectionFileDescriptor> conn_up( new ConnectionFileDescriptor(fd, true)); - if (conn_ap) { - m_stdio_communication.SetConnection(conn_ap.release()); + if (conn_up) { + m_stdio_communication.SetConnection(conn_up.release()); if (m_stdio_communication.IsConnected()) { m_stdio_communication.SetReadThreadBytesReceivedCallback( STDIOReadThreadBytesReceived, this); @@ -4671,7 +4516,8 @@ // Now read thread is set up, set up input reader. if (!m_process_input_reader) - m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd)); + m_process_input_reader = + std::make_shared<IOHandlerProcessSTDIO>(this, fd); } } } @@ -5096,7 +4942,7 @@ } got_event = - listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500)); + listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); if (!got_event) { if (log) log->Printf("Process::RunThreadPlan(): didn't get any event after " @@ -5327,7 +5173,7 @@ log->PutCString("Process::RunThreadPlan(): Halt succeeded."); got_event = - listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500)); + listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); if (got_event) { stop_state = @@ -5530,7 +5376,7 @@ event_explanation = ts.GetData(); } - } while (0); + } while (false); if (event_explanation) log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", @@ -5782,15 +5628,18 @@ Target &target = GetTarget(); target.CleanupProcess(); target.ClearModules(false); - m_dynamic_checkers_ap.reset(); + m_dynamic_checkers_up.reset(); m_abi_sp.reset(); - m_system_runtime_ap.reset(); - m_os_ap.reset(); - m_dyld_ap.reset(); - m_jit_loaders_ap.reset(); + m_system_runtime_up.reset(); + m_os_up.reset(); + m_dyld_up.reset(); + m_jit_loaders_up.reset(); m_image_tokens.clear(); m_allocated_memory_cache.Clear(); - m_language_runtimes.clear(); + { + std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); + m_language_runtimes.clear(); + } m_instrumentation_runtimes.clear(); m_thread_list.DiscardThreadPlans(); m_memory_cache.Clear(true); @@ -5859,19 +5708,22 @@ // Iterate over a copy of this language runtime list in case the language // runtime ModulesDidLoad somehow causes the language runtime to be // unloaded. - LanguageRuntimeCollection language_runtimes(m_language_runtimes); - for (const auto &pair : language_runtimes) { - // We must check language_runtime_sp to make sure it is not nullptr as we - // might cache the fact that we didn't have a language runtime for a - // language. - LanguageRuntimeSP language_runtime_sp = pair.second; - if (language_runtime_sp) - language_runtime_sp->ModulesDidLoad(module_list); + { + std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); + LanguageRuntimeCollection language_runtimes(m_language_runtimes); + for (const auto &pair : language_runtimes) { + // We must check language_runtime_sp to make sure it is not nullptr as we + // might cache the fact that we didn't have a language runtime for a + // language. + LanguageRuntimeSP language_runtime_sp = pair.second; + if (language_runtime_sp) + language_runtime_sp->ModulesDidLoad(module_list); + } } // If we don't have an operating system plug-in, try to load one since // loading shared libraries might cause a new one to try and load - if (!m_os_ap) + if (!m_os_up) LoadOperatingSystemPlugin(false); // Give structured-data plugins a chance to see the modified modules. @@ -5945,7 +5797,8 @@ return threads; } - threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr))); + threads = std::make_shared<ThreadCollection>( + memory_history->GetHistoryThreads(addr)); return threads; } @@ -6017,7 +5870,8 @@ } uint32_t branch_index = - insn_list->GetIndexOfNextBranchInstruction(insn_offset, target); + insn_list->GetIndexOfNextBranchInstruction(insn_offset, target, + false /* ignore_calls*/); if (branch_index == UINT32_MAX) { return retval; } @@ -6061,7 +5915,7 @@ } Status -Process::ConfigureStructuredData(const ConstString &type_name, +Process::ConfigureStructuredData(ConstString type_name, const StructuredData::ObjectSP &config_sp) { // If you get this, the Process-derived class needs to implement a method to // enable an already-reported asynchronous structured data feature. See
diff --git a/src/llvm-project/lldb/source/Target/ProcessInfo.cpp b/src/llvm-project/lldb/source/Target/ProcessInfo.cpp deleted file mode 100644 index 1ada612..0000000 --- a/src/llvm-project/lldb/source/Target/ProcessInfo.cpp +++ /dev/null
@@ -1,114 +0,0 @@ -//===-- ProcessInfo.cpp -----------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "lldb/Target/ProcessInfo.h" - -#include <climits> - -#include "lldb/Host/PosixApi.h" -#include "lldb/Utility/Stream.h" - -#include "llvm/ADT/SmallString.h" - -using namespace lldb; -using namespace lldb_private; - -ProcessInfo::ProcessInfo() - : m_executable(), m_arguments(), m_environment(), m_uid(UINT32_MAX), - m_gid(UINT32_MAX), m_arch(), m_pid(LLDB_INVALID_PROCESS_ID) {} - -ProcessInfo::ProcessInfo(const char *name, const ArchSpec &arch, - lldb::pid_t pid) - : m_executable(name), m_arguments(), m_environment(), m_uid(UINT32_MAX), - m_gid(UINT32_MAX), m_arch(arch), m_pid(pid) {} - -void ProcessInfo::Clear() { - m_executable.Clear(); - m_arguments.Clear(); - m_environment.clear(); - m_uid = UINT32_MAX; - m_gid = UINT32_MAX; - m_arch.Clear(); - m_pid = LLDB_INVALID_PROCESS_ID; -} - -const char *ProcessInfo::GetName() const { - return m_executable.GetFilename().GetCString(); -} - -size_t ProcessInfo::GetNameLength() const { - return m_executable.GetFilename().GetLength(); -} - -void ProcessInfo::Dump(Stream &s, Platform *platform) const { - s << "Executable: " << GetName() << "\n"; - s << "Triple: "; - m_arch.DumpTriple(s); - s << "\n"; - - s << "Arguments:\n"; - m_arguments.Dump(s); - - s.Format("Environment:\n{0}", m_environment); -} - -void ProcessInfo::SetExecutableFile(const FileSpec &exe_file, - bool add_exe_file_as_first_arg) { - if (exe_file) { - m_executable = exe_file; - if (add_exe_file_as_first_arg) { - llvm::SmallString<128> filename; - exe_file.GetPath(filename); - if (!filename.empty()) - m_arguments.InsertArgumentAtIndex(0, filename); - } - } else { - m_executable.Clear(); - } -} - -llvm::StringRef ProcessInfo::GetArg0() const { - return m_arg0; -} - -void ProcessInfo::SetArg0(llvm::StringRef arg) { - m_arg0 = arg; -} - -void ProcessInfo::SetArguments(char const **argv, - bool first_arg_is_executable) { - m_arguments.SetArguments(argv); - - // Is the first argument the executable? - if (first_arg_is_executable) { - const char *first_arg = m_arguments.GetArgumentAtIndex(0); - if (first_arg) { - // Yes the first argument is an executable, set it as the executable in - // the launch options. Don't resolve the file path as the path could be a - // remote platform path - m_executable.SetFile(first_arg, FileSpec::Style::native); - } - } -} - -void ProcessInfo::SetArguments(const Args &args, bool first_arg_is_executable) { - // Copy all arguments - m_arguments = args; - - // Is the first argument the executable? - if (first_arg_is_executable) { - const char *first_arg = m_arguments.GetArgumentAtIndex(0); - if (first_arg) { - // Yes the first argument is an executable, set it as the executable in - // the launch options. Don't resolve the file path as the path could be a - // remote platform path - m_executable.SetFile(first_arg, FileSpec::Style::native); - } - } -}
diff --git a/src/llvm-project/lldb/source/Target/Queue.cpp b/src/llvm-project/lldb/source/Target/Queue.cpp index c0683d1..fc2a93d 100644 --- a/src/llvm-project/lldb/source/Target/Queue.cpp +++ b/src/llvm-project/lldb/source/Target/Queue.cpp
@@ -1,9 +1,8 @@ //===-- Queue.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/QueueItem.cpp b/src/llvm-project/lldb/source/Target/QueueItem.cpp index a20fa91..47ff9e0 100644 --- a/src/llvm-project/lldb/source/Target/QueueItem.cpp +++ b/src/llvm-project/lldb/source/Target/QueueItem.cpp
@@ -1,9 +1,8 @@ //===-- QueueItem.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/QueueList.cpp b/src/llvm-project/lldb/source/Target/QueueList.cpp index ae9e7b9..7968251 100644 --- a/src/llvm-project/lldb/source/Target/QueueList.cpp +++ b/src/llvm-project/lldb/source/Target/QueueList.cpp
@@ -1,9 +1,8 @@ //===-- QueueList.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/RegisterContext.cpp b/src/llvm-project/lldb/source/Target/RegisterContext.cpp index 976f9e8..c960260 100644 --- a/src/llvm-project/lldb/source/Target/RegisterContext.cpp +++ b/src/llvm-project/lldb/source/Target/RegisterContext.cpp
@@ -1,9 +1,8 @@ //===-- RegisterContext.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/RegisterNumber.cpp b/src/llvm-project/lldb/source/Target/RegisterNumber.cpp index 8b01bd1..63b58d3 100644 --- a/src/llvm-project/lldb/source/Target/RegisterNumber.cpp +++ b/src/llvm-project/lldb/source/Target/RegisterNumber.cpp
@@ -1,9 +1,8 @@ //===--------------------- RegisterNumber.cpp -------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/RemoteAwarePlatform.cpp b/src/llvm-project/lldb/source/Target/RemoteAwarePlatform.cpp new file mode 100644 index 0000000..1704e15 --- /dev/null +++ b/src/llvm-project/lldb/source/Target/RemoteAwarePlatform.cpp
@@ -0,0 +1,284 @@ +//===-- RemoteAwarePlatform.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/Target/RemoteAwarePlatform.h" +#include "lldb/Host/FileCache.h" +#include "lldb/Host/FileSystem.h" +#include "lldb/Host/Host.h" +#include "lldb/Host/HostInfo.h" + +using namespace lldb_private; + +bool RemoteAwarePlatform::GetModuleSpec(const FileSpec &module_file_spec, + const ArchSpec &arch, + ModuleSpec &module_spec) { + if (m_remote_platform_sp) + return m_remote_platform_sp->GetModuleSpec(module_file_spec, arch, + module_spec); + + return Platform::GetModuleSpec(module_file_spec, arch, module_spec); +} + +Status RemoteAwarePlatform::RunShellCommand( + const char *command, const FileSpec &working_dir, int *status_ptr, + int *signo_ptr, std::string *command_output, + const Timeout<std::micro> &timeout) { + if (IsHost()) + return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr, + command_output, timeout); + if (m_remote_platform_sp) + return m_remote_platform_sp->RunShellCommand( + command, working_dir, status_ptr, signo_ptr, command_output, timeout); + return Status("unable to run a remote command without a platform"); +} + +Status RemoteAwarePlatform::MakeDirectory(const FileSpec &file_spec, + uint32_t file_permissions) { + if (m_remote_platform_sp) + return m_remote_platform_sp->MakeDirectory(file_spec, file_permissions); + return Platform::MakeDirectory(file_spec, file_permissions); +} + +Status RemoteAwarePlatform::GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions) { + if (m_remote_platform_sp) + return m_remote_platform_sp->GetFilePermissions(file_spec, + file_permissions); + return Platform::GetFilePermissions(file_spec, file_permissions); +} + +Status RemoteAwarePlatform::SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions) { + if (m_remote_platform_sp) + return m_remote_platform_sp->SetFilePermissions(file_spec, + file_permissions); + return Platform::SetFilePermissions(file_spec, file_permissions); +} + +lldb::user_id_t RemoteAwarePlatform::OpenFile(const FileSpec &file_spec, + uint32_t flags, uint32_t mode, + Status &error) { + if (IsHost()) + return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error); + if (m_remote_platform_sp) + return m_remote_platform_sp->OpenFile(file_spec, flags, mode, error); + return Platform::OpenFile(file_spec, flags, mode, error); +} + +bool RemoteAwarePlatform::CloseFile(lldb::user_id_t fd, Status &error) { + if (IsHost()) + return FileCache::GetInstance().CloseFile(fd, error); + if (m_remote_platform_sp) + return m_remote_platform_sp->CloseFile(fd, error); + return Platform::CloseFile(fd, error); +} + +uint64_t RemoteAwarePlatform::ReadFile(lldb::user_id_t fd, uint64_t offset, + void *dst, uint64_t dst_len, + Status &error) { + if (IsHost()) + return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error); + if (m_remote_platform_sp) + return m_remote_platform_sp->ReadFile(fd, offset, dst, dst_len, error); + return Platform::ReadFile(fd, offset, dst, dst_len, error); +} + +uint64_t RemoteAwarePlatform::WriteFile(lldb::user_id_t fd, uint64_t offset, + const void *src, uint64_t src_len, + Status &error) { + if (IsHost()) + return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error); + if (m_remote_platform_sp) + return m_remote_platform_sp->WriteFile(fd, offset, src, src_len, error); + return Platform::WriteFile(fd, offset, src, src_len, error); +} + +lldb::user_id_t RemoteAwarePlatform::GetFileSize(const FileSpec &file_spec) { + if (IsHost()) { + uint64_t Size; + if (llvm::sys::fs::file_size(file_spec.GetPath(), Size)) + return 0; + return Size; + } + if (m_remote_platform_sp) + return m_remote_platform_sp->GetFileSize(file_spec); + return Platform::GetFileSize(file_spec); +} + +Status RemoteAwarePlatform::CreateSymlink(const FileSpec &src, + const FileSpec &dst) { + if (IsHost()) + return FileSystem::Instance().Symlink(src, dst); + if (m_remote_platform_sp) + return m_remote_platform_sp->CreateSymlink(src, dst); + return Platform::CreateSymlink(src, dst); +} + +bool RemoteAwarePlatform::GetFileExists(const FileSpec &file_spec) { + if (IsHost()) + return FileSystem::Instance().Exists(file_spec); + if (m_remote_platform_sp) + return m_remote_platform_sp->GetFileExists(file_spec); + return Platform::GetFileExists(file_spec); +} + +Status RemoteAwarePlatform::Unlink(const FileSpec &file_spec) { + if (IsHost()) + return llvm::sys::fs::remove(file_spec.GetPath()); + if (m_remote_platform_sp) + return m_remote_platform_sp->Unlink(file_spec); + return Platform::Unlink(file_spec); +} + +bool RemoteAwarePlatform::CalculateMD5(const FileSpec &file_spec, uint64_t &low, + uint64_t &high) { + if (IsHost()) + return Platform::CalculateMD5(file_spec, low, high); + if (m_remote_platform_sp) + return m_remote_platform_sp->CalculateMD5(file_spec, low, high); + return false; +} + +FileSpec RemoteAwarePlatform::GetRemoteWorkingDirectory() { + if (IsRemote() && m_remote_platform_sp) + return m_remote_platform_sp->GetRemoteWorkingDirectory(); + return Platform::GetRemoteWorkingDirectory(); +} + +bool RemoteAwarePlatform::SetRemoteWorkingDirectory( + const FileSpec &working_dir) { + if (IsRemote() && m_remote_platform_sp) + return m_remote_platform_sp->SetRemoteWorkingDirectory(working_dir); + return Platform::SetRemoteWorkingDirectory(working_dir); +} + +Status RemoteAwarePlatform::GetFileWithUUID(const FileSpec &platform_file, + const UUID *uuid_ptr, + FileSpec &local_file) { + if (IsRemote() && m_remote_platform_sp) + return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr, + local_file); + + // Default to the local case + local_file = platform_file; + return Status(); +} + +bool RemoteAwarePlatform::GetRemoteOSVersion() { + if (m_remote_platform_sp) { + m_os_version = m_remote_platform_sp->GetOSVersion(); + return !m_os_version.empty(); + } + return false; +} + +bool RemoteAwarePlatform::GetRemoteOSBuildString(std::string &s) { + if (m_remote_platform_sp) + return m_remote_platform_sp->GetRemoteOSBuildString(s); + s.clear(); + return false; +} + +bool RemoteAwarePlatform::GetRemoteOSKernelDescription(std::string &s) { + if (m_remote_platform_sp) + return m_remote_platform_sp->GetRemoteOSKernelDescription(s); + s.clear(); + return false; +} + +ArchSpec RemoteAwarePlatform::GetRemoteSystemArchitecture() { + if (m_remote_platform_sp) + return m_remote_platform_sp->GetRemoteSystemArchitecture(); + return ArchSpec(); +} + +const char *RemoteAwarePlatform::GetHostname() { + if (IsHost()) + return Platform::GetHostname(); + if (m_remote_platform_sp) + return m_remote_platform_sp->GetHostname(); + return nullptr; +} + +UserIDResolver &RemoteAwarePlatform::GetUserIDResolver() { + if (IsHost()) + return HostInfo::GetUserIDResolver(); + if (m_remote_platform_sp) + return m_remote_platform_sp->GetUserIDResolver(); + return UserIDResolver::GetNoopResolver(); +} + +Environment RemoteAwarePlatform::GetEnvironment() { + if (IsRemote()) { + if (m_remote_platform_sp) + return m_remote_platform_sp->GetEnvironment(); + return Environment(); + } + return Host::GetEnvironment(); +} + +bool RemoteAwarePlatform::IsConnected() const { + if (IsHost()) + return true; + else if (m_remote_platform_sp) + return m_remote_platform_sp->IsConnected(); + return false; +} + +bool RemoteAwarePlatform::GetProcessInfo(lldb::pid_t pid, + ProcessInstanceInfo &process_info) { + if (IsHost()) + return Platform::GetProcessInfo(pid, process_info); + if (m_remote_platform_sp) + return m_remote_platform_sp->GetProcessInfo(pid, process_info); + return false; +} + +uint32_t +RemoteAwarePlatform::FindProcesses(const ProcessInstanceInfoMatch &match_info, + ProcessInstanceInfoList &process_infos) { + if (IsHost()) + return Platform::FindProcesses(match_info, process_infos); + if (m_remote_platform_sp) + return m_remote_platform_sp->FindProcesses(match_info, process_infos); + return 0; +} + +lldb::ProcessSP RemoteAwarePlatform::ConnectProcess(llvm::StringRef connect_url, + llvm::StringRef plugin_name, + Debugger &debugger, + Target *target, + Status &error) { + if (m_remote_platform_sp) + return m_remote_platform_sp->ConnectProcess(connect_url, plugin_name, + debugger, target, error); + return Platform::ConnectProcess(connect_url, plugin_name, debugger, target, + error); +} + +Status RemoteAwarePlatform::LaunchProcess(ProcessLaunchInfo &launch_info) { + Status error; + + if (IsHost()) { + error = Platform::LaunchProcess(launch_info); + } else { + if (m_remote_platform_sp) + error = m_remote_platform_sp->LaunchProcess(launch_info); + else + error.SetErrorString("the platform is not currently connected"); + } + return error; +} + +Status RemoteAwarePlatform::KillProcess(const lldb::pid_t pid) { + if (IsHost()) + return Platform::KillProcess(pid); + if (m_remote_platform_sp) + return m_remote_platform_sp->KillProcess(pid); + return Status("the platform is not currently connected"); +}
diff --git a/src/llvm-project/lldb/source/Target/SectionLoadHistory.cpp b/src/llvm-project/lldb/source/Target/SectionLoadHistory.cpp index 1229933..ec16b58 100644 --- a/src/llvm-project/lldb/source/Target/SectionLoadHistory.cpp +++ b/src/llvm-project/lldb/source/Target/SectionLoadHistory.cpp
@@ -1,9 +1,8 @@ //===-- SectionLoadHistory.cpp ----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -81,7 +80,7 @@ StopIDToSectionLoadList::reverse_iterator rpos = m_stop_id_to_section_load_list.rbegin(); SectionLoadListSP section_load_list_sp( - new SectionLoadList(*rpos->second.get())); + new SectionLoadList(*rpos->second)); m_stop_id_to_section_load_list[stop_id] = section_load_list_sp; return section_load_list_sp.get(); } @@ -98,7 +97,7 @@ std::lock_guard<std::recursive_mutex> guard(m_mutex); SectionLoadList *section_load_list = GetSectionLoadListForStopID(eStopIDNow, read_only); - assert(section_load_list != NULL); + assert(section_load_list != nullptr); return *section_load_list; }
diff --git a/src/llvm-project/lldb/source/Target/SectionLoadList.cpp b/src/llvm-project/lldb/source/Target/SectionLoadList.cpp index ea9f7ea..598f49c 100644 --- a/src/llvm-project/lldb/source/Target/SectionLoadList.cpp +++ b/src/llvm-project/lldb/source/Target/SectionLoadList.cpp
@@ -1,9 +1,8 @@ //===-- SectionLoadList.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,8 +27,9 @@ } void SectionLoadList::operator=(const SectionLoadList &rhs) { - std::lock_guard<std::recursive_mutex> lhs_guard(m_mutex); - std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_mutex); + std::lock(m_mutex, rhs.m_mutex); + std::lock_guard<std::recursive_mutex> lhs_guard(m_mutex, std::adopt_lock); + std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_mutex, std::adopt_lock); m_addr_to_sect = rhs.m_addr_to_sect; m_sect_to_addr = rhs.m_sect_to_addr; }
diff --git a/src/llvm-project/lldb/source/Target/StackFrame.cpp b/src/llvm-project/lldb/source/Target/StackFrame.cpp index 3cea644..f8b22d9 100644 --- a/src/llvm-project/lldb/source/Target/StackFrame.cpp +++ b/src/llvm-project/lldb/source/Target/StackFrame.cpp
@@ -1,9 +1,8 @@ //===-- StackFrame.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -34,6 +33,8 @@ #include "lldb/lldb-enumerations.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -258,12 +259,10 @@ return nullptr; } -//---------------------------------------------------------------------- // Get the symbol context if we already haven't done so by resolving the // PC address as much as possible. This way when we pass around a // StackFrame object, everyone will have as much information as possible and no // one will ever have to look things up manually. -//---------------------------------------------------------------------- const SymbolContext & StackFrame::GetSymbolContext(SymbolContextItem resolve_scope) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -423,7 +422,7 @@ const bool get_child_variables = true; const bool can_create = true; const bool stop_if_child_block_is_inlined_function = true; - m_variable_list_sp.reset(new VariableList()); + m_variable_list_sp = std::make_shared<VariableList>(); frame_block->AppendBlockVariables(can_create, get_child_variables, stop_if_child_block_is_inlined_function, [](Variable *v) { return true; }, @@ -641,7 +640,12 @@ valobj_sp = valobj_sp->Dereference(deref_error); if (error.Fail()) { error.SetErrorStringWithFormatv( - "Failed to dereference sythetic value: %s", deref_error); + "Failed to dereference sythetic value: {0}", deref_error); + return ValueObjectSP(); + } + // Some synthetic plug-ins fail to set the error in Dereference + if (!valobj_sp) { + error.SetErrorString("Failed to dereference sythetic value"); return ValueObjectSP(); } expr_is_ptr = false; @@ -1174,7 +1178,7 @@ VariableList *var_list = GetVariableList(true); // If this frame has no variables, create a new list if (var_list == nullptr) - m_variable_list_sp.reset(new VariableList()); + m_variable_list_sp = std::make_shared<VariableList>(); // Add the global/static variable to this frame m_variable_list_sp->AddVariable(variable_sp); @@ -1447,33 +1451,31 @@ return GetValueForOffset(frame, pointee, offset); } -//------------------------------------------------------------------ /// Attempt to reconstruct the ValueObject for the address contained in a /// given register plus an offset. /// -/// @params [in] frame +/// \params [in] frame /// The current stack frame. /// -/// @params [in] reg +/// \params [in] reg /// The register. /// -/// @params [in] offset +/// \params [in] offset /// The offset from the register. /// -/// @param [in] disassembler +/// \param [in] disassembler /// A disassembler containing instructions valid up to the current PC. /// -/// @param [in] variables +/// \param [in] variables /// The variable list from the current frame, /// -/// @param [in] pc +/// \param [in] pc /// The program counter for the instruction considered the 'user'. /// -/// @return +/// \return /// A string describing the base for the ExpressionPath. This could be a /// variable, a register value, an argument, or a function return value. /// The ValueObject if found. If valid, it has a valid ExpressionPath. -//------------------------------------------------------------------ lldb::ValueObjectSP DoGuessValueAt(StackFrame &frame, ConstString reg, int64_t offset, Disassembler &disassembler, VariableList &variables, const Address &pc) {
diff --git a/src/llvm-project/lldb/source/Target/StackFrameList.cpp b/src/llvm-project/lldb/source/Target/StackFrameList.cpp index fc9fcec..5492dda 100644 --- a/src/llvm-project/lldb/source/Target/StackFrameList.cpp +++ b/src/llvm-project/lldb/source/Target/StackFrameList.cpp
@@ -1,9 +1,8 @@ //===-- StackFrameList.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,14 +24,14 @@ #include "lldb/Utility/Log.h" #include "llvm/ADT/SmallPtrSet.h" +#include <memory> + //#define DEBUG_STACK_FRAMES 1 using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // StackFrameList constructor -//---------------------------------------------------------------------- StackFrameList::StackFrameList(Thread &thread, const lldb::StackFrameListSP &prev_frames_sp, bool show_inline_frames) @@ -466,9 +465,9 @@ pc = reg_ctx_sp->GetPC(); } - unwind_frame_sp.reset(new StackFrame(m_thread.shared_from_this(), - m_frames.size(), idx, reg_ctx_sp, - cfa, pc, nullptr)); + unwind_frame_sp = std::make_shared<StackFrame>( + m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp, + cfa, pc, nullptr); m_frames.push_back(unwind_frame_sp); } } else { @@ -484,9 +483,9 @@ break; } const bool cfa_is_valid = true; - unwind_frame_sp.reset( - new StackFrame(m_thread.shared_from_this(), m_frames.size(), idx, cfa, - cfa_is_valid, pc, StackFrame::Kind::Regular, nullptr)); + unwind_frame_sp = std::make_shared<StackFrame>( + m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid, + pc, StackFrame::Kind::Regular, nullptr); // Create synthetic tail call frames between the previous frame and the // newly-found frame. The new frame's index may change after this call, @@ -664,9 +663,9 @@ addr_t pc, cfa; if (unwinder->GetFrameInfoAtIndex(idx, cfa, pc)) { const bool cfa_is_valid = true; - frame_sp.reset(new StackFrame(m_thread.shared_from_this(), idx, idx, - cfa, cfa_is_valid, pc, - StackFrame::Kind::Regular, nullptr)); + frame_sp = std::make_shared<StackFrame>( + m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc, + StackFrame::Kind::Regular, nullptr); Function *function = frame_sp->GetSymbolContext(eSymbolContextFunction).function; @@ -818,11 +817,11 @@ m_concrete_frames_fetched = 0; } -void StackFrameList::Merge(std::unique_ptr<StackFrameList> &curr_ap, +void StackFrameList::Merge(std::unique_ptr<StackFrameList> &curr_up, lldb::StackFrameListSP &prev_sp) { std::unique_lock<std::recursive_mutex> current_lock, previous_lock; - if (curr_ap) - current_lock = std::unique_lock<std::recursive_mutex>(curr_ap->m_mutex); + if (curr_up) + current_lock = std::unique_lock<std::recursive_mutex>(curr_up->m_mutex); if (prev_sp) previous_lock = std::unique_lock<std::recursive_mutex>(prev_sp->m_mutex); @@ -834,18 +833,18 @@ else s.PutCString("NULL"); s.PutCString("\nCurr:\n"); - if (curr_ap) - curr_ap->Dump(&s); + if (curr_up) + curr_up->Dump(&s); else s.PutCString("NULL"); s.EOL(); #endif - if (!curr_ap || curr_ap->GetNumFrames(false) == 0) { + if (!curr_up || curr_up->GetNumFrames(false) == 0) { #if defined(DEBUG_STACK_FRAMES) s.PutCString("No current frames, leave previous frames alone...\n"); #endif - curr_ap.release(); + curr_up.release(); return; } @@ -856,11 +855,11 @@ // We either don't have any previous frames, or since we have more than one // current frames it means we have all the frames and can safely replace // our previous frames. - prev_sp.reset(curr_ap.release()); + prev_sp.reset(curr_up.release()); return; } - const uint32_t num_curr_frames = curr_ap->GetNumFrames(false); + const uint32_t num_curr_frames = curr_up->GetNumFrames(false); if (num_curr_frames > 1) { #if defined(DEBUG_STACK_FRAMES) @@ -869,7 +868,7 @@ #endif // We have more than one current frames it means we have all the frames and // can safely replace our previous frames. - prev_sp.reset(curr_ap.release()); + prev_sp.reset(curr_up.release()); #if defined(DEBUG_STACK_FRAMES) s.PutCString("\nMerged:\n"); @@ -879,7 +878,7 @@ } StackFrameSP prev_frame_zero_sp(prev_sp->GetFrameAtIndex(0)); - StackFrameSP curr_frame_zero_sp(curr_ap->GetFrameAtIndex(0)); + StackFrameSP curr_frame_zero_sp(curr_up->GetFrameAtIndex(0)); StackID curr_stack_id(curr_frame_zero_sp->GetStackID()); StackID prev_stack_id(prev_frame_zero_sp->GetStackID()); @@ -909,7 +908,7 @@ prev_sp->m_frames.insert(prev_sp->m_frames.begin(), curr_frame_zero_sp); } - curr_ap.release(); + curr_up.release(); #if defined(DEBUG_STACK_FRAMES) s.PutCString("\nMerged:\n");
diff --git a/src/llvm-project/lldb/source/Target/StackFrameRecognizer.cpp b/src/llvm-project/lldb/source/Target/StackFrameRecognizer.cpp index 152f4a1..567d694 100644 --- a/src/llvm-project/lldb/source/Target/StackFrameRecognizer.cpp +++ b/src/llvm-project/lldb/source/Target/StackFrameRecognizer.cpp
@@ -1,9 +1,8 @@ //===-- StackFrameRecognizer.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,8 +17,6 @@ using namespace lldb; using namespace lldb_private; -#ifndef LLDB_DISABLE_PYTHON - class ScriptedRecognizedStackFrame : public RecognizedStackFrame { public: ScriptedRecognizedStackFrame(ValueObjectListSP args) { @@ -41,16 +38,20 @@ ValueObjectListSP args = m_interpreter->GetRecognizedArguments(m_python_object_sp, frame); + auto args_synthesized = ValueObjectListSP(new ValueObjectList()); + for (const auto o : args->GetObjects()) { + args_synthesized->Append(ValueObjectRecognizerSynthesizedValue::Create( + *o, eValueTypeVariableArgument)); + } - return RecognizedStackFrameSP(new ScriptedRecognizedStackFrame(args)); + return RecognizedStackFrameSP( + new ScriptedRecognizedStackFrame(args_synthesized)); } -#endif - class StackFrameRecognizerManagerImpl { public: void AddRecognizer(StackFrameRecognizerSP recognizer, - const ConstString &module, const ConstString &symbol, + ConstString module, ConstString symbol, bool first_instruction_only) { m_recognizers.push_front({(uint32_t)m_recognizers.size(), false, recognizer, false, module, RegularExpressionSP(), symbol, RegularExpressionSP(), @@ -153,8 +154,8 @@ } void StackFrameRecognizerManager::AddRecognizer( - StackFrameRecognizerSP recognizer, const ConstString &module, - const ConstString &symbol, bool first_instruction_only) { + StackFrameRecognizerSP recognizer, ConstString module, + ConstString symbol, bool first_instruction_only) { GetStackFrameRecognizerManagerImpl().AddRecognizer(recognizer, module, symbol, first_instruction_only); }
diff --git a/src/llvm-project/lldb/source/Target/StackID.cpp b/src/llvm-project/lldb/source/Target/StackID.cpp index d6640b2..a8f6b78 100644 --- a/src/llvm-project/lldb/source/Target/StackID.cpp +++ b/src/llvm-project/lldb/source/Target/StackID.cpp
@@ -1,9 +1,8 @@ //===-- StackID.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Target/StopInfo.cpp b/src/llvm-project/lldb/source/Target/StopInfo.cpp index 4e13c58..6db0c2b 100644 --- a/src/llvm-project/lldb/source/Target/StopInfo.cpp +++ b/src/llvm-project/lldb/source/Target/StopInfo.cpp
@@ -1,9 +1,8 @@ //===-- StopInfo.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -79,9 +78,7 @@ return false; } -//---------------------------------------------------------------------- // StopInfoBreakpoint -//---------------------------------------------------------------------- namespace lldb_private { class StopInfoBreakpoint : public StopInfo { @@ -576,9 +573,7 @@ bool m_was_one_shot; }; -//---------------------------------------------------------------------- // StopInfoWatchpoint -//---------------------------------------------------------------------- class StopInfoWatchpoint : public StopInfo { public: @@ -913,9 +908,7 @@ lldb::addr_t m_watch_hit_addr; }; -//---------------------------------------------------------------------- // StopInfoUnixSignal -//---------------------------------------------------------------------- class StopInfoUnixSignal : public StopInfo { public: @@ -990,9 +983,7 @@ } }; -//---------------------------------------------------------------------- // StopInfoTrace -//---------------------------------------------------------------------- class StopInfoTrace : public StopInfo { public: @@ -1010,9 +1001,7 @@ } }; -//---------------------------------------------------------------------- // StopInfoException -//---------------------------------------------------------------------- class StopInfoException : public StopInfo { public: @@ -1034,9 +1023,7 @@ } }; -//---------------------------------------------------------------------- // StopInfoThreadPlan -//---------------------------------------------------------------------- class StopInfoThreadPlan : public StopInfo { public: @@ -1079,9 +1066,7 @@ ExpressionVariableSP m_expression_variable_sp; }; -//---------------------------------------------------------------------- // StopInfoExec -//---------------------------------------------------------------------- class StopInfoExec : public StopInfo { public: @@ -1211,7 +1196,7 @@ address_loc += (sizeof(address_string) - 1); - uint64_t address = strtoull(address_loc, 0, 0); + uint64_t address = strtoull(address_loc, nullptr, 0); if (crashing_address) { *crashing_address = address; }
diff --git a/src/llvm-project/lldb/source/Target/StructuredDataPlugin.cpp b/src/llvm-project/lldb/source/Target/StructuredDataPlugin.cpp index fe267e5..a22902d 100644 --- a/src/llvm-project/lldb/source/Target/StructuredDataPlugin.cpp +++ b/src/llvm-project/lldb/source/Target/StructuredDataPlugin.cpp
@@ -1,9 +1,8 @@ //===-- StructuredDataPlugin.cpp --------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,7 +23,7 @@ "Parent for per-plugin structured data commands", "plugin structured-data <plugin>") {} - ~CommandStructuredData() {} + ~CommandStructuredData() override {} }; } @@ -33,7 +32,7 @@ StructuredDataPlugin::~StructuredDataPlugin() {} -bool StructuredDataPlugin::GetEnabled(const ConstString &type_name) const { +bool StructuredDataPlugin::GetEnabled(ConstString type_name) const { // By default, plugins are always enabled. Plugin authors should override // this if there is an enabled/disabled state for their plugin. return true;
diff --git a/src/llvm-project/lldb/source/Target/SystemRuntime.cpp b/src/llvm-project/lldb/source/Target/SystemRuntime.cpp index 574c01c..286bea0 100644 --- a/src/llvm-project/lldb/source/Target/SystemRuntime.cpp +++ b/src/llvm-project/lldb/source/Target/SystemRuntime.cpp
@@ -1,9 +1,8 @@ //===-- SystemRuntime.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -21,16 +20,14 @@ (create_callback = PluginManager::GetSystemRuntimeCreateCallbackAtIndex( idx)) != nullptr; ++idx) { - std::unique_ptr<SystemRuntime> instance_ap(create_callback(process)); - if (instance_ap) - return instance_ap.release(); + std::unique_ptr<SystemRuntime> instance_up(create_callback(process)); + if (instance_up) + return instance_up.release(); } return nullptr; } -//---------------------------------------------------------------------- // SystemRuntime constructor -//---------------------------------------------------------------------- SystemRuntime::SystemRuntime(Process *process) : m_process(process), m_types() {}
diff --git a/src/llvm-project/lldb/source/Target/Target.cpp b/src/llvm-project/lldb/source/Target/Target.cpp index 437f92a..4941cb5 100644 --- a/src/llvm-project/lldb/source/Target/Target.cpp +++ b/src/llvm-project/lldb/source/Target/Target.cpp
@@ -1,17 +1,15 @@ //===-- Target.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Target.h" -#include "Plugins/ExpressionParser/Clang/ClangASTSource.h" #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h" -#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "lldb/Breakpoint/BreakpointIDList.h" +#include "lldb/Breakpoint/BreakpointPrecondition.h" #include "lldb/Breakpoint/BreakpointResolver.h" #include "lldb/Breakpoint/BreakpointResolverAddress.h" #include "lldb/Breakpoint/BreakpointResolverFileLine.h" @@ -39,12 +37,12 @@ #include "lldb/Interpreter/OptionValues.h" #include "lldb/Interpreter/Property.h" #include "lldb/Symbol/ClangASTContext.h" +#include "lldb/Symbol/ClangASTImporter.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Language.h" #include "lldb/Target/LanguageRuntime.h" -#include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/SectionLoadList.h" #include "lldb/Target/StackFrame.h" @@ -58,6 +56,10 @@ #include "lldb/Utility/State.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" + +#include "llvm/ADT/ScopeExit.h" + +#include <memory> #include <mutex> using namespace lldb; @@ -90,7 +92,7 @@ m_breakpoint_list(false), m_internal_breakpoint_list(true), m_watchpoint_list(), m_process_sp(), m_search_filter_sp(), m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(), - m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0), + m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0), m_valid(true), m_suppress_stop_hooks(false), m_is_dummy_target(is_dummy_target), m_stats_storage(static_cast<int>(StatisticKind::StatisticMax)) @@ -498,12 +500,13 @@ if (containingModule != nullptr) { // TODO: We should look into sharing module based search filters // across many breakpoints like we do for the simple target based one - filter_sp.reset( - new SearchFilterByModule(shared_from_this(), *containingModule)); + filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(), + *containingModule); } else { if (!m_search_filter_sp) - m_search_filter_sp.reset( - new SearchFilterForUnconstrainedSearches(shared_from_this())); + m_search_filter_sp = + std::make_shared<SearchFilterForUnconstrainedSearches>( + shared_from_this()); filter_sp = m_search_filter_sp; } return filter_sp; @@ -515,12 +518,13 @@ if (containingModules && containingModules->GetSize() != 0) { // TODO: We should look into sharing module based search filters // across many breakpoints like we do for the simple target based one - filter_sp.reset( - new SearchFilterByModuleList(shared_from_this(), *containingModules)); + filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(), + *containingModules); } else { if (!m_search_filter_sp) - m_search_filter_sp.reset( - new SearchFilterForUnconstrainedSearches(shared_from_this())); + m_search_filter_sp = + std::make_shared<SearchFilterForUnconstrainedSearches>( + shared_from_this()); filter_sp = m_search_filter_sp; } return filter_sp; @@ -537,11 +541,11 @@ // We could make a special "CU List only SearchFilter". Better yet was if // these could be composable, but that will take a little reworking. - filter_sp.reset(new SearchFilterByModuleListAndCU( - shared_from_this(), FileSpecList(), *containingSourceFiles)); + filter_sp = std::make_shared<SearchFilterByModuleListAndCU>( + shared_from_this(), FileSpecList(), *containingSourceFiles); } else { - filter_sp.reset(new SearchFilterByModuleListAndCU( - shared_from_this(), *containingModules, *containingSourceFiles)); + filter_sp = std::make_shared<SearchFilterByModuleListAndCU>( + shared_from_this(), *containingModules, *containingSourceFiles); } return filter_sp; } @@ -569,8 +573,7 @@ BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint( *this, language, catch_bp, throw_bp, internal); if (exc_bkpt_sp && additional_args) { - Breakpoint::BreakpointPreconditionSP precondition_sp = - exc_bkpt_sp->GetPrecondition(); + BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition(); if (precondition_sp && additional_args) { if (error) *error = precondition_sp->ConfigurePrecondition(*additional_args); @@ -605,19 +608,17 @@ } else if (has_modules) { filter_sp = GetSearchFilterForModuleList(containingModules); } else { - filter_sp.reset(new SearchFilterForUnconstrainedSearches(shared_from_this())); + filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>( + shared_from_this()); } StructuredDataImpl *extra_args_impl = new StructuredDataImpl(); if (extra_args_sp) extra_args_impl->SetObjectSP(extra_args_sp); - - BreakpointResolverSP resolver_sp(new - BreakpointResolverScripted(nullptr, class_name, - depth, - extra_args_impl, - *GetDebugger().GetCommandInterpreter() - .GetScriptInterpreter())); + + BreakpointResolverSP resolver_sp(new BreakpointResolverScripted( + nullptr, class_name, depth, extra_args_impl, + *GetDebugger().GetScriptInterpreter())); return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true); } @@ -697,7 +698,7 @@ m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name)); } -BreakpointName *Target::FindBreakpointName(const ConstString &name, +BreakpointName *Target::FindBreakpointName(ConstString name, bool can_create, Status &error) { @@ -722,7 +723,7 @@ } void -Target::DeleteBreakpointName(const ConstString &name) +Target::DeleteBreakpointName(ConstString name) { BreakpointNameList::iterator iter = m_breakpoint_names.find(name); @@ -735,7 +736,7 @@ } void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp, - const ConstString &name) + ConstString name) { bp_sp->RemoveName(name.AsCString()); } @@ -848,7 +849,7 @@ } if (!wp_sp) { - wp_sp.reset(new Watchpoint(*this, addr, size, type)); + wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type); wp_sp->SetWatchpointType(kind, notify); m_watchpoint_list.Add(wp_sp, true); } @@ -1025,7 +1026,7 @@ } if (!break_store_ptr) { - break_store_sp.reset(new StructuredData::Array()); + break_store_sp = std::make_shared<StructuredData::Array>(); break_store_ptr = break_store_sp.get(); } @@ -1438,7 +1439,8 @@ "Target::SetExecutableModule (executable = '%s')", executable_sp->GetFileSpec().GetPath().c_str()); - m_images.Append(executable_sp); // The first image is our executable file + const bool notify = true; + m_images.Append(executable_sp, notify); // The first image is our executable file // If we haven't set an architecture yet, reset our architecture based on // what we found in the executable module. @@ -1466,6 +1468,7 @@ } if (executable_objfile && load_dependents) { + ModuleList added_modules; executable_objfile->GetDependentModules(dependent_files); for (uint32_t i = 0; i < dependent_files.GetSize(); i++) { FileSpec dependent_file_spec( @@ -1478,13 +1481,16 @@ platform_dependent_file_spec = dependent_file_spec; ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec()); - ModuleSP image_module_sp(GetSharedModule(module_spec)); + ModuleSP image_module_sp(GetOrCreateModule(module_spec, + false /* notify */)); if (image_module_sp) { + added_modules.AppendIfNeeded (image_module_sp, false); ObjectFile *objfile = image_module_sp->GetObjectFile(); if (objfile) objfile->GetDependentModules(dependent_files); } } + ModulesDidLoad(added_modules); } } } @@ -1565,8 +1571,9 @@ arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str()); ModuleSpec module_spec(executable_sp->GetFileSpec(), other); + FileSpecList search_paths = GetExecutableSearchPaths(); Status error = ModuleList::GetSharedModule(module_spec, executable_sp, - &GetExecutableSearchPaths(), + &search_paths, nullptr, nullptr); if (!error.Fail() && executable_sp) { @@ -1602,20 +1609,19 @@ return false; } -void Target::WillClearList(const ModuleList &module_list) {} +void Target::NotifyWillClearList(const ModuleList &module_list) {} -void Target::ModuleAdded(const ModuleList &module_list, +void Target::NotifyModuleAdded(const ModuleList &module_list, const ModuleSP &module_sp) { // A module is being added to this target for the first time if (m_valid) { ModuleList my_module_list; my_module_list.Append(module_sp); - LoadScriptingResourceForModule(module_sp, this); ModulesDidLoad(my_module_list); } } -void Target::ModuleRemoved(const ModuleList &module_list, +void Target::NotifyModuleRemoved(const ModuleList &module_list, const ModuleSP &module_sp) { // A module is being removed from this target. if (m_valid) { @@ -1625,7 +1631,7 @@ } } -void Target::ModuleUpdated(const ModuleList &module_list, +void Target::NotifyModuleUpdated(const ModuleList &module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp) { // A module is replacing an already added module @@ -1637,8 +1643,18 @@ } } +void Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) { + ModulesDidUnload (module_list, false); +} + + void Target::ModulesDidLoad(ModuleList &module_list) { - if (m_valid && module_list.GetSize()) { + const size_t num_images = module_list.GetSize(); + if (m_valid && num_images) { + for (size_t idx = 0; idx < num_images; ++idx) { + ModuleSP module_sp(module_list.GetModuleAtIndex(idx)); + LoadScriptingResourceForModule(module_sp, this); + } m_breakpoint_list.UpdateBreakpoints(module_list, true, false); m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false); if (m_process_sp) { @@ -1652,11 +1668,8 @@ void Target::SymbolsDidLoad(ModuleList &module_list) { if (m_valid && module_list.GetSize()) { if (m_process_sp) { - LanguageRuntime *runtime = - m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC); - if (runtime) { - ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime; - objc_runtime->SymbolsDidLoad(module_list); + for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) { + runtime->SymbolsDidLoad(module_list); } } @@ -1840,7 +1853,7 @@ out_str.clear(); addr_t curr_addr = addr.GetLoadAddress(this); Address address(addr); - while (1) { + while (true) { size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error); if (length == 0) break; @@ -1980,8 +1993,8 @@ return false; } -ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec, - Status *error_ptr) { +ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify, + Status *error_ptr) { ModuleSP module_sp; Status error; @@ -1997,7 +2010,7 @@ ModuleSP old_module_sp; // This will get filled in if we have a new version // of the library bool did_create_module = false; - + FileSpecList search_paths = GetExecutableSearchPaths(); // If there are image search path entries, try to use them first to acquire // a suitable image. if (m_image_search_paths.GetSize()) { @@ -2008,7 +2021,7 @@ transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename(); error = ModuleList::GetSharedModule(transformed_spec, module_sp, - &GetExecutableSearchPaths(), + &search_paths, &old_module_sp, &did_create_module); } } @@ -2025,7 +2038,7 @@ if (module_spec.GetUUID().IsValid()) { // We have a UUID, it is OK to check the global module list... error = ModuleList::GetSharedModule(module_spec, module_sp, - &GetExecutableSearchPaths(), + &search_paths, &old_module_sp, &did_create_module); } @@ -2035,7 +2048,7 @@ if (m_platform_sp) { error = m_platform_sp->GetSharedModule( module_spec, m_process_sp.get(), module_sp, - &GetExecutableSearchPaths(), &old_module_sp, &did_create_module); + &search_paths, &old_module_sp, &did_create_module); } else { error.SetErrorString("no platform is currently set"); } @@ -2114,8 +2127,9 @@ Module *old_module_ptr = old_module_sp.get(); old_module_sp.reset(); ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr); - } else - m_images.Append(module_sp); + } else { + m_images.Append(module_sp, notify); + } } else module_sp.reset(); } @@ -2200,7 +2214,8 @@ UserExpression *Target::GetUserExpressionForLanguage( llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, Expression::ResultType desired_type, - const EvaluateExpressionOptions &options, Status &error) { + const EvaluateExpressionOptions &options, + ValueObject *ctx_obj, Status &error) { Status type_system_error; TypeSystem *type_system = @@ -2216,7 +2231,7 @@ } user_expr = type_system->GetUserExpression(expr, prefix, language, - desired_type, options); + desired_type, options, ctx_obj); if (!user_expr) error.SetErrorStringWithFormat( "Could not create an expression for language %s", @@ -2290,7 +2305,7 @@ ClangASTImporterSP Target::GetClangASTImporter() { if (m_valid) { if (!m_ast_importer_sp) { - m_ast_importer_sp.reset(new ClangASTImporter()); + m_ast_importer_sp = std::make_shared<ClangASTImporter>(); } return m_ast_importer_sp; } @@ -2315,13 +2330,6 @@ return FileSpecList(); } -FileSpecList Target::GetDefaultClangModuleSearchPaths() { - TargetPropertiesSP properties_sp(Target::GetGlobalProperties()); - if (properties_sp) - return properties_sp->GetClangModuleSearchPaths(); - return FileSpecList(); -} - ArchSpec Target::GetDefaultArchitecture() { TargetPropertiesSP properties_sp(Target::GetGlobalProperties()); if (properties_sp) @@ -2357,7 +2365,8 @@ ExpressionResults Target::EvaluateExpression( llvm::StringRef expr, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, - const EvaluateExpressionOptions &options, std::string *fixed_expression) { + const EvaluateExpressionOptions &options, std::string *fixed_expression, + ValueObject *ctx_obj) { result_valobj_sp.reset(); ExpressionResults execution_results = eExpressionSetupError; @@ -2365,10 +2374,11 @@ if (expr.empty()) return execution_results; - // We shouldn't run stop hooks in expressions. Be sure to reset this if you - // return anywhere within this function. + // We shouldn't run stop hooks in expressions. bool old_suppress_value = m_suppress_stop_hooks; m_suppress_stop_hooks = true; + auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() { + m_suppress_stop_hooks = old_suppress_value; }); ExecutionContext exe_ctx; @@ -2395,19 +2405,18 @@ } else { llvm::StringRef prefix = GetExpressionPrefixContents(); Status error; - execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix, - result_valobj_sp, error, - 0, // Line Number - fixed_expression); + execution_results = + UserExpression::Evaluate(exe_ctx, options, expr, prefix, + result_valobj_sp, error, fixed_expression, + nullptr, // Module + ctx_obj); } - m_suppress_stop_hooks = old_suppress_value; - return execution_results; } lldb::ExpressionVariableSP -Target::GetPersistentVariable(const ConstString &name) { +Target::GetPersistentVariable(ConstString name) { lldb::ExpressionVariableSP variable_sp; m_scratch_type_system_map.ForEach( [name, &variable_sp](TypeSystem *type_system) -> bool { @@ -2423,7 +2432,7 @@ return variable_sp; } -lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) { +lldb::addr_t Target::GetPersistentSymbol(ConstString name) { lldb::addr_t address = LLDB_INVALID_ADDRESS; m_scratch_type_system_map.ForEach( @@ -2460,9 +2469,9 @@ } SourceManager &Target::GetSourceManager() { - if (!m_source_manager_ap) - m_source_manager_ap.reset(new SourceManager(shared_from_this())); - return *m_source_manager_ap; + if (!m_source_manager_up) + m_source_manager_up.reset(new SourceManager(shared_from_this())); + return *m_source_manager_up; } ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() { @@ -2473,13 +2482,13 @@ { std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex); - if (!m_clang_modules_decl_vendor_ap) { - m_clang_modules_decl_vendor_ap.reset( + if (!m_clang_modules_decl_vendor_up) { + m_clang_modules_decl_vendor_up.reset( ClangModulesDeclVendor::Create(*this)); } } - return m_clang_modules_decl_vendor_ap.get(); + return m_clang_modules_decl_vendor_up.get(); } Target::StopHookSP Target::CreateStopHook() { @@ -2546,12 +2555,14 @@ StopHookCollection::iterator pos, end = m_stop_hooks.end(); - // If there aren't any active stop hooks, don't bother either: + // If there aren't any active stop hooks, don't bother either. + // Also see if any of the active hooks want to auto-continue. bool any_active_hooks = false; - for (pos = m_stop_hooks.begin(); pos != end; pos++) { - if ((*pos).second->IsActive()) { + bool auto_continue = false; + for (auto hook : m_stop_hooks) { + if (hook.second->IsActive()) { any_active_hooks = true; - break; + auto_continue |= hook.second->GetAutoContinue(); } } if (!any_active_hooks) @@ -2587,6 +2598,7 @@ bool hooks_ran = false; bool print_hook_header = (m_stop_hooks.size() != 1); bool print_thread_header = (num_exe_ctx != 1); + bool did_restart = false; for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) { // result.Clear(); @@ -2629,12 +2641,16 @@ options.SetStopOnError(true); options.SetEchoCommands(false); options.SetPrintResults(true); + options.SetPrintErrors(true); options.SetAddToHistory(false); + // Force Async: + bool old_async = GetDebugger().GetAsyncExecution(); + GetDebugger().SetAsyncExecution(true); GetDebugger().GetCommandInterpreter().HandleCommands( cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options, result); - + GetDebugger().SetAsyncExecution(old_async); // If the command started the target going again, we should bag out of // running the stop hooks. if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) || @@ -2643,13 +2659,19 @@ StopHookCollection::iterator tmp = pos; if (++tmp != end) result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64 - " set the program running.\n", + " set the program running.\n" + " Consider using '-G true' to make " + "stop hooks auto-continue.\n", cur_hook_sp->GetID()); keep_going = false; + did_restart = true; } } } } + // Finally, if auto-continue was requested, do it now: + if (!did_restart && auto_continue) + m_process_sp->PrivateResume(); result.GetImmediateOutputStream()->Flush(); result.GetImmediateErrorStream()->Flush(); @@ -2906,17 +2928,11 @@ if (state == eStateStopped) { if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) { if (synchronous_execution) { - error = m_process_sp->PrivateResume(); - if (error.Success()) { - state = m_process_sp->WaitForProcessToStop( - llvm::None, nullptr, true, hijack_listener_sp, stream); - const bool must_be_alive = - false; // eStateExited is ok, so this must be false - if (!StateIsStoppedState(state, must_be_alive)) { - error.SetErrorStringWithFormat("process isn't stopped: %s", - StateAsCString(state)); - } - } + // Now we have handled the stop-from-attach, and we are just switching + // to a synchronous resume. So we should switch to the SyncResume + // hijacker. + m_process_sp->RestoreProcessEvents(); + m_process_sp->ResumeSynchronous(stream); } else { m_process_sp->RestoreProcessEvents(); error = m_process_sp->PrivateResume(); @@ -3130,19 +3146,18 @@ } } -//-------------------------------------------------------------- // Target::StopHook -//-------------------------------------------------------------- Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid) : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(), - m_thread_spec_ap(), m_active(true) {} + m_thread_spec_up() {} Target::StopHook::StopHook(const StopHook &rhs) : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp), m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp), - m_thread_spec_ap(), m_active(rhs.m_active) { - if (rhs.m_thread_spec_ap) - m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + m_thread_spec_up(), m_active(rhs.m_active), + m_auto_continue(rhs.m_auto_continue) { + if (rhs.m_thread_spec_up) + m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up)); } Target::StopHook::~StopHook() = default; @@ -3152,7 +3167,7 @@ } void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) { - m_thread_spec_ap.reset(specifier); + m_thread_spec_up.reset(specifier); } void Target::StopHook::GetDescription(Stream *s, @@ -3167,6 +3182,9 @@ else s->Indent("State: disabled\n"); + if (m_auto_continue) + s->Indent("AutoContinue on\n"); + if (m_specifier_sp) { s->Indent(); s->PutCString("Specifier:\n"); @@ -3175,10 +3193,10 @@ s->SetIndentLevel(indent_level + 2); } - if (m_thread_spec_ap) { + if (m_thread_spec_up) { StreamString tmp; s->Indent("Thread:\n"); - m_thread_spec_ap->GetDescription(&tmp, level); + m_thread_spec_up->GetDescription(&tmp, level); s->SetIndentLevel(indent_level + 4); s->Indent(tmp.GetString()); s->PutCString("\n"); @@ -3195,9 +3213,7 @@ s->SetIndentLevel(indent_level); } -//-------------------------------------------------------------- // class TargetProperties -//-------------------------------------------------------------- // clang-format off static constexpr OptionEnumValueElement g_dynamic_value_types[] = { @@ -3225,11 +3241,11 @@ "Always look for inline breakpoint locations when setting file and line " "breakpoints (slower but most accurate)."} }; -typedef enum x86DisassemblyFlavor { +enum x86DisassemblyFlavor { eX86DisFlavorDefault, eX86DisFlavorIntel, eX86DisFlavorATT -} x86DisassemblyFlavor; +}; static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = { {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."}, @@ -3310,6 +3326,9 @@ {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true, nullptr, {}, "Automatically load Clang modules referred to by the program."}, + {"import-std-module", OptionValue::eTypeBoolean, false, false, + nullptr, {}, + "Import the C++ std module to improve debugging STL containers."}, {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr, {}, "Automatically apply fix-it hints to expressions."}, {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr, @@ -3448,6 +3467,7 @@ ePropertyDebugFileSearchPaths, ePropertyClangModuleSearchPaths, ePropertyAutoImportClangModules, + ePropertyImportStdModule, ePropertyAutoApplyFixIts, ePropertyNotifyAboutFixIts, ePropertySaveObjects, @@ -3485,7 +3505,7 @@ class TargetOptionValueProperties : public OptionValueProperties { public: - TargetOptionValueProperties(const ConstString &name) + TargetOptionValueProperties(ConstString name) : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {} // This constructor is used when creating TargetOptionValueProperties when it @@ -3554,9 +3574,7 @@ mutable bool m_got_host_env; }; -//---------------------------------------------------------------------- // TargetProperties -//---------------------------------------------------------------------- static constexpr PropertyDefinition g_experimental_properties[]{ {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr, {}, @@ -3582,14 +3600,12 @@ m_collection_sp->Initialize(g_experimental_properties); } -//---------------------------------------------------------------------- // TargetProperties -//---------------------------------------------------------------------- TargetProperties::TargetProperties(Target *target) : Properties(), m_launch_info() { if (target) { - m_collection_sp.reset( - new TargetOptionValueProperties(target, Target::GetGlobalProperties())); + m_collection_sp = std::make_shared<TargetOptionValueProperties>( + target, Target::GetGlobalProperties()); // Set callbacks to update launch_info whenever "settins set" updated any // of these properties @@ -3637,8 +3653,8 @@ DisableASLRValueChangedCallback(this, nullptr); DisableSTDIOValueChangedCallback(this, nullptr); } else { - m_collection_sp.reset( - new TargetOptionValueProperties(ConstString("target"))); + m_collection_sp = + std::make_shared<TargetOptionValueProperties>(ConstString("target")); m_collection_sp->Initialize(g_properties); m_experimental_properties_up.reset(new TargetExperimentalProperties()); m_collection_sp->AppendProperty( @@ -3837,27 +3853,36 @@ return option_value->GetCurrentValue(); } -FileSpecList &TargetProperties::GetExecutableSearchPaths() { +void TargetProperties::AppendExecutableSearchPaths(const FileSpec& dir) { const uint32_t idx = ePropertyExecutableSearchPaths; OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx); assert(option_value); - return option_value->GetCurrentValue(); + option_value->AppendCurrentValue(dir); } -FileSpecList &TargetProperties::GetDebugFileSearchPaths() { - const uint32_t idx = ePropertyDebugFileSearchPaths; - OptionValueFileSpecList *option_value = +FileSpecList TargetProperties::GetExecutableSearchPaths() { + const uint32_t idx = ePropertyExecutableSearchPaths; + const OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx); assert(option_value); return option_value->GetCurrentValue(); } -FileSpecList &TargetProperties::GetClangModuleSearchPaths() { +FileSpecList TargetProperties::GetDebugFileSearchPaths() { + const uint32_t idx = ePropertyDebugFileSearchPaths; + const OptionValueFileSpecList *option_value = + m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, + false, idx); + assert(option_value); + return option_value->GetCurrentValue(); +} + +FileSpecList TargetProperties::GetClangModuleSearchPaths() { const uint32_t idx = ePropertyClangModuleSearchPaths; - OptionValueFileSpecList *option_value = + const OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx); assert(option_value); @@ -3870,6 +3895,12 @@ nullptr, idx, g_properties[idx].default_uint_value != 0); } +bool TargetProperties::GetEnableImportStdModule() const { + const uint32_t idx = ePropertyImportStdModule; + return m_collection_sp->GetPropertyAtIndexAsBoolean( + nullptr, idx, g_properties[idx].default_uint_value != 0); +} + bool TargetProperties::GetEnableAutoApplyFixIts() const { const uint32_t idx = ePropertyAutoApplyFixIts; return m_collection_sp->GetPropertyAtIndexAsBoolean( @@ -4176,9 +4207,7 @@ this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO); } -//---------------------------------------------------------------------- // Target::TargetEventData -//---------------------------------------------------------------------- Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp) : EventData(), m_target_sp(target_sp), m_module_list() {} @@ -4189,7 +4218,7 @@ Target::TargetEventData::~TargetEventData() = default; -const ConstString &Target::TargetEventData::GetFlavorString() { +ConstString Target::TargetEventData::GetFlavorString() { static ConstString g_flavor("Target::TargetEventData"); return g_flavor; }
diff --git a/src/llvm-project/lldb/source/Target/TargetList.cpp b/src/llvm-project/lldb/source/Target/TargetList.cpp index 5b26250..7c7a36e 100644 --- a/src/llvm-project/lldb/source/Target/TargetList.cpp +++ b/src/llvm-project/lldb/source/Target/TargetList.cpp
@@ -1,9 +1,8 @@ //===-- TargetList.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -35,9 +34,7 @@ return class_name; } -//---------------------------------------------------------------------- // TargetList constructor -//---------------------------------------------------------------------- TargetList::TargetList(Debugger &debugger) : Broadcaster(debugger.GetBroadcasterManager(), TargetList::GetStaticBroadcasterClass().AsCString()), @@ -45,9 +42,7 @@ CheckInWithManager(); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- TargetList::~TargetList() { std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex); m_target_list.clear(); @@ -427,7 +422,7 @@ if (file.GetDirectory()) { FileSpec file_dir; file_dir.GetDirectory() = file.GetDirectory(); - target_sp->GetExecutableSearchPaths().Append(file_dir); + target_sp->AppendExecutableSearchPaths(file_dir); } // Don't put the dummy target in the target list, it's held separately.
diff --git a/src/llvm-project/lldb/source/Target/Thread.cpp b/src/llvm-project/lldb/source/Target/Thread.cpp index 569d7a0..7a6b49e 100644 --- a/src/llvm-project/lldb/source/Target/Thread.cpp +++ b/src/llvm-project/lldb/source/Target/Thread.cpp
@@ -1,9 +1,8 @@ //===-- Thread.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,7 +22,7 @@ #include "lldb/Target/ABI.h" #include "lldb/Target/DynamicLoader.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/ObjCLanguageRuntime.h" +#include "lldb/Target/LanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrameRecognizer.h" @@ -51,6 +50,8 @@ #include "lldb/Utility/StreamString.h" #include "lldb/lldb-enumerations.h" +#include <memory> + using namespace lldb; using namespace lldb_private; @@ -91,7 +92,7 @@ class ThreadOptionValueProperties : public OptionValueProperties { public: - ThreadOptionValueProperties(const ConstString &name) + ThreadOptionValueProperties(ConstString name) : OptionValueProperties(name) {} // This constructor is used when creating ThreadOptionValueProperties when it @@ -122,12 +123,12 @@ ThreadProperties::ThreadProperties(bool is_global) : Properties() { if (is_global) { - m_collection_sp.reset( - new ThreadOptionValueProperties(ConstString("thread"))); + m_collection_sp = + std::make_shared<ThreadOptionValueProperties>(ConstString("thread")); m_collection_sp->Initialize(g_properties); } else - m_collection_sp.reset( - new ThreadOptionValueProperties(Thread::GetGlobalProperties().get())); + m_collection_sp = std::make_shared<ThreadOptionValueProperties>( + Thread::GetGlobalProperties().get()); } ThreadProperties::~ThreadProperties() = default; @@ -137,9 +138,9 @@ return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex(nullptr, idx); } -FileSpecList &ThreadProperties::GetLibrariesToAvoid() const { +FileSpecList ThreadProperties::GetLibrariesToAvoid() const { const uint32_t idx = ePropertyStepAvoidLibraries; - OptionValueFileSpecList *option_value = + const OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx); assert(option_value); @@ -170,11 +171,9 @@ nullptr, idx, g_properties[idx].default_uint_value != 0); } -//------------------------------------------------------------------ // Thread Event Data -//------------------------------------------------------------------ -const ConstString &Thread::ThreadEventData::GetFlavorString() { +ConstString Thread::ThreadEventData::GetFlavorString() { static ConstString g_flavor("Thread::ThreadEventData"); return g_flavor; } @@ -233,9 +232,7 @@ return frame_sp; } -//------------------------------------------------------------------ // Thread class -//------------------------------------------------------------------ ConstString &Thread::GetStaticBroadcasterClass() { static ConstString class_name("lldb.thread"); @@ -255,7 +252,7 @@ m_curr_frames_sp(), m_prev_frames_sp(), m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER), m_resume_state(eStateRunning), m_temporary_resume_state(eStateRunning), - m_unwinder_ap(), m_destroy_called(false), + m_unwinder_up(), m_destroy_called(false), m_override_should_notify(eLazyBoolCalculate), m_extended_info_fetched(false), m_extended_info() { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); @@ -305,7 +302,7 @@ m_stop_info_sp.reset(); m_reg_context_sp.reset(); - m_unwinder_ap.reset(); + m_unwinder_up.reset(); std::lock_guard<std::recursive_mutex> guard(m_frame_mutex); m_curr_frames_sp.reset(); m_prev_frames_sp.reset(); @@ -561,8 +558,8 @@ // Clear out all stack frames as our world just changed. ClearStackFrames(); reg_ctx_sp->InvalidateIfNeeded(true); - if (m_unwinder_ap.get()) - m_unwinder_ap->Clear(); + if (m_unwinder_up) + m_unwinder_up->Clear(); return ret; } } @@ -856,7 +853,7 @@ // Otherwise, don't let the base plan override what the other plans say // to do, since presumably if there were other plans they would know what // to do... - while (1) { + while (true) { if (PlanIsBasePlan(current_plan)) break; @@ -981,7 +978,7 @@ } else { Vote thread_vote = eVoteNoOpinion; ThreadPlan *plan_ptr = GetCurrentPlan(); - while (1) { + while (true) { if (plan_ptr->PlanExplainsStop(event_ptr)) { thread_vote = plan_ptr->ShouldReportStop(event_ptr); break; @@ -1301,7 +1298,7 @@ return; } - while (1) { + while (true) { int master_plan_idx; bool discard = true; @@ -1384,9 +1381,9 @@ const SymbolContext &addr_context, lldb::RunMode stop_other_threads, Status &status, LazyBool step_out_avoids_code_withoug_debug_info) { ThreadPlanSP thread_plan_sp; - thread_plan_sp.reset(new ThreadPlanStepOverRange( + thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>( *this, range, addr_context, stop_other_threads, - step_out_avoids_code_withoug_debug_info)); + step_out_avoids_code_withoug_debug_info); status = QueueThreadPlan(thread_plan_sp, abort_other_plans); return thread_plan_sp; @@ -1398,10 +1395,12 @@ bool abort_other_plans, const LineEntry &line_entry, const SymbolContext &addr_context, lldb::RunMode stop_other_threads, Status &status, LazyBool step_out_avoids_code_withoug_debug_info) { + const bool include_inlined_functions = true; + auto address_range = + line_entry.GetSameLineContiguousAddressRange(include_inlined_functions); return QueueThreadPlanForStepOverRange( - abort_other_plans, line_entry.GetSameLineContiguousAddressRange(), - addr_context, stop_other_threads, status, - step_out_avoids_code_withoug_debug_info); + abort_other_plans, address_range, addr_context, stop_other_threads, + status, step_out_avoids_code_withoug_debug_info); } ThreadPlanSP Thread::QueueThreadPlanForStepInRange( @@ -1431,8 +1430,10 @@ lldb::RunMode stop_other_threads, Status &status, LazyBool step_in_avoids_code_without_debug_info, LazyBool step_out_avoids_code_without_debug_info) { + const bool include_inlined_functions = false; return QueueThreadPlanForStepInRange( - abort_other_plans, line_entry.GetSameLineContiguousAddressRange(), + abort_other_plans, + line_entry.GetSameLineContiguousAddressRange(include_inlined_functions), addr_context, step_in_target, stop_other_threads, status, step_in_avoids_code_without_debug_info, step_out_avoids_code_without_debug_info); @@ -1599,15 +1600,13 @@ } StackFrameListSP Thread::GetStackFrameList() { - StackFrameListSP frame_list_sp; std::lock_guard<std::recursive_mutex> guard(m_frame_mutex); - if (m_curr_frames_sp) { - frame_list_sp = m_curr_frames_sp; - } else { - frame_list_sp.reset(new StackFrameList(*this, m_prev_frames_sp, true)); - m_curr_frames_sp = frame_list_sp; - } - return frame_list_sp; + + if (!m_curr_frames_sp) + m_curr_frames_sp = + std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true); + + return m_curr_frames_sp; } void Thread::ClearStackFrames() { @@ -1678,7 +1677,7 @@ // FIXME: ValueObject::Cast doesn't currently work correctly, at least not // for scalars. // Turn that back on when that works. - if (/* DISABLES CODE */ (0) && sc.function != nullptr) { + if (/* DISABLES CODE */ (false) && sc.function != nullptr) { Type *function_type = sc.function->GetType(); if (function_type) { CompilerType return_type = @@ -2055,7 +2054,7 @@ } Unwind *Thread::GetUnwinder() { - if (!m_unwinder_ap) { + if (!m_unwinder_up) { const ArchSpec target_arch(CalculateTarget()->GetArchitecture()); const llvm::Triple::ArchType machine = target_arch.GetMachine(); switch (machine) { @@ -2073,16 +2072,16 @@ case llvm::Triple::ppc64le: case llvm::Triple::systemz: case llvm::Triple::hexagon: - m_unwinder_ap.reset(new UnwindLLDB(*this)); + m_unwinder_up.reset(new UnwindLLDB(*this)); break; default: if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple) - m_unwinder_ap.reset(new UnwindMacOSXFrameBackchain(*this)); + m_unwinder_up.reset(new UnwindMacOSXFrameBackchain(*this)); break; } } - return m_unwinder_ap.get(); + return m_unwinder_up.get(); } void Thread::Flush() { @@ -2210,25 +2209,27 @@ if (auto e = recognized_frame->GetExceptionObject()) return e; - // FIXME: For now, only ObjC exceptions are supported. This should really - // iterate over all language runtimes and ask them all to give us the current - // exception. - if (auto runtime = GetProcess()->GetObjCLanguageRuntime()) + // NOTE: Even though this behavior is generalized, only ObjC is actually + // supported at the moment. + for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) { if (auto e = runtime->GetExceptionObjectForThread(shared_from_this())) return e; + } return ValueObjectSP(); } ThreadSP Thread::GetCurrentExceptionBacktrace() { ValueObjectSP exception = GetCurrentException(); - if (!exception) return ThreadSP(); + if (!exception) + return ThreadSP(); - // FIXME: For now, only ObjC exceptions are supported. This should really - // iterate over all language runtimes and ask them all to give us the current - // exception. - auto runtime = GetProcess()->GetObjCLanguageRuntime(); - if (!runtime) return ThreadSP(); + // NOTE: Even though this behavior is generalized, only ObjC is actually + // supported at the moment. + for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) { + if (auto bt = runtime->GetBacktraceThreadFromException(exception)) + return bt; + } - return runtime->GetBacktraceThreadFromException(exception); + return ThreadSP(); }
diff --git a/src/llvm-project/lldb/source/Target/ThreadCollection.cpp b/src/llvm-project/lldb/source/Target/ThreadCollection.cpp index 2d63b67..cf3c1e2 100644 --- a/src/llvm-project/lldb/source/Target/ThreadCollection.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadCollection.cpp
@@ -1,9 +1,8 @@ //===-- ThreadCollection.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 <stdlib.h>
diff --git a/src/llvm-project/lldb/source/Target/ThreadList.cpp b/src/llvm-project/lldb/source/Target/ThreadList.cpp index 20c2859..afdfda3 100644 --- a/src/llvm-project/lldb/source/Target/ThreadList.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadList.cpp
@@ -1,9 +1,8 @@ //===-- ThreadList.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -38,8 +37,10 @@ if (this != &rhs) { // Lock both mutexes to make sure neither side changes anyone on us while // the assignment occurs - std::lock_guard<std::recursive_mutex> guard(GetMutex()); - std::lock_guard<std::recursive_mutex> rhs_guard(rhs.GetMutex()); + std::lock(GetMutex(), rhs.GetMutex()); + std::lock_guard<std::recursive_mutex> guard(GetMutex(), std::adopt_lock); + std::lock_guard<std::recursive_mutex> rhs_guard(rhs.GetMutex(), + std::adopt_lock); m_process = rhs.m_process; m_stop_id = rhs.m_stop_id;
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlan.cpp b/src/llvm-project/lldb/source/Target/ThreadPlan.cpp index 1f2c69c..1d8cc18 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlan.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlan.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlan.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlan constructor -//---------------------------------------------------------------------- ThreadPlan::ThreadPlan(ThreadPlanKind kind, const char *name, Thread &thread, Vote stop_vote, Vote run_vote) : m_thread(thread), m_stop_vote(stop_vote), m_run_vote(run_vote), @@ -33,9 +30,7 @@ SetID(GetNextID()); } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- ThreadPlan::~ThreadPlan() = default; bool ThreadPlan::PlanExplainsStop(Event *event_ptr) { @@ -161,9 +156,7 @@ } } -//---------------------------------------------------------------------- // ThreadPlanNull -//---------------------------------------------------------------------- ThreadPlanNull::ThreadPlanNull(Thread &thread) : ThreadPlan(ThreadPlan::eKindNull, "Null Thread Plan", thread,
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanBase.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanBase.cpp index 058d146..9cd4bcb 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanBase.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanBase.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanBase.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,11 +22,9 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanBase: This one always stops, and never has anything particular to // do. // FIXME: The "signal handling" policies should probably go here. -//---------------------------------------------------------------------- ThreadPlanBase::ThreadPlanBase(Thread &thread) : ThreadPlan(ThreadPlan::eKindBase, "base plan", thread, eVoteYes,
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanCallFunction.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanCallFunction.cpp index 1131ec9..68d771c 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanCallFunction.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanCallFunction.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanCallFunction.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,12 +24,12 @@ #include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" +#include <memory> + using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanCallFunction: Plan to call a single function -//---------------------------------------------------------------------- bool ThreadPlanCallFunction::ConstructorSetup( Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr, lldb::addr_t &function_load_addr) { @@ -405,8 +404,8 @@ GetThread().SetStopInfoToNothing(); #ifndef SINGLE_STEP_EXPRESSIONS - m_subplan_sp.reset( - new ThreadPlanRunToAddress(m_thread, m_start_addr, m_stop_other_threads)); + m_subplan_sp = std::make_shared<ThreadPlanRunToAddress>( + m_thread, m_start_addr, m_stop_other_threads); m_thread.QueueThreadPlan(m_subplan_sp, false); m_subplan_sp->SetPrivate(true);
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanCallFunctionUsingABI.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanCallFunctionUsingABI.cpp index 08604d2..3155e6f 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanCallFunctionUsingABI.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanCallFunctionUsingABI.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanCallFunctionUsingABI.cpp ----------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,10 +18,8 @@ using namespace lldb; using namespace lldb_private; -//-------------------------------------------------------------------------------------------- // ThreadPlanCallFunctionUsingABI: Plan to call a single function using the ABI // instead of JIT -//------------------------------------------------------------------------------------------- ThreadPlanCallFunctionUsingABI::ThreadPlanCallFunctionUsingABI( Thread &thread, const Address &function, llvm::Type &prototype, llvm::Type &return_type, llvm::ArrayRef<ABI::CallArgument> args,
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanCallOnFunctionExit.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanCallOnFunctionExit.cpp index 2ea083d..3330adc 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanCallOnFunctionExit.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanCallOnFunctionExit.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanCallOnFunctionExit.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -41,9 +40,7 @@ ); } -// ------------------------------------------------------------------------- // ThreadPlan API -// ------------------------------------------------------------------------- void ThreadPlanCallOnFunctionExit::GetDescription( Stream *s, lldb::DescriptionLevel level) {
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanCallUserExpression.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanCallUserExpression.cpp index 1fbd346..864808a 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanCallUserExpression.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanCallUserExpression.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanCallUserExpression.cpp -------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,7 +13,7 @@ #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Address.h" #include "lldb/Expression/DiagnosticManager.h" -#include "lldb/Expression/IRDynamicChecks.h" +#include "lldb/Expression/DynamicCheckerFunctions.h" #include "lldb/Expression/UserExpression.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/LanguageRuntime.h" @@ -30,9 +29,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanCallUserExpression: Plan to call a single function -//---------------------------------------------------------------------- ThreadPlanCallUserExpression::ThreadPlanCallUserExpression( Thread &thread, Address &function, llvm::ArrayRef<lldb::addr_t> args,
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanPython.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanPython.cpp index 84b93bd..8b30c4e 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanPython.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanPython.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanPython.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,9 +23,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanPython -//---------------------------------------------------------------------- ThreadPlanPython::ThreadPlanPython(Thread &thread, const char *class_name) : ThreadPlan(ThreadPlan::eKindPython, "Python based Thread Plan", thread, @@ -63,7 +60,6 @@ ScriptInterpreter *script_interp = m_thread.GetProcess() ->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter(); if (script_interp) { m_implementation_sp = script_interp->CreateScriptedThreadPlan( @@ -83,7 +79,6 @@ ScriptInterpreter *script_interp = m_thread.GetProcess() ->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter(); if (script_interp) { bool script_error; @@ -107,7 +102,6 @@ ScriptInterpreter *script_interp = m_thread.GetProcess() ->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter(); if (script_interp) { bool script_error; @@ -131,7 +125,6 @@ ScriptInterpreter *script_interp = m_thread.GetProcess() ->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter(); if (script_interp) { bool script_error; @@ -170,7 +163,6 @@ ScriptInterpreter *script_interp = m_thread.GetProcess() ->GetTarget() .GetDebugger() - .GetCommandInterpreter() .GetScriptInterpreter(); if (script_interp) { bool script_error;
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanRunToAddress.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanRunToAddress.cpp index bd11f8b..a973bd1 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanRunToAddress.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanRunToAddress.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanRunToAddress.cpp ------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,9 +17,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanRunToAddress: Continue plan -//---------------------------------------------------------------------- ThreadPlanRunToAddress::ThreadPlanRunToAddress(Thread &thread, Address &address, bool stop_others)
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanShouldStopHere.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanShouldStopHere.cpp index 8062d80..a0b7072 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanShouldStopHere.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanShouldStopHere.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanShouldStopHere.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanShouldStopHere constructor -//---------------------------------------------------------------------- ThreadPlanShouldStopHere::ThreadPlanShouldStopHere(ThreadPlan *owner) : m_callbacks(), m_baton(nullptr), m_owner(owner), m_flags(ThreadPlanShouldStopHere::eNone) { @@ -133,7 +130,7 @@ "Queueing StepInRange plan to step through line 0 code."); return_plan_sp = current_plan->GetThread().QueueThreadPlanForStepInRange( - false, range, sc, NULL, eOnlyDuringStepping, status, + false, range, sc, nullptr, eOnlyDuringStepping, status, eLazyBoolCalculate, eLazyBoolNo); } }
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepInRange.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepInRange.cpp index 8f9889a..2065fa5 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepInRange.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepInRange.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanStepInRange.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -29,10 +28,8 @@ uint32_t ThreadPlanStepInRange::s_default_flag_values = ThreadPlanShouldStopHere::eStepInAvoidNoDebug; -//---------------------------------------------------------------------- // ThreadPlanStepInRange: Step through a stack range, either stepping over or // into based on the value of \a type. -//---------------------------------------------------------------------- ThreadPlanStepInRange::ThreadPlanStepInRange( Thread &thread, const AddressRange &range, @@ -315,10 +312,10 @@ void ThreadPlanStepInRange::SetAvoidRegexp(const char *name) { auto name_ref = llvm::StringRef::withNullAsEmpty(name); - if (!m_avoid_regexp_ap) - m_avoid_regexp_ap.reset(new RegularExpression(name_ref)); + if (!m_avoid_regexp_up) + m_avoid_regexp_up.reset(new RegularExpression(name_ref)); - m_avoid_regexp_ap->Compile(name_ref); + m_avoid_regexp_up->Compile(name_ref); } void ThreadPlanStepInRange::SetDefaultFlagValue(uint32_t new_value) { @@ -351,7 +348,7 @@ if (libraries_say_avoid) return true; - const RegularExpression *avoid_regexp_to_use = m_avoid_regexp_ap.get(); + const RegularExpression *avoid_regexp_to_use = m_avoid_regexp_up.get(); if (avoid_regexp_to_use == nullptr) avoid_regexp_to_use = GetThread().GetSymbolsToAvoidRegexp();
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepInstruction.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepInstruction.cpp index 7707454..a11b623 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepInstruction.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepInstruction.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanStepInstruction.cpp ---------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,9 +18,7 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanStepInstruction: Step over the current instruction -//---------------------------------------------------------------------- ThreadPlanStepInstruction::ThreadPlanStepInstruction(Thread &thread, bool step_over,
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepOut.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepOut.cpp index 378de53..bf55c37 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepOut.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepOut.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanStepOut.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -24,14 +23,14 @@ #include "lldb/Target/ThreadPlanStepThrough.h" #include "lldb/Utility/Log.h" +#include <memory> + using namespace lldb; using namespace lldb_private; uint32_t ThreadPlanStepOut::s_default_flag_values = 0; -//---------------------------------------------------------------------- // ThreadPlanStepOut: Step out of the current frame -//---------------------------------------------------------------------- ThreadPlanStepOut::ThreadPlanStepOut( Thread &thread, SymbolContext *context, bool first_insn, bool stop_others, Vote stop_vote, Vote run_vote, uint32_t frame_idx, @@ -85,9 +84,9 @@ if (frame_idx > 0) { // First queue a plan that gets us to this inlined frame, and when we get // there we'll queue a second plan that walks us out of this frame. - m_step_out_to_inline_plan_sp.reset(new ThreadPlanStepOut( + m_step_out_to_inline_plan_sp = std::make_shared<ThreadPlanStepOut>( m_thread, nullptr, false, stop_others, eVoteNoOpinion, eVoteNoOpinion, - frame_idx - 1, eLazyBoolNo, continue_to_next_branch)); + frame_idx - 1, eLazyBoolNo, continue_to_next_branch); static_cast<ThreadPlanStepOut *>(m_step_out_to_inline_plan_sp.get()) ->SetShouldStopHereCallbacks(nullptr, nullptr); m_step_out_to_inline_plan_sp->SetPrivate(true); @@ -111,8 +110,9 @@ return_address_decr_pc.CalculateSymbolContext( &return_address_sc, lldb::eSymbolContextLineEntry); if (return_address_sc.line_entry.IsValid()) { - range = - return_address_sc.line_entry.GetSameLineContiguousAddressRange(); + const bool include_inlined_functions = false; + range = return_address_sc.line_entry.GetSameLineContiguousAddressRange( + include_inlined_functions); if (range.GetByteSize() > 0) { return_address = m_thread.GetProcess()->AdvanceAddressToNextBranchInstruction( @@ -450,8 +450,9 @@ m_stop_others ? lldb::eOnlyThisThread : lldb::eAllThreads; const LazyBool avoid_no_debug = eLazyBoolNo; - m_step_through_inline_plan_sp.reset(new ThreadPlanStepOverRange( - m_thread, inline_range, inlined_sc, run_mode, avoid_no_debug)); + m_step_through_inline_plan_sp = + std::make_shared<ThreadPlanStepOverRange>( + m_thread, inline_range, inlined_sc, run_mode, avoid_no_debug); ThreadPlanStepOverRange *step_through_inline_plan_ptr = static_cast<ThreadPlanStepOverRange *>( m_step_through_inline_plan_sp.get());
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepOverBreakpoint.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepOverBreakpoint.cpp index 8b24bf9..4770b57 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepOverBreakpoint.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepOverBreakpoint.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanStepOverBreakpoint.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -17,10 +16,8 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanStepOverBreakpoint: Single steps over a breakpoint bp_site_sp at // the pc. -//---------------------------------------------------------------------- ThreadPlanStepOverBreakpoint::ThreadPlanStepOverBreakpoint(Thread &thread) : ThreadPlan(
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepOverRange.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepOverRange.cpp index 129f303..3aaeac9 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepOverRange.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepOverRange.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanStepOverRange.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,10 +25,8 @@ uint32_t ThreadPlanStepOverRange::s_default_flag_values = 0; -//---------------------------------------------------------------------- // ThreadPlanStepOverRange: Step through a stack range, either stepping over or // into based on the value of \a type. -//---------------------------------------------------------------------- ThreadPlanStepOverRange::ThreadPlanStepOverRange( Thread &thread, const AddressRange &range,
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepRange.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepRange.cpp index 7ba68ee..49c72db 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepRange.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepRange.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanStepRange.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,10 +25,8 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanStepRange: Step through a stack range, either stepping over or // into based on the value of \a type. -//---------------------------------------------------------------------- ThreadPlanStepRange::ThreadPlanStepRange(ThreadPlanKind kind, const char *name, Thread &thread, @@ -129,8 +126,10 @@ new_context.line_entry.original_file) { if (m_addr_context.line_entry.line == new_context.line_entry.line) { m_addr_context = new_context; - AddRange( - m_addr_context.line_entry.GetSameLineContiguousAddressRange()); + const bool include_inlined_functions = + GetKind() == eKindStepOverRange; + AddRange(m_addr_context.line_entry.GetSameLineContiguousAddressRange( + include_inlined_functions)); ret_value = true; if (log) { StreamString s; @@ -145,8 +144,10 @@ } else if (new_context.line_entry.line == 0) { new_context.line_entry.line = m_addr_context.line_entry.line; m_addr_context = new_context; - AddRange( - m_addr_context.line_entry.GetSameLineContiguousAddressRange()); + const bool include_inlined_functions = + GetKind() == eKindStepOverRange; + AddRange(m_addr_context.line_entry.GetSameLineContiguousAddressRange( + include_inlined_functions)); ret_value = true; if (log) { StreamString s; @@ -314,9 +315,10 @@ return false; else { Target &target = GetThread().GetProcess()->GetTarget(); - uint32_t branch_index; - branch_index = - instructions->GetIndexOfNextBranchInstruction(pc_index, target); + const bool ignore_calls = GetKind() == eKindStepOverRange; + uint32_t branch_index = + instructions->GetIndexOfNextBranchInstruction(pc_index, target, + ignore_calls); Address run_to_address;
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepThrough.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepThrough.cpp index d1f3c22..e46eba0 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepThrough.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepThrough.cpp
@@ -1,17 +1,15 @@ //===-- ThreadPlanStepThrough.cpp -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/ThreadPlanStepThrough.h" #include "lldb/Breakpoint/Breakpoint.h" -#include "lldb/Target/CPPLanguageRuntime.h" #include "lldb/Target/DynamicLoader.h" -#include "lldb/Target/ObjCLanguageRuntime.h" +#include "lldb/Target/LanguageRuntime.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Target.h" @@ -21,12 +19,10 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanStepThrough: If the current instruction is a trampoline, step // through it If it is the beginning of the prologue of a function, step // through that as well. // FIXME: At present only handles DYLD trampolines. -//---------------------------------------------------------------------- ThreadPlanStepThrough::ThreadPlanStepThrough(Thread &thread, StackID &m_stack_id, @@ -88,22 +84,17 @@ m_sub_plan_sp = loader->GetStepThroughTrampolinePlan(m_thread, m_stop_others); - // If that didn't come up with anything, try the ObjC runtime plugin: - if (!m_sub_plan_sp.get()) { - ObjCLanguageRuntime *objc_runtime = - m_thread.GetProcess()->GetObjCLanguageRuntime(); - if (objc_runtime) + // If the DynamicLoader was unable to provide us with a ThreadPlan, then we + // try the LanguageRuntimes. + if (!m_sub_plan_sp) { + for (LanguageRuntime *runtime : + m_thread.GetProcess()->GetLanguageRuntimes()) { m_sub_plan_sp = - objc_runtime->GetStepThroughTrampolinePlan(m_thread, m_stop_others); + runtime->GetStepThroughTrampolinePlan(m_thread, m_stop_others); - CPPLanguageRuntime *cpp_runtime = - m_thread.GetProcess()->GetCPPLanguageRuntime(); - - // If the ObjC runtime did not provide us with a step though plan then if we - // have it check the C++ runtime for a step though plan. - if (!m_sub_plan_sp.get() && cpp_runtime) - m_sub_plan_sp = - cpp_runtime->GetStepThroughTrampolinePlan(m_thread, m_stop_others); + if (m_sub_plan_sp) + break; + } } Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanStepUntil.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanStepUntil.cpp index 1335c62..d4109c3 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanStepUntil.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanStepUntil.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanStepUntil.cpp ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -20,10 +19,8 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // ThreadPlanStepUntil: Run until we reach a given line number or step out of // the current frame -//---------------------------------------------------------------------- ThreadPlanStepUntil::ThreadPlanStepUntil(Thread &thread, lldb::addr_t *address_list,
diff --git a/src/llvm-project/lldb/source/Target/ThreadPlanTracer.cpp b/src/llvm-project/lldb/source/Target/ThreadPlanTracer.cpp index 04e29fd..4e79b6b 100644 --- a/src/llvm-project/lldb/source/Target/ThreadPlanTracer.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadPlanTracer.cpp
@@ -1,9 +1,8 @@ //===-- ThreadPlanTracer.cpp ------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -188,8 +187,6 @@ for (int arg_index = 0; arg_index < num_args; ++arg_index) { Value value; value.SetValueType(Value::eValueTypeScalar); - // value.SetContext (Value::eContextTypeClangType, - // intptr_type.GetOpaqueQualType()); value.SetCompilerType(intptr_type); value_list.PushValue(value); }
diff --git a/src/llvm-project/lldb/source/Target/ThreadSpec.cpp b/src/llvm-project/lldb/source/Target/ThreadSpec.cpp index bae3d0b..1a733cb 100644 --- a/src/llvm-project/lldb/source/Target/ThreadSpec.cpp +++ b/src/llvm-project/lldb/source/Target/ThreadSpec.cpp
@@ -1,9 +1,8 @@ //===-- ThreadSpec.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,18 +21,6 @@ : m_index(UINT32_MAX), m_tid(LLDB_INVALID_THREAD_ID), m_name(), m_queue_name() {} -ThreadSpec::ThreadSpec(const ThreadSpec &rhs) - : m_index(rhs.m_index), m_tid(rhs.m_tid), m_name(rhs.m_name), - m_queue_name(rhs.m_queue_name) {} - -const ThreadSpec &ThreadSpec::operator=(const ThreadSpec &rhs) { - m_index = rhs.m_index; - m_tid = rhs.m_tid; - m_name = rhs.m_name; - m_queue_name = rhs.m_queue_name; - return *this; -} - std::unique_ptr<ThreadSpec> ThreadSpec::CreateFromStructuredData( const StructuredData::Dictionary &spec_dict, Status &error) { uint32_t index = UINT32_MAX;
diff --git a/src/llvm-project/lldb/source/Target/UnixSignals.cpp b/src/llvm-project/lldb/source/Target/UnixSignals.cpp index 1448535..33090a7 100644 --- a/src/llvm-project/lldb/source/Target/UnixSignals.cpp +++ b/src/llvm-project/lldb/source/Target/UnixSignals.cpp
@@ -1,9 +1,8 @@ //===-- UnixSignals.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,6 +11,7 @@ #include "Plugins/Process/Utility/LinuxSignals.h" #include "Plugins/Process/Utility/MipsLinuxSignals.h" #include "Plugins/Process/Utility/NetBSDSignals.h" +#include "lldb/Host/HostInfo.h" #include "lldb/Host/StringConvert.h" #include "lldb/Utility/ArchSpec.h" @@ -51,9 +51,13 @@ } } -//---------------------------------------------------------------------- +lldb::UnixSignalsSP UnixSignals::CreateForHost() { + static lldb::UnixSignalsSP s_unix_signals_sp = + Create(HostInfo::GetArchitecture()); + return s_unix_signals_sp; +} + // UnixSignals constructor -//---------------------------------------------------------------------- UnixSignals::UnixSignals() { Reset(); } UnixSignals::UnixSignals(const UnixSignals &rhs) : m_signals(rhs.m_signals) {}
diff --git a/src/llvm-project/lldb/source/Target/UnwindAssembly.cpp b/src/llvm-project/lldb/source/Target/UnwindAssembly.cpp index 06b6aef..d3d8068 100644 --- a/src/llvm-project/lldb/source/Target/UnwindAssembly.cpp +++ b/src/llvm-project/lldb/source/Target/UnwindAssembly.cpp
@@ -1,9 +1,8 @@ //===-- UnwindAssembly.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,9 +21,9 @@ (create_callback = PluginManager::GetUnwindAssemblyCreateCallbackAtIndex( idx)) != nullptr; ++idx) { - UnwindAssemblySP assembly_profiler_ap(create_callback(arch)); - if (assembly_profiler_ap) - return assembly_profiler_ap; + UnwindAssemblySP assembly_profiler_up(create_callback(arch)); + if (assembly_profiler_up) + return assembly_profiler_up; } return nullptr; }
diff --git a/src/llvm-project/lldb/source/Utility/ARM64_DWARF_Registers.h b/src/llvm-project/lldb/source/Utility/ARM64_DWARF_Registers.h index ce548a2..64f69d6 100644 --- a/src/llvm-project/lldb/source/Utility/ARM64_DWARF_Registers.h +++ b/src/llvm-project/lldb/source/Utility/ARM64_DWARF_Registers.h
@@ -1,9 +1,8 @@ //===-- ARM64_DWARF_Registers.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/ARM64_ehframe_Registers.h b/src/llvm-project/lldb/source/Utility/ARM64_ehframe_Registers.h index 7f49314..9b5cd93 100644 --- a/src/llvm-project/lldb/source/Utility/ARM64_ehframe_Registers.h +++ b/src/llvm-project/lldb/source/Utility/ARM64_ehframe_Registers.h
@@ -1,10 +1,9 @@ //===-- ARM64_ehframe_Registers.h -------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/ARM_DWARF_Registers.h b/src/llvm-project/lldb/source/Utility/ARM_DWARF_Registers.h index ab91d8c..e33210d 100644 --- a/src/llvm-project/lldb/source/Utility/ARM_DWARF_Registers.h +++ b/src/llvm-project/lldb/source/Utility/ARM_DWARF_Registers.h
@@ -1,9 +1,8 @@ //===-- ARM_DWARF_Registers.h -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/ARM_ehframe_Registers.h b/src/llvm-project/lldb/source/Utility/ARM_ehframe_Registers.h index 2a42423..1816b1d97 100644 --- a/src/llvm-project/lldb/source/Utility/ARM_ehframe_Registers.h +++ b/src/llvm-project/lldb/source/Utility/ARM_ehframe_Registers.h
@@ -1,10 +1,9 @@ //===-- ARM_ehframe_Registers.h -------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/ArchSpec.cpp b/src/llvm-project/lldb/source/Utility/ArchSpec.cpp index 752fb18..81b87ff 100644 --- a/src/llvm-project/lldb/source/Utility/ArchSpec.cpp +++ b/src/llvm-project/lldb/source/Utility/ArchSpec.cpp
@@ -1,9 +1,8 @@ //===-- ArchSpec.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -215,13 +214,7 @@ ArchSpec::eCore_uknownMach32, "unknown-mach-32"}, {eByteOrderLittle, 8, 4, 4, llvm::Triple::UnknownArch, ArchSpec::eCore_uknownMach64, "unknown-mach-64"}, - - {eByteOrderBig, 4, 1, 1, llvm::Triple::kalimba, ArchSpec::eCore_kalimba3, - "kalimba3"}, - {eByteOrderLittle, 4, 1, 1, llvm::Triple::kalimba, ArchSpec::eCore_kalimba4, - "kalimba4"}, - {eByteOrderLittle, 4, 1, 1, llvm::Triple::kalimba, ArchSpec::eCore_kalimba5, - "kalimba5"}}; +}; // Ensure that we have an entry in the g_core_definitions for each core. If you // comment out an entry above, you will need to comment out the corresponding @@ -453,12 +446,6 @@ ArchSpec::eMIPSSubType_mips64r6el, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips64r6el {ArchSpec::eCore_hexagon_generic, llvm::ELF::EM_HEXAGON, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // HEXAGON - {ArchSpec::eCore_kalimba3, llvm::ELF::EM_CSR_KALIMBA, - llvm::Triple::KalimbaSubArch_v3, 0xFFFFFFFFu, 0xFFFFFFFFu}, // KALIMBA - {ArchSpec::eCore_kalimba4, llvm::ELF::EM_CSR_KALIMBA, - llvm::Triple::KalimbaSubArch_v4, 0xFFFFFFFFu, 0xFFFFFFFFu}, // KALIMBA - {ArchSpec::eCore_kalimba5, llvm::ELF::EM_CSR_KALIMBA, - llvm::Triple::KalimbaSubArch_v5, 0xFFFFFFFFu, 0xFFFFFFFFu} // KALIMBA }; static const ArchDefinition g_elf_arch_def = { @@ -608,11 +595,7 @@ return "unknown"; } -bool ArchSpec::IsMIPS() const { - const llvm::Triple::ArchType machine = GetMachine(); - return machine == llvm::Triple::mips || machine == llvm::Triple::mipsel || - machine == llvm::Triple::mips64 || machine == llvm::Triple::mips64el; -} +bool ArchSpec::IsMIPS() const { return GetTriple().isMIPS(); } std::string ArchSpec::GetTargetABI() const { @@ -652,10 +635,8 @@ std::string ArchSpec::GetClangTargetCPU() const { std::string cpu; - const llvm::Triple::ArchType machine = GetMachine(); - if (machine == llvm::Triple::mips || machine == llvm::Triple::mipsel || - machine == llvm::Triple::mips64 || machine == llvm::Triple::mips64el) { + if (IsMIPS()) { switch (m_core) { case ArchSpec::eCore_mips32: case ArchSpec::eCore_mips32el: @@ -729,30 +710,10 @@ } uint32_t ArchSpec::GetDataByteSize() const { - switch (m_core) { - case eCore_kalimba3: - return 4; - case eCore_kalimba4: - return 1; - case eCore_kalimba5: - return 4; - default: - return 1; - } return 1; } uint32_t ArchSpec::GetCodeByteSize() const { - switch (m_core) { - case eCore_kalimba3: - return 4; - case eCore_kalimba4: - return 1; - case eCore_kalimba5: - return 1; - default: - return 1; - } return 1; } @@ -764,7 +725,7 @@ return llvm::Triple::UnknownArch; } -const ConstString &ArchSpec::GetDistributionId() const { +ConstString ArchSpec::GetDistributionId() const { return m_distribution_id; } @@ -890,10 +851,9 @@ } void ArchSpec::MergeFrom(const ArchSpec &other) { - if (TripleVendorIsUnspecifiedUnknown() && - !other.TripleVendorIsUnspecifiedUnknown()) + if (!TripleVendorWasSpecified() && other.TripleVendorWasSpecified()) GetTriple().setVendor(other.GetTriple().getVendor()); - if (TripleOSIsUnspecifiedUnknown() && !other.TripleOSIsUnspecifiedUnknown()) + if (!TripleOSWasSpecified() && other.TripleOSWasSpecified()) GetTriple().setOS(other.GetTriple().getOS()); if (GetTriple().getArch() == llvm::Triple::UnknownArch) { GetTriple().setArch(other.GetTriple().getArch()); @@ -904,10 +864,9 @@ if (other.GetCore() != eCore_uknownMach64) UpdateCore(); } - if (GetTriple().getEnvironment() == llvm::Triple::UnknownEnvironment && - !TripleVendorWasSpecified()) { - if (other.TripleVendorWasSpecified()) - GetTriple().setEnvironment(other.GetTriple().getEnvironment()); + if (!TripleEnvironmentWasSpecified() && + other.TripleEnvironmentWasSpecified()) { + GetTriple().setEnvironment(other.GetTriple().getEnvironment()); } // If this and other are both arm ArchSpecs and this ArchSpec is a generic // "some kind of arm" spec but the other ArchSpec is a specific arm core, @@ -945,13 +904,13 @@ m_triple.setVendor(llvm::Triple::Apple); // Don't set the OS. It could be simulator, macosx, ios, watchos, - // tvos, bridgeos. We could get close with the cpu type - but we - // can't get it right all of the time. Better to leave this unset - // so other sections of code will set it when they have more - // information. NB: don't call m_triple.setOS (llvm::Triple::UnknownOS). - // That sets the OSName to "unknown" and the - // ArchSpec::TripleVendorWasSpecified() method says that any OSName - // setting means it was specified. + // tvos, bridgeos. We could get close with the cpu type - but we + // can't get it right all of the time. Better to leave this unset + // so other sections of code will set it when they have more + // information. NB: don't call m_triple.setOS + // (llvm::Triple::UnknownOS). That sets the OSName to "unknown" and + // the ArchSpec::TripleVendorWasSpecified() method says that any + // OSName setting means it was specified. } else if (arch_type == eArchTypeELF) { switch (os) { case llvm::ELF::ELFOSABI_AIX:
diff --git a/src/llvm-project/lldb/source/Utility/Args.cpp b/src/llvm-project/lldb/source/Utility/Args.cpp index 3b5cf17..77b0d43 100644 --- a/src/llvm-project/lldb/source/Utility/Args.cpp +++ b/src/llvm-project/lldb/source/Utility/Args.cpp
@@ -1,9 +1,8 @@ //===-- Args.cpp ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -96,7 +95,7 @@ bool arg_complete = false; do { // Skip over over regular characters and append them. - size_t regular = command.find_first_of(" \t\"'`\\"); + size_t regular = command.find_first_of(" \t\r\"'`\\"); arg += command.substr(0, regular); command = command.substr(regular); @@ -124,6 +123,7 @@ case ' ': case '\t': + case '\r': // We are not inside any quotes, we just found a space after an argument. // We are done. arg_complete = true; @@ -166,9 +166,7 @@ ref = llvm::StringRef(c_str(), size); } -//---------------------------------------------------------------------- // Args constructor -//---------------------------------------------------------------------- Args::Args(llvm::StringRef command) { SetCommandString(command); } Args::Args(const Args &rhs) { *this = rhs; } @@ -191,9 +189,7 @@ return *this; } -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- Args::~Args() {} void Args::Dump(Stream &s, const char *label_name) const { @@ -546,7 +542,7 @@ p += i - 1; unsigned long octal_value = ::strtoul(oct_str, nullptr, 8); if (octal_value <= UINT8_MAX) { - dst.append(1, (char)octal_value); + dst.append(1, static_cast<char>(octal_value)); } } break; @@ -566,7 +562,7 @@ unsigned long hex_value = strtoul(hex_str, nullptr, 16); if (hex_value <= UINT8_MAX) - dst.append(1, (char)hex_value); + dst.append(1, static_cast<char>(hex_value)); } else { dst.append(1, 'x'); } @@ -641,14 +637,15 @@ case '\0': chars_to_escape = " \t\\'\"`"; break; - case '\'': - chars_to_escape = ""; - break; case '"': chars_to_escape = "$\"`\\"; break; + case '`': + case '\'': + return arg; default: assert(false && "Unhandled quote character"); + return arg; } std::string res;
diff --git a/src/llvm-project/lldb/source/Utility/Baton.cpp b/src/llvm-project/lldb/source/Utility/Baton.cpp index 786be2f..84e295e2 100644 --- a/src/llvm-project/lldb/source/Utility/Baton.cpp +++ b/src/llvm-project/lldb/source/Utility/Baton.cpp
@@ -1,9 +1,8 @@ //===-- Baton.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/Broadcaster.cpp b/src/llvm-project/lldb/source/Utility/Broadcaster.cpp index 5b9b998..597888c 100644 --- a/src/llvm-project/lldb/source/Utility/Broadcaster.cpp +++ b/src/llvm-project/lldb/source/Utility/Broadcaster.cpp
@@ -1,9 +1,8 @@ //===-- Broadcaster.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -19,6 +18,7 @@ #include <algorithm> #include <memory> #include <type_traits> +#include <utility> #include <assert.h> #include <stddef.h> @@ -28,11 +28,10 @@ Broadcaster::Broadcaster(BroadcasterManagerSP manager_sp, const char *name) : m_broadcaster_sp(std::make_shared<BroadcasterImpl>(*this)), - m_manager_sp(manager_sp), m_broadcaster_name(name) { + m_manager_sp(std::move(manager_sp)), m_broadcaster_name(name) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); - if (log) - log->Printf("%p Broadcaster::Broadcaster(\"%s\")", - static_cast<void *>(this), GetBroadcasterName().AsCString()); + LLDB_LOG(log, "{0} Broadcaster::Broadcaster(\"{1}\")", + static_cast<void *>(this), GetBroadcasterName().AsCString()); } Broadcaster::BroadcasterImpl::BroadcasterImpl(Broadcaster &broadcaster) @@ -41,9 +40,8 @@ Broadcaster::~Broadcaster() { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); - if (log) - log->Printf("%p Broadcaster::~Broadcaster(\"%s\")", - static_cast<void *>(this), m_broadcaster_name.AsCString()); + LLDB_LOG(log, "{0} Broadcaster::~Broadcaster(\"{1}\")", + static_cast<void *>(this), GetBroadcasterName().AsCString()); Clear(); } @@ -213,8 +211,7 @@ hijacking_listener_sp.reset(); } - Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS)); - if (log) { + if (Log *log = lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS)) { StreamString event_description; event_sp->Dump(&event_description); log->Printf("%p Broadcaster(\"%s\")::BroadcastEvent (event_sp = {%s}, " @@ -225,18 +222,16 @@ } if (hijacking_listener_sp) { - if (unique && - hijacking_listener_sp->PeekAtNextEventForBroadcasterWithType( - &m_broadcaster, event_type)) + if (unique && hijacking_listener_sp->PeekAtNextEventForBroadcasterWithType( + &m_broadcaster, event_type)) return; hijacking_listener_sp->AddEvent(event_sp); } else { for (auto &pair : GetListeners()) { if (!(pair.second & event_type)) continue; - if (unique && - pair.first->PeekAtNextEventForBroadcasterWithType(&m_broadcaster, - event_type)) + if (unique && pair.first->PeekAtNextEventForBroadcasterWithType( + &m_broadcaster, event_type)) continue; pair.first->AddEvent(event_sp); @@ -267,11 +262,11 @@ std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex); Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS)); - if (log) - log->Printf( - "%p Broadcaster(\"%s\")::HijackBroadcaster (listener(\"%s\")=%p)", - static_cast<void *>(this), GetBroadcasterName(), - listener_sp->m_name.c_str(), static_cast<void *>(listener_sp.get())); + LLDB_LOG( + log, + "{0} Broadcaster(\"{1}\")::HijackBroadcaster (listener(\"{2}\")={3})", + static_cast<void *>(this), GetBroadcasterName(), + listener_sp->m_name.c_str(), static_cast<void *>(listener_sp.get())); m_hijacking_listeners.push_back(listener_sp); m_hijacking_masks.push_back(event_mask); return true; @@ -288,24 +283,22 @@ const char *Broadcaster::BroadcasterImpl::GetHijackingListenerName() { if (m_hijacking_listeners.size()) { return m_hijacking_listeners.back()->GetName(); - } else { - return nullptr; } + return nullptr; } void Broadcaster::BroadcasterImpl::RestoreBroadcaster() { std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex); if (!m_hijacking_listeners.empty()) { + ListenerSP listener_sp = m_hijacking_listeners.back(); Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS)); - if (log) { - ListenerSP listener_sp = m_hijacking_listeners.back(); - log->Printf("%p Broadcaster(\"%s\")::RestoreBroadcaster (about to pop " - "listener(\"%s\")=%p)", - static_cast<void *>(this), GetBroadcasterName(), - listener_sp->m_name.c_str(), - static_cast<void *>(listener_sp.get())); - } + LLDB_LOG(log, + "{0} Broadcaster(\"{1}\")::RestoreBroadcaster (about to pop " + "listener(\"{2}\")={3})", + static_cast<void *>(this), GetBroadcasterName(), + listener_sp->m_name.c_str(), + static_cast<void *>(listener_sp.get())); m_hijacking_listeners.pop_back(); } if (!m_hijacking_masks.empty()) @@ -317,14 +310,11 @@ return class_name; } -BroadcastEventSpec::BroadcastEventSpec(const BroadcastEventSpec &rhs) = default; - bool BroadcastEventSpec::operator<(const BroadcastEventSpec &rhs) const { if (GetBroadcasterClass() == rhs.GetBroadcasterClass()) { return GetEventBits() < rhs.GetEventBits(); - } else { - return GetBroadcasterClass() < rhs.GetBroadcasterClass(); } + return GetBroadcasterClass() < rhs.GetBroadcasterClass(); } BroadcastEventSpec &BroadcastEventSpec:: @@ -337,7 +327,7 @@ } uint32_t BroadcasterManager::RegisterListenerForEvents( - const lldb::ListenerSP &listener_sp, BroadcastEventSpec event_spec) { + const lldb::ListenerSP &listener_sp, const BroadcastEventSpec &event_spec) { std::lock_guard<std::recursive_mutex> guard(m_manager_mutex); collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end(); @@ -362,7 +352,7 @@ } bool BroadcasterManager::UnregisterListenerForEvents( - const lldb::ListenerSP &listener_sp, BroadcastEventSpec event_spec) { + const lldb::ListenerSP &listener_sp, const BroadcastEventSpec &event_spec) { std::lock_guard<std::recursive_mutex> guard(m_manager_mutex); bool removed_some = false; @@ -380,17 +370,16 @@ iter = find_if(m_event_map.begin(), end_iter, predicate); if (iter == end_iter) { break; - } else { - uint32_t iter_event_bits = (*iter).first.GetEventBits(); - removed_some = true; - - if (event_bits_to_remove != iter_event_bits) { - uint32_t new_event_bits = iter_event_bits & ~event_bits_to_remove; - to_be_readded.push_back(BroadcastEventSpec( - event_spec.GetBroadcasterClass(), new_event_bits)); - } - m_event_map.erase(iter); } + uint32_t iter_event_bits = (*iter).first.GetEventBits(); + removed_some = true; + + if (event_bits_to_remove != iter_event_bits) { + uint32_t new_event_bits = iter_event_bits & ~event_bits_to_remove; + to_be_readded.push_back( + BroadcastEventSpec(event_spec.GetBroadcasterClass(), new_event_bits)); + } + m_event_map.erase(iter); } // Okay now add back the bits that weren't completely removed: @@ -402,7 +391,7 @@ } ListenerSP BroadcasterManager::GetListenerForEventSpec( - BroadcastEventSpec event_spec) const { + const BroadcastEventSpec &event_spec) const { std::lock_guard<std::recursive_mutex> guard(m_manager_mutex); collection::const_iterator iter, end_iter = m_event_map.end(); @@ -410,8 +399,8 @@ BroadcastEventSpecMatches(event_spec)); if (iter != end_iter) return (*iter).second; - else - return nullptr; + + return nullptr; } void BroadcasterManager::RemoveListener(Listener *listener) { @@ -429,8 +418,8 @@ iter = find_if(m_event_map.begin(), end_iter, predicate); if (iter == end_iter) break; - else - m_event_map.erase(iter); + + m_event_map.erase(iter); } } @@ -446,8 +435,8 @@ iter = find_if(m_event_map.begin(), end_iter, predicate); if (iter == end_iter) break; - else - m_event_map.erase(iter); + + m_event_map.erase(iter); } }
diff --git a/src/llvm-project/lldb/source/Utility/CMakeLists.txt b/src/llvm-project/lldb/source/Utility/CMakeLists.txt index 008054a..03254c3 100644 --- a/src/llvm-project/lldb/source/Utility/CMakeLists.txt +++ b/src/llvm-project/lldb/source/Utility/CMakeLists.txt
@@ -1,46 +1,15 @@ set(LLDB_SYSTEM_LIBS) -# Windows-only libraries -if ( CMAKE_SYSTEM_NAME MATCHES "Windows" ) - list(APPEND LLDB_SYSTEM_LIBS - ws2_32 - rpcrt4 - ) -endif () +list(APPEND LLDB_SYSTEM_LIBS ${system_libs}) -if (NOT LLDB_DISABLE_LIBEDIT) - list(APPEND LLDB_SYSTEM_LIBS ${libedit_LIBRARIES}) -endif() -if (NOT LLDB_DISABLE_CURSES) - list(APPEND LLDB_SYSTEM_LIBS ${CURSES_LIBRARIES}) - if(LLVM_ENABLE_TERMINFO AND HAVE_TERMINFO) - list(APPEND LLDB_SYSTEM_LIBS ${TERMINFO_LIBS}) - endif() -endif() +if (CMAKE_SYSTEM_NAME MATCHES "Windows") + list(APPEND LLDB_SYSTEM_LIBS ws2_32 rpcrt4) +endif () if (NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB ) list(APPEND LLDB_SYSTEM_LIBS atomic) endif() -if(Backtrace_FOUND) - list(APPEND LLDB_SYSTEM_LIBS ${Backtrace_LIBRARY}) -endif() - -if (NOT LLDB_DISABLE_PYTHON AND NOT LLVM_BUILD_STATIC) - list(APPEND LLDB_SYSTEM_LIBS ${PYTHON_LIBRARIES}) -endif() - -list(APPEND LLDB_SYSTEM_LIBS ${system_libs}) - -if (LLVM_BUILD_STATIC) - if (NOT LLDB_DISABLE_PYTHON) - list(APPEND LLDB_SYSTEM_LIBS python2.7 util) - endif() - if (NOT LLDB_DISABLE_CURSES) - list(APPEND LLDB_SYSTEM_LIBS gpm) - endif() -endif() - add_lldb_library(lldbUtility ArchSpec.cpp Args.cpp @@ -54,6 +23,7 @@ DataEncoder.cpp DataExtractor.cpp Environment.cpp + FileCollector.cpp Event.cpp FileSpec.cpp IOObject.cpp @@ -63,9 +33,11 @@ Log.cpp Logging.cpp NameMatches.cpp + ProcessInfo.cpp RegisterValue.cpp RegularExpression.cpp Reproducer.cpp + ReproducerInstrumentation.cpp Scalar.cpp SelectHelper.cpp SharingPtr.cpp @@ -83,6 +55,7 @@ TildeExpressionResolver.cpp Timer.cpp UserID.cpp + UserIDResolver.cpp UriParser.cpp UUID.cpp VASprintf.cpp
diff --git a/src/llvm-project/lldb/source/Utility/CompletionRequest.cpp b/src/llvm-project/lldb/source/Utility/CompletionRequest.cpp index 096661b..c62ec4f 100644 --- a/src/llvm-project/lldb/source/Utility/CompletionRequest.cpp +++ b/src/llvm-project/lldb/source/Utility/CompletionRequest.cpp
@@ -1,9 +1,8 @@ //===-- CompletionRequest.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/Connection.cpp b/src/llvm-project/lldb/source/Utility/Connection.cpp index 9f6114f..483a0c9 100644 --- a/src/llvm-project/lldb/source/Utility/Connection.cpp +++ b/src/llvm-project/lldb/source/Utility/Connection.cpp
@@ -1,9 +1,8 @@ //===-- Connection.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/ConstString.cpp b/src/llvm-project/lldb/source/Utility/ConstString.cpp index 9b8bea71..46b7ab2 100644 --- a/src/llvm-project/lldb/source/Utility/ConstString.cpp +++ b/src/llvm-project/lldb/source/Utility/ConstString.cpp
@@ -1,9 +1,8 @@ //===-- ConstString.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -144,16 +143,14 @@ const char *GetConstTrimmedCStringWithLength(const char *cstr, size_t cstr_len) { if (cstr != nullptr) { - const size_t trimmed_len = std::min<size_t>(strlen(cstr), cstr_len); + const size_t trimmed_len = strnlen(cstr, cstr_len); return GetConstCStringWithLength(cstr, trimmed_len); } return nullptr; } - //------------------------------------------------------------------ // Return the size in bytes that this object and any items in its collection // of uniqued strings + data count values takes in memory. - //------------------------------------------------------------------ size_t MemorySize() const { size_t mem_size = sizeof(Pool); for (const auto &pool : m_string_pools) { @@ -178,7 +175,6 @@ std::array<PoolEntry, 256> m_string_pools; }; -//---------------------------------------------------------------------- // Frameworks and dylibs aren't supposed to have global C++ initializers so we // hide the string pool in a static function so that it will get initialized on // the first call to this static function. @@ -187,7 +183,6 @@ // can't guarantee that some objects won't get destroyed after the global // destructor chain is run, and trying to make sure no destructors touch // ConstStrings is difficult. So we leak the pool instead. -//---------------------------------------------------------------------- static Pool &StringPool() { static llvm::once_flag g_pool_initialization_flag; static Pool *g_string_pool = nullptr; @@ -205,9 +200,9 @@ : m_string(StringPool().GetConstCStringWithLength(cstr, cstr_len)) {} ConstString::ConstString(const llvm::StringRef &s) - : m_string(StringPool().GetConstCStringWithLength(s.data(), s.size())) {} + : m_string(StringPool().GetConstCStringWithStringRef(s)) {} -bool ConstString::operator<(const ConstString &rhs) const { +bool ConstString::operator<(ConstString rhs) const { if (m_string == rhs.m_string) return false; @@ -222,7 +217,7 @@ return lhs_string_ref.data() == nullptr; } -Stream &lldb_private::operator<<(Stream &s, const ConstString &str) { +Stream &lldb_private::operator<<(Stream &s, ConstString str) { const char *cstr = str.GetCString(); if (cstr != nullptr) s << cstr; @@ -234,7 +229,7 @@ return Pool::GetConstCStringLength(m_string); } -bool ConstString::Equals(const ConstString &lhs, const ConstString &rhs, +bool ConstString::Equals(ConstString lhs, ConstString rhs, const bool case_sensitive) { if (lhs.m_string == rhs.m_string) return true; @@ -251,7 +246,7 @@ return lhs_string_ref.equals_lower(rhs_string_ref); } -int ConstString::Compare(const ConstString &lhs, const ConstString &rhs, +int ConstString::Compare(ConstString lhs, ConstString rhs, const bool case_sensitive) { // If the iterators are the same, this is the same string const char *lhs_cstr = lhs.m_string; @@ -303,7 +298,7 @@ } void ConstString::SetStringWithMangledCounterpart(llvm::StringRef demangled, - const ConstString &mangled) { + ConstString mangled) { m_string = StringPool().GetConstCStringAndSetMangledCounterPart( demangled, mangled.m_string); }
diff --git a/src/llvm-project/lldb/source/Utility/DataBufferHeap.cpp b/src/llvm-project/lldb/source/Utility/DataBufferHeap.cpp index 36cac00..5bff777 100644 --- a/src/llvm-project/lldb/source/Utility/DataBufferHeap.cpp +++ b/src/llvm-project/lldb/source/Utility/DataBufferHeap.cpp
@@ -1,9 +1,8 @@ //===-- DataBufferHeap.cpp --------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -12,64 +11,48 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // Default constructor -//---------------------------------------------------------------------- DataBufferHeap::DataBufferHeap() : m_data() {} -//---------------------------------------------------------------------- // Initialize this class with "n" characters and fill the buffer with "ch". -//---------------------------------------------------------------------- DataBufferHeap::DataBufferHeap(lldb::offset_t n, uint8_t ch) : m_data() { if (n < m_data.max_size()) m_data.assign(n, ch); } -//---------------------------------------------------------------------- // Initialize this class with a copy of the "n" bytes from the "bytes" buffer. -//---------------------------------------------------------------------- DataBufferHeap::DataBufferHeap(const void *src, lldb::offset_t src_len) : m_data() { CopyData(src, src_len); } -//---------------------------------------------------------------------- // Virtual destructor since this class inherits from a pure virtual base class. -//---------------------------------------------------------------------- DataBufferHeap::~DataBufferHeap() = default; -//---------------------------------------------------------------------- // Return a pointer to the bytes owned by this object, or nullptr if the object // contains no bytes. -//---------------------------------------------------------------------- uint8_t *DataBufferHeap::GetBytes() { return (m_data.empty() ? nullptr : m_data.data()); } -//---------------------------------------------------------------------- // Return a const pointer to the bytes owned by this object, or nullptr if the // object contains no bytes. -//---------------------------------------------------------------------- const uint8_t *DataBufferHeap::GetBytes() const { return (m_data.empty() ? nullptr : m_data.data()); } -//---------------------------------------------------------------------- // Return the number of bytes this object currently contains. -//---------------------------------------------------------------------- uint64_t DataBufferHeap::GetByteSize() const { return m_data.size(); } -//---------------------------------------------------------------------- // Sets the number of bytes that this object should be able to contain. This // can be used prior to copying data into the buffer. -//---------------------------------------------------------------------- uint64_t DataBufferHeap::SetByteSize(uint64_t new_size) { m_data.resize(new_size); return m_data.size(); } void DataBufferHeap::CopyData(const void *src, uint64_t src_len) { - const uint8_t *src_u8 = (const uint8_t *)src; + const uint8_t *src_u8 = static_cast<const uint8_t *>(src); if (src && src_len > 0) m_data.assign(src_u8, src_u8 + src_len); else @@ -77,8 +60,8 @@ } void DataBufferHeap::AppendData(const void *src, uint64_t src_len) { - m_data.insert(m_data.end(), (const uint8_t *)src, - (const uint8_t *)src + src_len); + m_data.insert(m_data.end(), static_cast<const uint8_t *>(src), + static_cast<const uint8_t *>(src) + src_len); } void DataBufferHeap::Clear() {
diff --git a/src/llvm-project/lldb/source/Utility/DataBufferLLVM.cpp b/src/llvm-project/lldb/source/Utility/DataBufferLLVM.cpp index 0ab3fe5..4227e9b 100644 --- a/src/llvm-project/lldb/source/Utility/DataBufferLLVM.cpp +++ b/src/llvm-project/lldb/source/Utility/DataBufferLLVM.cpp
@@ -1,9 +1,8 @@ //===--- DataBufferLLVM.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/DataEncoder.cpp b/src/llvm-project/lldb/source/Utility/DataEncoder.cpp index c26c0fa..13c505e 100644 --- a/src/llvm-project/lldb/source/Utility/DataEncoder.cpp +++ b/src/llvm-project/lldb/source/Utility/DataEncoder.cpp
@@ -1,9 +1,8 @@ //===-- DataEncoder.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,29 +24,24 @@ using namespace lldb_private; using namespace llvm::support::endian; -//---------------------------------------------------------------------- // Default constructor. -//---------------------------------------------------------------------- DataEncoder::DataEncoder() : m_start(nullptr), m_end(nullptr), m_byte_order(endian::InlHostByteOrder()), m_addr_size(sizeof(void *)), m_data_sp() {} -//---------------------------------------------------------------------- // This constructor allows us to use data that is owned by someone else. The // data must stay around as long as this object is valid. -//---------------------------------------------------------------------- DataEncoder::DataEncoder(void *data, uint32_t length, ByteOrder endian, uint8_t addr_size) - : m_start((uint8_t *)data), m_end((uint8_t *)data + length), - m_byte_order(endian), m_addr_size(addr_size), m_data_sp() {} + : m_start(static_cast<uint8_t *>(data)), + m_end(static_cast<uint8_t *>(data) + length), m_byte_order(endian), + m_addr_size(addr_size), m_data_sp() {} -//---------------------------------------------------------------------- // Make a shared pointer reference to the shared data in "data_sp" and set the // endian swapping setting to "swap", and the address size to "addr_size". The // shared data reference will ensure the data lives as long as any DataEncoder // objects exist that have a reference to this data. -//---------------------------------------------------------------------- DataEncoder::DataEncoder(const DataBufferSP &data_sp, ByteOrder endian, uint8_t addr_size) : m_start(nullptr), m_end(nullptr), m_byte_order(endian), @@ -57,10 +51,8 @@ DataEncoder::~DataEncoder() = default; -//------------------------------------------------------------------ // Clears the object contents back to a default invalid state, and release any // references to shared data that this object may contain. -//------------------------------------------------------------------ void DataEncoder::Clear() { m_start = nullptr; m_end = nullptr; @@ -69,10 +61,8 @@ m_data_sp.reset(); } -//------------------------------------------------------------------ // If this object contains shared data, this function returns the offset into // that shared data. Else zero is returned. -//------------------------------------------------------------------ size_t DataEncoder::GetSharedDataOffset() const { if (m_start != nullptr) { const DataBuffer *data = m_data_sp.get(); @@ -87,7 +77,6 @@ return 0; } -//---------------------------------------------------------------------- // Set the data with which this object will extract from to data starting at // BYTES and set the length of the data to LENGTH bytes long. The data is // externally owned must be around at least as long as this object points to @@ -95,7 +84,6 @@ // and can extract from it. If this object refers to any shared data upon // entry, the reference to that data will be released. Is SWAP is set to true, // any data extracted will be endian swapped. -//---------------------------------------------------------------------- uint32_t DataEncoder::SetData(void *bytes, uint32_t length, ByteOrder endian) { m_byte_order = endian; m_data_sp.reset(); @@ -103,13 +91,12 @@ m_start = nullptr; m_end = nullptr; } else { - m_start = (uint8_t *)bytes; + m_start = static_cast<uint8_t *>(bytes); m_end = m_start + length; } return GetByteSize(); } -//---------------------------------------------------------------------- // Assign the data for this object to be a subrange of the shared data in // "data_sp" starting "data_offset" bytes into "data_sp" and ending // "data_length" bytes later. If "data_offset" is not a valid offset into @@ -121,7 +108,6 @@ // starting at "data_offset") to ensure the data stays around as long as it is // needed. The address size and endian swap settings will remain unchanged from // their current settings. -//---------------------------------------------------------------------- uint32_t DataEncoder::SetData(const DataBufferSP &data_sp, uint32_t data_offset, uint32_t data_length) { m_start = m_end = nullptr; @@ -153,12 +139,10 @@ return new_size; } -//---------------------------------------------------------------------- // Extract a single unsigned char from the binary data and update the offset // pointed to by "offset_ptr". // // RETURNS the byte that was extracted, or zero on failure. -//---------------------------------------------------------------------- uint32_t DataEncoder::PutU8(uint32_t offset, uint8_t value) { if (ValidOffset(offset)) { m_start[offset] = value; @@ -203,7 +187,6 @@ return UINT32_MAX; } -//---------------------------------------------------------------------- // Extract a single integer value from the data and update the offset pointed // to by "offset_ptr". The size of the extracted integer is specified by the // "byte_size" argument. "byte_size" should have a value >= 1 and <= 8 since @@ -212,7 +195,6 @@ // returned. // // RETURNS the integer value that was extracted, or zero on failure. -//---------------------------------------------------------------------- uint32_t DataEncoder::PutMaxU64(uint32_t offset, uint32_t byte_size, uint64_t value) { switch (byte_size) {
diff --git a/src/llvm-project/lldb/source/Utility/DataExtractor.cpp b/src/llvm-project/lldb/source/Utility/DataExtractor.cpp index ae5a3f9..79a1f75 100644 --- a/src/llvm-project/lldb/source/Utility/DataExtractor.cpp +++ b/src/llvm-project/lldb/source/Utility/DataExtractor.cpp
@@ -1,9 +1,8 @@ //===-- DataExtractor.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -125,10 +124,8 @@ m_byte_order(endian::InlHostByteOrder()), m_addr_size(sizeof(void *)), m_data_sp(), m_target_byte_size(1) {} -//---------------------------------------------------------------------- // This constructor allows us to use data that is owned by someone else. The // data must stay around as long as this object is valid. -//---------------------------------------------------------------------- DataExtractor::DataExtractor(const void *data, offset_t length, ByteOrder endian, uint32_t addr_size, uint32_t target_byte_size /*=1*/) @@ -137,44 +134,34 @@ length), m_byte_order(endian), m_addr_size(addr_size), m_data_sp(), m_target_byte_size(target_byte_size) { -#ifdef LLDB_CONFIGURATION_DEBUG assert(addr_size == 4 || addr_size == 8); -#endif } -//---------------------------------------------------------------------- // Make a shared pointer reference to the shared data in "data_sp" and set the // endian swapping setting to "swap", and the address size to "addr_size". The // shared data reference will ensure the data lives as long as any // DataExtractor objects exist that have a reference to this data. -//---------------------------------------------------------------------- DataExtractor::DataExtractor(const DataBufferSP &data_sp, ByteOrder endian, uint32_t addr_size, uint32_t target_byte_size /*=1*/) : m_start(nullptr), m_end(nullptr), m_byte_order(endian), m_addr_size(addr_size), m_data_sp(), m_target_byte_size(target_byte_size) { -#ifdef LLDB_CONFIGURATION_DEBUG assert(addr_size == 4 || addr_size == 8); -#endif SetData(data_sp); } -//---------------------------------------------------------------------- // Initialize this object with a subset of the data bytes in "data". If "data" // contains shared data, then a reference to this shared data will added and // the shared data will stay around as long as any object contains a reference // to that data. The endian swap and address size settings are copied from // "data". -//---------------------------------------------------------------------- DataExtractor::DataExtractor(const DataExtractor &data, offset_t offset, offset_t length, uint32_t target_byte_size /*=1*/) : m_start(nullptr), m_end(nullptr), m_byte_order(data.m_byte_order), m_addr_size(data.m_addr_size), m_data_sp(), m_target_byte_size(target_byte_size) { -#ifdef LLDB_CONFIGURATION_DEBUG assert(m_addr_size == 4 || m_addr_size == 8); -#endif if (data.ValidOffset(offset)) { offset_t bytes_available = data.GetByteSize() - offset; if (length > bytes_available) @@ -187,14 +174,10 @@ : m_start(rhs.m_start), m_end(rhs.m_end), m_byte_order(rhs.m_byte_order), m_addr_size(rhs.m_addr_size), m_data_sp(rhs.m_data_sp), m_target_byte_size(rhs.m_target_byte_size) { -#ifdef LLDB_CONFIGURATION_DEBUG assert(m_addr_size == 4 || m_addr_size == 8); -#endif } -//---------------------------------------------------------------------- // Assignment operator -//---------------------------------------------------------------------- const DataExtractor &DataExtractor::operator=(const DataExtractor &rhs) { if (this != &rhs) { m_start = rhs.m_start; @@ -208,10 +191,8 @@ DataExtractor::~DataExtractor() = default; -//------------------------------------------------------------------ // Clears the object contents back to a default invalid state, and release any // references to shared data that this object may contain. -//------------------------------------------------------------------ void DataExtractor::Clear() { m_start = nullptr; m_end = nullptr; @@ -220,10 +201,8 @@ m_data_sp.reset(); } -//------------------------------------------------------------------ // If this object contains shared data, this function returns the offset into // that shared data. Else zero is returned. -//------------------------------------------------------------------ size_t DataExtractor::GetSharedDataOffset() const { if (m_start != nullptr) { const DataBuffer *data = m_data_sp.get(); @@ -238,7 +217,6 @@ return 0; } -//---------------------------------------------------------------------- // Set the data with which this object will extract from to data starting at // BYTES and set the length of the data to LENGTH bytes long. The data is // externally owned must be around at least as long as this object points to @@ -246,7 +224,6 @@ // and can extract from it. If this object refers to any shared data upon // entry, the reference to that data will be released. Is SWAP is set to true, // any data extracted will be endian swapped. -//---------------------------------------------------------------------- lldb::offset_t DataExtractor::SetData(const void *bytes, offset_t length, ByteOrder endian) { m_byte_order = endian; @@ -261,7 +238,6 @@ return GetByteSize(); } -//---------------------------------------------------------------------- // Assign the data for this object to be a subrange in "data" starting // "data_offset" bytes into "data" and ending "data_length" bytes later. If // "data_offset" is not a valid offset into "data", then this object will @@ -272,14 +248,11 @@ // a shared pointer to data, then the bytes referred to in "data" will need to // exist at least as long as this object refers to those bytes. The address // size and endian swap settings are copied from the current values in "data". -//---------------------------------------------------------------------- lldb::offset_t DataExtractor::SetData(const DataExtractor &data, offset_t data_offset, offset_t data_length) { m_addr_size = data.m_addr_size; -#ifdef LLDB_CONFIGURATION_DEBUG assert(m_addr_size == 4 || m_addr_size == 8); -#endif // If "data" contains shared pointer to data, then we can use that if (data.m_data_sp) { m_byte_order = data.m_byte_order; @@ -297,7 +270,6 @@ return 0; } -//---------------------------------------------------------------------- // Assign the data for this object to be a subrange of the shared data in // "data_sp" starting "data_offset" bytes into "data_sp" and ending // "data_length" bytes later. If "data_offset" is not a valid offset into @@ -309,7 +281,6 @@ // starting at "data_offset") to ensure the data stays around as long as it is // needed. The address size and endian swap settings will remain unchanged from // their current settings. -//---------------------------------------------------------------------- lldb::offset_t DataExtractor::SetData(const DataBufferSP &data_sp, offset_t data_offset, offset_t data_length) { @@ -342,30 +313,27 @@ return new_size; } -//---------------------------------------------------------------------- // Extract a single unsigned char from the binary data and update the offset // pointed to by "offset_ptr". // // RETURNS the byte that was extracted, or zero on failure. -//---------------------------------------------------------------------- uint8_t DataExtractor::GetU8(offset_t *offset_ptr) const { - const uint8_t *data = (const uint8_t *)GetData(offset_ptr, 1); + const uint8_t *data = static_cast<const uint8_t *>(GetData(offset_ptr, 1)); if (data) return *data; return 0; } -//---------------------------------------------------------------------- // Extract "count" unsigned chars from the binary data and update the offset // pointed to by "offset_ptr". The extracted data is copied into "dst". // // RETURNS the non-nullptr buffer pointer upon successful extraction of // all the requested bytes, or nullptr when the data is not available in the // buffer due to being out of bounds, or insufficient data. -//---------------------------------------------------------------------- void *DataExtractor::GetU8(offset_t *offset_ptr, void *dst, uint32_t count) const { - const uint8_t *data = (const uint8_t *)GetData(offset_ptr, count); + const uint8_t *data = + static_cast<const uint8_t *>(GetData(offset_ptr, count)); if (data) { // Copy the data into the buffer memcpy(dst, data, count); @@ -376,15 +344,14 @@ return nullptr; } -//---------------------------------------------------------------------- // Extract a single uint16_t from the data and update the offset pointed to by // "offset_ptr". // // RETURNS the uint16_t that was extracted, or zero on failure. -//---------------------------------------------------------------------- uint16_t DataExtractor::GetU16(offset_t *offset_ptr) const { uint16_t val = 0; - const uint8_t *data = (const uint8_t *)GetData(offset_ptr, sizeof(val)); + const uint8_t *data = + static_cast<const uint8_t *>(GetData(offset_ptr, sizeof(val))); if (data) { if (m_byte_order != endian::InlHostByteOrder()) val = ReadSwapInt16(data); @@ -424,21 +391,20 @@ return val; } -//---------------------------------------------------------------------- // Extract "count" uint16_t values from the binary data and update the offset // pointed to by "offset_ptr". The extracted data is copied into "dst". // // RETURNS the non-nullptr buffer pointer upon successful extraction of // all the requested bytes, or nullptr when the data is not available in the // buffer due to being out of bounds, or insufficient data. -//---------------------------------------------------------------------- void *DataExtractor::GetU16(offset_t *offset_ptr, void *void_dst, uint32_t count) const { const size_t src_size = sizeof(uint16_t) * count; - const uint16_t *src = (const uint16_t *)GetData(offset_ptr, src_size); + const uint16_t *src = + static_cast<const uint16_t *>(GetData(offset_ptr, src_size)); if (src) { if (m_byte_order != endian::InlHostByteOrder()) { - uint16_t *dst_pos = (uint16_t *)void_dst; + uint16_t *dst_pos = static_cast<uint16_t *>(void_dst); uint16_t *dst_end = dst_pos + count; const uint16_t *src_pos = src; while (dst_pos < dst_end) { @@ -456,15 +422,14 @@ return nullptr; } -//---------------------------------------------------------------------- // Extract a single uint32_t from the data and update the offset pointed to by // "offset_ptr". // // RETURNS the uint32_t that was extracted, or zero on failure. -//---------------------------------------------------------------------- uint32_t DataExtractor::GetU32(offset_t *offset_ptr) const { uint32_t val = 0; - const uint8_t *data = (const uint8_t *)GetData(offset_ptr, sizeof(val)); + const uint8_t *data = + static_cast<const uint8_t *>(GetData(offset_ptr, sizeof(val))); if (data) { if (m_byte_order != endian::InlHostByteOrder()) { val = ReadSwapInt32(data); @@ -475,21 +440,20 @@ return val; } -//---------------------------------------------------------------------- // Extract "count" uint32_t values from the binary data and update the offset // pointed to by "offset_ptr". The extracted data is copied into "dst". // // RETURNS the non-nullptr buffer pointer upon successful extraction of // all the requested bytes, or nullptr when the data is not available in the // buffer due to being out of bounds, or insufficient data. -//---------------------------------------------------------------------- void *DataExtractor::GetU32(offset_t *offset_ptr, void *void_dst, uint32_t count) const { const size_t src_size = sizeof(uint32_t) * count; - const uint32_t *src = (const uint32_t *)GetData(offset_ptr, src_size); + const uint32_t *src = + static_cast<const uint32_t *>(GetData(offset_ptr, src_size)); if (src) { if (m_byte_order != endian::InlHostByteOrder()) { - uint32_t *dst_pos = (uint32_t *)void_dst; + uint32_t *dst_pos = static_cast<uint32_t *>(void_dst); uint32_t *dst_end = dst_pos + count; const uint32_t *src_pos = src; while (dst_pos < dst_end) { @@ -507,15 +471,14 @@ return nullptr; } -//---------------------------------------------------------------------- // Extract a single uint64_t from the data and update the offset pointed to by // "offset_ptr". // // RETURNS the uint64_t that was extracted, or zero on failure. -//---------------------------------------------------------------------- uint64_t DataExtractor::GetU64(offset_t *offset_ptr) const { uint64_t val = 0; - const uint8_t *data = (const uint8_t *)GetData(offset_ptr, sizeof(val)); + const uint8_t *data = + static_cast<const uint8_t *>(GetData(offset_ptr, sizeof(val))); if (data) { if (m_byte_order != endian::InlHostByteOrder()) { val = ReadSwapInt64(data); @@ -526,20 +489,19 @@ return val; } -//---------------------------------------------------------------------- // GetU64 // // Get multiple consecutive 64 bit values. Return true if the entire read // succeeds and increment the offset pointed to by offset_ptr, else return // false and leave the offset pointed to by offset_ptr unchanged. -//---------------------------------------------------------------------- void *DataExtractor::GetU64(offset_t *offset_ptr, void *void_dst, uint32_t count) const { const size_t src_size = sizeof(uint64_t) * count; - const uint64_t *src = (const uint64_t *)GetData(offset_ptr, src_size); + const uint64_t *src = + static_cast<const uint64_t *>(GetData(offset_ptr, src_size)); if (src) { if (m_byte_order != endian::InlHostByteOrder()) { - uint64_t *dst_pos = (uint64_t *)void_dst; + uint64_t *dst_pos = static_cast<uint64_t *>(void_dst); uint64_t *dst_end = dst_pos + count; const uint64_t *src_pos = src; while (dst_pos < dst_end) { @@ -640,10 +602,11 @@ lsbcount = size * 8 - bitfield_bit_offset - bitfield_bit_size; if (lsbcount > 0) sval64 >>= lsbcount; - uint64_t bitfield_mask = (((uint64_t)1) << bitfield_bit_size) - 1; + uint64_t bitfield_mask = + ((static_cast<uint64_t>(1)) << bitfield_bit_size) - 1; sval64 &= bitfield_mask; // sign extend if needed - if (sval64 & (((uint64_t)1) << (bitfield_bit_size - 1))) + if (sval64 & ((static_cast<uint64_t>(1)) << (bitfield_bit_size - 1))) sval64 |= ~bitfield_mask; } return sval64; @@ -653,11 +616,12 @@ typedef float float_type; float_type val = 0.0; const size_t src_size = sizeof(float_type); - const float_type *src = (const float_type *)GetData(offset_ptr, src_size); + const float_type *src = + static_cast<const float_type *>(GetData(offset_ptr, src_size)); if (src) { if (m_byte_order != endian::InlHostByteOrder()) { - const uint8_t *src_data = (const uint8_t *)src; - uint8_t *dst_data = (uint8_t *)&val; + const uint8_t *src_data = reinterpret_cast<const uint8_t *>(src); + uint8_t *dst_data = reinterpret_cast<uint8_t *>(&val); for (size_t i = 0; i < sizeof(float_type); ++i) dst_data[sizeof(float_type) - 1 - i] = src_data[i]; } else { @@ -671,11 +635,12 @@ typedef double float_type; float_type val = 0.0; const size_t src_size = sizeof(float_type); - const float_type *src = (const float_type *)GetData(offset_ptr, src_size); + const float_type *src = + static_cast<const float_type *>(GetData(offset_ptr, src_size)); if (src) { if (m_byte_order != endian::InlHostByteOrder()) { - const uint8_t *src_data = (const uint8_t *)src; - uint8_t *dst_data = (uint8_t *)&val; + const uint8_t *src_data = reinterpret_cast<const uint8_t *>(src); + uint8_t *dst_data = reinterpret_cast<uint8_t *>(&val); for (size_t i = 0; i < sizeof(float_type); ++i) dst_data[sizeof(float_type) - 1 - i] = src_data[i]; } else { @@ -698,40 +663,30 @@ return val; } -//------------------------------------------------------------------ // Extract a single address from the data and update the offset pointed to by // "offset_ptr". The size of the extracted address comes from the // "this->m_addr_size" member variable and should be set correctly prior to // extracting any address values. // // RETURNS the address that was extracted, or zero on failure. -//------------------------------------------------------------------ uint64_t DataExtractor::GetAddress(offset_t *offset_ptr) const { -#ifdef LLDB_CONFIGURATION_DEBUG assert(m_addr_size == 4 || m_addr_size == 8); -#endif return GetMaxU64(offset_ptr, m_addr_size); } uint64_t DataExtractor::GetAddress_unchecked(offset_t *offset_ptr) const { -#ifdef LLDB_CONFIGURATION_DEBUG assert(m_addr_size == 4 || m_addr_size == 8); -#endif return GetMaxU64_unchecked(offset_ptr, m_addr_size); } -//------------------------------------------------------------------ // Extract a single pointer from the data and update the offset pointed to by // "offset_ptr". The size of the extracted pointer comes from the // "this->m_addr_size" member variable and should be set correctly prior to // extracting any pointer values. // // RETURNS the pointer that was extracted, or zero on failure. -//------------------------------------------------------------------ uint64_t DataExtractor::GetPointer(offset_t *offset_ptr) const { -#ifdef LLDB_CONFIGURATION_DEBUG assert(m_addr_size == 4 || m_addr_size == 8); -#endif return GetMaxU64(offset_ptr, m_addr_size); } @@ -745,7 +700,7 @@ length == 10 || length == 16 || length == 32); for (uint32_t i = 0; i < length; ++i) - ((uint8_t *)dst)[i] = src[length - i - 1]; + (static_cast<uint8_t *>(dst))[i] = src[length - i - 1]; } else ::memcpy(dst, src, length); return length; @@ -791,8 +746,8 @@ !(m_byte_order == eByteOrderBig || m_byte_order == eByteOrderLittle)) return 0; - uint8_t *dst = (uint8_t *)dst_void_ptr; - const uint8_t *src = (const uint8_t *)PeekData(src_offset, src_len); + uint8_t *dst = static_cast<uint8_t *>(dst_void_ptr); + const uint8_t *src = PeekData(src_offset, src_len); if (src) { if (dst_len >= src_len) { // We are copying the entire value from src into dst. Calculate how many, @@ -853,7 +808,6 @@ return 0; } -//---------------------------------------------------------------------- // Extracts a variable length NULL terminated C string from the data at the // offset pointed to by "offset_ptr". The "offset_ptr" will be updated with // the offset of the byte that follows the NULL terminator byte. @@ -861,12 +815,11 @@ // If the offset pointed to by "offset_ptr" is out of bounds, or if "length" is // non-zero and there aren't enough available bytes, nullptr will be returned // and "offset_ptr" will not be updated. -//---------------------------------------------------------------------- const char *DataExtractor::GetCStr(offset_t *offset_ptr) const { - const char *cstr = (const char *)PeekData(*offset_ptr, 1); + const char *cstr = reinterpret_cast<const char *>(PeekData(*offset_ptr, 1)); if (cstr) { const char *cstr_end = cstr; - const char *end = (const char *)m_end; + const char *end = reinterpret_cast<const char *>(m_end); while (cstr_end < end && *cstr_end) ++cstr_end; @@ -885,7 +838,6 @@ return nullptr; } -//---------------------------------------------------------------------- // Extracts a NULL terminated C string from the fixed length field of length // "len" at the offset pointed to by "offset_ptr". The "offset_ptr" will be // updated with the offset of the byte that follows the fixed length field. @@ -894,9 +846,8 @@ // plus the length of the field is out of bounds, or if the field does not // contain a NULL terminator byte, nullptr will be returned and "offset_ptr" // will not be updated. -//---------------------------------------------------------------------- const char *DataExtractor::GetCStr(offset_t *offset_ptr, offset_t len) const { - const char *cstr = (const char *)PeekData(*offset_ptr, len); + const char *cstr = reinterpret_cast<const char *>(PeekData(*offset_ptr, len)); if (cstr != nullptr) { if (memchr(cstr, '\0', len) == nullptr) { return nullptr; @@ -907,28 +858,24 @@ return nullptr; } -//------------------------------------------------------------------ // Peeks at a string in the contained data. No verification is done to make // sure the entire string lies within the bounds of this object's data, only // "offset" is verified to be a valid offset. // // Returns a valid C string pointer if "offset" is a valid offset in this // object's data, else nullptr is returned. -//------------------------------------------------------------------ const char *DataExtractor::PeekCStr(offset_t offset) const { - return (const char *)PeekData(offset, 1); + return reinterpret_cast<const char *>(PeekData(offset, 1)); } -//---------------------------------------------------------------------- // Extracts an unsigned LEB128 number from this object's data starting at the // offset pointed to by "offset_ptr". The offset pointed to by "offset_ptr" // will be updated with the offset of the byte following the last extracted // byte. // // Returned the extracted integer value. -//---------------------------------------------------------------------- uint64_t DataExtractor::GetULEB128(offset_t *offset_ptr) const { - const uint8_t *src = (const uint8_t *)PeekData(*offset_ptr, 1); + const uint8_t *src = PeekData(*offset_ptr, 1); if (src == nullptr) return 0; @@ -941,7 +888,7 @@ int shift = 7; while (src < end) { uint8_t byte = *src++; - result |= (uint64_t)(byte & 0x7f) << shift; + result |= static_cast<uint64_t>(byte & 0x7f) << shift; if ((byte & 0x80) == 0) break; shift += 7; @@ -954,16 +901,14 @@ return 0; } -//---------------------------------------------------------------------- // Extracts an signed LEB128 number from this object's data starting at the // offset pointed to by "offset_ptr". The offset pointed to by "offset_ptr" // will be updated with the offset of the byte following the last extracted // byte. // // Returned the extracted integer value. -//---------------------------------------------------------------------- int64_t DataExtractor::GetSLEB128(offset_t *offset_ptr) const { - const uint8_t *src = (const uint8_t *)PeekData(*offset_ptr, 1); + const uint8_t *src = PeekData(*offset_ptr, 1); if (src == nullptr) return 0; @@ -980,7 +925,7 @@ while (src < end) { bytecount++; byte = *src++; - result |= (int64_t)(byte & 0x7f) << shift; + result |= static_cast<int64_t>(byte & 0x7f) << shift; shift += 7; if ((byte & 0x80) == 0) break; @@ -996,17 +941,15 @@ return 0; } -//---------------------------------------------------------------------- // Skips a ULEB128 number (signed or unsigned) from this object's data starting // at the offset pointed to by "offset_ptr". The offset pointed to by // "offset_ptr" will be updated with the offset of the byte following the last // extracted byte. // // Returns the number of bytes consumed during the extraction. -//---------------------------------------------------------------------- uint32_t DataExtractor::Skip_LEB128(offset_t *offset_ptr) const { uint32_t bytes_consumed = 0; - const uint8_t *src = (const uint8_t *)PeekData(*offset_ptr, 1); + const uint8_t *src = PeekData(*offset_ptr, 1); if (src == nullptr) return 0; @@ -1021,7 +964,6 @@ return bytes_consumed; } -//---------------------------------------------------------------------- // Dumps bytes from this object's data to the stream "s" starting // "start_offset" bytes into this data, and ending with the byte before // "end_offset". "base_addr" will be added to the offset into the dumped data @@ -1031,7 +973,6 @@ // printf style formatting string. If "type_format" is nullptr, then an // appropriate format string will be used for the supplied "type". If the // stream "s" is nullptr, then the output will be send to Log(). -//---------------------------------------------------------------------- lldb::offset_t DataExtractor::PutToLog(Log *log, offset_t start_offset, offset_t length, uint64_t base_addr, uint32_t num_per_line, @@ -1055,7 +996,7 @@ // Reset string offset and fill the current line string with address: if (base_addr != LLDB_INVALID_ADDRESS) sstr.Printf("0x%8.8" PRIx64 ":", - (uint64_t)(base_addr + (offset - start_offset))); + static_cast<uint64_t>(base_addr + (offset - start_offset))); } switch (type) {
diff --git a/src/llvm-project/lldb/source/Utility/Environment.cpp b/src/llvm-project/lldb/source/Utility/Environment.cpp index ea20267..1405336 100644 --- a/src/llvm-project/lldb/source/Utility/Environment.cpp +++ b/src/llvm-project/lldb/source/Utility/Environment.cpp
@@ -1,9 +1,8 @@ //===-- Environment.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/Event.cpp b/src/llvm-project/lldb/source/Utility/Event.cpp index ad9f6e3..579d0da 100644 --- a/src/llvm-project/lldb/source/Utility/Event.cpp +++ b/src/llvm-project/lldb/source/Utility/Event.cpp
@@ -1,9 +1,8 @@ //===-- Event.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -26,9 +25,7 @@ #pragma mark - #pragma mark Event -//------------------------------------------------------------------ // Event functions -//------------------------------------------------------------------ Event::Event(Broadcaster *broadcaster, uint32_t event_type, EventData *data) : m_broadcaster_wp(broadcaster->GetBroadcasterImpl()), m_type(event_type), @@ -88,9 +85,7 @@ #pragma mark - #pragma mark EventData -//------------------------------------------------------------------ // EventData functions -//------------------------------------------------------------------ EventData::EventData() = default; @@ -101,9 +96,7 @@ #pragma mark - #pragma mark EventDataBytes -//------------------------------------------------------------------ // EventDataBytes functions -//------------------------------------------------------------------ EventDataBytes::EventDataBytes() : m_bytes() {} @@ -121,12 +114,12 @@ EventDataBytes::~EventDataBytes() = default; -const ConstString &EventDataBytes::GetFlavorString() { +ConstString EventDataBytes::GetFlavorString() { static ConstString g_flavor("EventDataBytes"); return g_flavor; } -const ConstString &EventDataBytes::GetFlavor() const { +ConstString EventDataBytes::GetFlavor() const { return EventDataBytes::GetFlavorString(); } @@ -150,7 +143,7 @@ void EventDataBytes::SetBytes(const void *src, size_t src_len) { if (src != nullptr && src_len > 0) - m_bytes.assign((const char *)src, src_len); + m_bytes.assign(static_cast<const char *>(src), src_len); else m_bytes.clear(); } @@ -194,9 +187,7 @@ #pragma mark - #pragma mark EventStructuredData -//------------------------------------------------------------------ // EventDataStructuredData definitions -//------------------------------------------------------------------ EventDataStructuredData::EventDataStructuredData() : EventData(), m_process_sp(), m_object_sp(), m_plugin_sp() {} @@ -209,11 +200,9 @@ EventDataStructuredData::~EventDataStructuredData() {} -//------------------------------------------------------------------ // EventDataStructuredData member functions -//------------------------------------------------------------------ -const ConstString &EventDataStructuredData::GetFlavor() const { +ConstString EventDataStructuredData::GetFlavor() const { return EventDataStructuredData::GetFlavorString(); } @@ -252,9 +241,7 @@ m_plugin_sp = plugin_sp; } -//------------------------------------------------------------------ // EventDataStructuredData static functions -//------------------------------------------------------------------ const EventDataStructuredData * EventDataStructuredData::GetEventDataFromEvent(const Event *event_ptr) { @@ -295,7 +282,7 @@ return StructuredDataPluginSP(); } -const ConstString &EventDataStructuredData::GetFlavorString() { +ConstString EventDataStructuredData::GetFlavorString() { static ConstString s_flavor("EventDataStructuredData"); return s_flavor; }
diff --git a/src/llvm-project/lldb/source/Utility/FileCollector.cpp b/src/llvm-project/lldb/source/Utility/FileCollector.cpp new file mode 100644 index 0000000..ed93591 --- /dev/null +++ b/src/llvm-project/lldb/source/Utility/FileCollector.cpp
@@ -0,0 +1,182 @@ +//===-- FileCollector.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/Utility/FileCollector.h" + +#include "llvm/ADT/SmallString.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/Process.h" + +using namespace lldb_private; +using namespace llvm; + +static bool IsCaseSensitivePath(StringRef path) { + SmallString<256> tmp_dest = path, upper_dest, real_dest; + + // Remove component traversals, links, etc. + if (!sys::fs::real_path(path, tmp_dest)) + return true; // Current default value in vfs.yaml + path = tmp_dest; + + // Change path to all upper case and ask for its real path, if the latter + // exists and is equal to path, it's not case sensitive. Default to case + // sensitive in the absence of real_path, since this is the YAMLVFSWriter + // default. + upper_dest = path.upper(); + if (sys::fs::real_path(upper_dest, real_dest) && path.equals(real_dest)) + return false; + return true; +} + +FileCollector::FileCollector(const FileSpec &root, const FileSpec &overlay_root) + : m_root(root), m_overlay_root(overlay_root) { + sys::fs::create_directories(m_root.GetPath(), true); +} + +bool FileCollector::GetRealPath(StringRef src_path, + SmallVectorImpl<char> &result) { + SmallString<256> real_path; + StringRef FileName = sys::path::filename(src_path); + std::string directory = sys::path::parent_path(src_path).str(); + auto dir_with_symlink = m_symlink_map.find(directory); + + // Use real_path to fix any symbolic link component present in a path. + // Computing the real path is expensive, cache the search through the + // parent path directory. + if (dir_with_symlink == m_symlink_map.end()) { + auto ec = sys::fs::real_path(directory, real_path); + if (ec) + return false; + m_symlink_map[directory] = real_path.str(); + } else { + real_path = dir_with_symlink->second; + } + + sys::path::append(real_path, FileName); + result.swap(real_path); + return true; +} + +void FileCollector::AddFile(const Twine &file) { + std::lock_guard<std::mutex> lock(m_mutex); + std::string file_str = file.str(); + if (MarkAsSeen(file_str)) + AddFileImpl(file_str); +} + +void FileCollector::AddFileImpl(StringRef src_path) { + std::string root = m_root.GetPath(); + + // We need an absolute src path to append to the root. + SmallString<256> absolute_src = src_path; + sys::fs::make_absolute(absolute_src); + + // Canonicalize src to a native path to avoid mixed separator styles. + sys::path::native(absolute_src); + + // Remove redundant leading "./" pieces and consecutive separators. + absolute_src = sys::path::remove_leading_dotslash(absolute_src); + + // Canonicalize the source path by removing "..", "." components. + SmallString<256> virtual_path = absolute_src; + sys::path::remove_dots(virtual_path, /*remove_dot_dot=*/true); + + // If a ".." component is present after a symlink component, remove_dots may + // lead to the wrong real destination path. Let the source be canonicalized + // like that but make sure we always use the real path for the destination. + SmallString<256> copy_from; + if (!GetRealPath(absolute_src, copy_from)) + copy_from = virtual_path; + + SmallString<256> dst_path = StringRef(root); + sys::path::append(dst_path, sys::path::relative_path(copy_from)); + + // Always map a canonical src path to its real path into the YAML, by doing + // this we map different virtual src paths to the same entry in the VFS + // overlay, which is a way to emulate symlink inside the VFS; this is also + // needed for correctness, not doing that can lead to module redefinition + // errors. + AddFileToMapping(virtual_path, dst_path); +} + +/// Set the access and modification time for the given file from the given +/// status object. +static std::error_code +CopyAccessAndModificationTime(StringRef filename, + const sys::fs::file_status &stat) { + int fd; + + if (auto ec = + sys::fs::openFileForWrite(filename, fd, sys::fs::CD_OpenExisting)) + return ec; + + if (auto ec = sys::fs::setLastAccessAndModificationTime( + fd, stat.getLastAccessedTime(), stat.getLastModificationTime())) + return ec; + + if (auto ec = sys::Process::SafelyCloseFileDescriptor(fd)) + return ec; + + return {}; +} + +std::error_code FileCollector::CopyFiles(bool stop_on_error) { + for (auto &entry : m_vfs_writer.getMappings()) { + // Create directory tree. + if (std::error_code ec = + sys::fs::create_directories(sys::path::parent_path(entry.RPath), + /*IgnoreExisting=*/true)) { + if (stop_on_error) + return ec; + } + + // Copy file over. + if (std::error_code ec = sys::fs::copy_file(entry.VPath, entry.RPath)) { + if (stop_on_error) + return ec; + } + + // Copy over permissions. + if (auto perms = sys::fs::getPermissions(entry.VPath)) { + if (std::error_code ec = sys::fs::setPermissions(entry.RPath, *perms)) { + if (stop_on_error) + return ec; + } + } + + // Copy over modification time. + sys::fs::file_status stat; + if (std::error_code ec = sys::fs::status(entry.VPath, stat)) { + if (stop_on_error) + return ec; + continue; + } + CopyAccessAndModificationTime(entry.RPath, stat); + } + return {}; +} + +std::error_code FileCollector::WriteMapping(const FileSpec &mapping_file) { + std::lock_guard<std::mutex> lock(m_mutex); + + std::string root = m_overlay_root.GetPath(); + + m_vfs_writer.setOverlayDir(root); + m_vfs_writer.setCaseSensitivity(IsCaseSensitivePath(root)); + m_vfs_writer.setUseExternalNames(false); + + std::error_code ec; + raw_fd_ostream os(mapping_file.GetPath(), ec, sys::fs::F_Text); + if (ec) + return ec; + + m_vfs_writer.write(os); + + return {}; +}
diff --git a/src/llvm-project/lldb/source/Utility/FileSpec.cpp b/src/llvm-project/lldb/source/Utility/FileSpec.cpp index 954968b..35d2240 100644 --- a/src/llvm-project/lldb/source/Utility/FileSpec.cpp +++ b/src/llvm-project/lldb/source/Utility/FileSpec.cpp
@@ -1,9 +1,8 @@ //===-- FileSpec.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -68,9 +67,7 @@ FileSpec::FileSpec() : m_style(GetNativeStyle()) {} -//------------------------------------------------------------------ // Default constructor that can take an optional full path to a file on disk. -//------------------------------------------------------------------ FileSpec::FileSpec(llvm::StringRef path, Style style) : m_style(style) { SetFile(path, style); } @@ -78,47 +75,33 @@ FileSpec::FileSpec(llvm::StringRef path, const llvm::Triple &Triple) : FileSpec{path, Triple.isOSWindows() ? Style::windows : Style::posix} {} -//------------------------------------------------------------------ // Copy constructor -//------------------------------------------------------------------ -FileSpec::FileSpec(const FileSpec &rhs) - : m_directory(rhs.m_directory), m_filename(rhs.m_filename), - m_is_resolved(rhs.m_is_resolved), m_style(rhs.m_style) {} - -//------------------------------------------------------------------ -// Copy constructor -//------------------------------------------------------------------ FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() { if (rhs) *this = *rhs; } -//------------------------------------------------------------------ // Virtual destructor in case anyone inherits from this class. -//------------------------------------------------------------------ FileSpec::~FileSpec() {} namespace { -//------------------------------------------------------------------ /// Safely get a character at the specified index. /// -/// @param[in] path +/// \param[in] path /// A full, partial, or relative path to a file. /// -/// @param[in] i +/// \param[in] i /// An index into path which may or may not be valid. /// -/// @return +/// \return /// The character at index \a i if the index is valid, or 0 if /// the index is not valid. -//------------------------------------------------------------------ inline char safeCharAtIndex(const llvm::StringRef &path, size_t i) { if (i < path.size()) return path[i]; return 0; } -//------------------------------------------------------------------ /// Check if a path needs to be normalized. /// /// Check if a path needs to be normalized. We currently consider a @@ -131,12 +114,11 @@ /// need normalization since we aren't trying to resolve the path, /// we are just trying to remove redundant things from the path. /// -/// @param[in] path +/// \param[in] path /// A full, partial, or relative path to a file. /// -/// @return +/// \return /// Returns \b true if the path needs to be normalized. -//------------------------------------------------------------------ bool needsNormalization(const llvm::StringRef &path) { if (path.empty()) return false; @@ -192,9 +174,7 @@ } -//------------------------------------------------------------------ // Assignment operator. -//------------------------------------------------------------------ const FileSpec &FileSpec::operator=(const FileSpec &rhs) { if (this != &rhs) { m_directory = rhs.m_directory; @@ -207,11 +187,9 @@ void FileSpec::SetFile(llvm::StringRef pathname) { SetFile(pathname, m_style); } -//------------------------------------------------------------------ // Update the contents of this object with a new path. The path will be split // up into a directory and filename and stored as uniqued string values for // quick comparison and efficient memory usage. -//------------------------------------------------------------------ void FileSpec::SetFile(llvm::StringRef pathname, Style style) { m_filename.Clear(); m_directory.Clear(); @@ -254,22 +232,18 @@ return SetFile(path, Triple.isOSWindows() ? Style::windows : Style::posix); } -//---------------------------------------------------------------------- // Convert to pointer operator. This allows code to check any FileSpec objects // to see if they contain anything valid using code such as: // // if (file_spec) // {} -//---------------------------------------------------------------------- FileSpec::operator bool() const { return m_filename || m_directory; } -//---------------------------------------------------------------------- // Logical NOT operator. This allows code to check any FileSpec objects to see // if they are invalid using code such as: // // if (!file_spec) // {} -//---------------------------------------------------------------------- bool FileSpec::operator!() const { return !m_directory && !m_filename; } bool FileSpec::DirectoryEquals(const FileSpec &rhs) const { @@ -282,43 +256,32 @@ return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive); } -//------------------------------------------------------------------ // Equal to operator -//------------------------------------------------------------------ bool FileSpec::operator==(const FileSpec &rhs) const { return FileEquals(rhs) && DirectoryEquals(rhs); } -//------------------------------------------------------------------ // Not equal to operator -//------------------------------------------------------------------ bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); } -//------------------------------------------------------------------ // Less than operator -//------------------------------------------------------------------ bool FileSpec::operator<(const FileSpec &rhs) const { return FileSpec::Compare(*this, rhs, true) < 0; } -//------------------------------------------------------------------ // Dump a FileSpec object to a stream -//------------------------------------------------------------------ Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) { f.Dump(&s); return s; } -//------------------------------------------------------------------ // Clear this object by releasing both the directory and filename string values // and making them both the empty string. -//------------------------------------------------------------------ void FileSpec::Clear() { m_directory.Clear(); m_filename.Clear(); } -//------------------------------------------------------------------ // Compare two FileSpec objects. If "full" is true, then both the directory and // the filename must match. If "full" is false, then the directory names for // "a" and "b" are only compared if they are both non-empty. This allows a @@ -327,7 +290,6 @@ // // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" and "1" if // "a" is greater than "b". -//------------------------------------------------------------------ int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) { int result = 0; @@ -366,11 +328,20 @@ return a == b; } -//------------------------------------------------------------------ +llvm::Optional<FileSpec::Style> FileSpec::GuessPathStyle(llvm::StringRef absolute_path) { + if (absolute_path.startswith("/")) + return Style::posix; + if (absolute_path.startswith(R"(\\)")) + return Style::windows; + if (absolute_path.size() > 3 && llvm::isAlpha(absolute_path[0]) && + absolute_path.substr(1, 2) == R"(:\)") + return Style::windows; + return llvm::None; +} + // Dump the object to the supplied stream. If the object contains a valid // directory name, it will be displayed followed by a directory delimiter, and // the filename. -//------------------------------------------------------------------ void FileSpec::Dump(Stream *s) const { if (s) { std::string path{GetPath(true)}; @@ -383,30 +354,20 @@ FileSpec::Style FileSpec::GetPathStyle() const { return m_style; } -//------------------------------------------------------------------ // Directory string get accessor. -//------------------------------------------------------------------ ConstString &FileSpec::GetDirectory() { return m_directory; } -//------------------------------------------------------------------ // Directory string const get accessor. -//------------------------------------------------------------------ -const ConstString &FileSpec::GetDirectory() const { return m_directory; } +ConstString FileSpec::GetDirectory() const { return m_directory; } -//------------------------------------------------------------------ // Filename string get accessor. -//------------------------------------------------------------------ ConstString &FileSpec::GetFilename() { return m_filename; } -//------------------------------------------------------------------ // Filename string const get accessor. -//------------------------------------------------------------------ -const ConstString &FileSpec::GetFilename() const { return m_filename; } +ConstString FileSpec::GetFilename() const { return m_filename; } -//------------------------------------------------------------------ // Extract the directory and path into a fixed buffer. This is needed as the // directory and path are stored in separate string values. -//------------------------------------------------------------------ size_t FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const { if (!path) @@ -452,10 +413,8 @@ return ConstString(llvm::sys::path::stem(m_filename.GetStringRef(), m_style)); } -//------------------------------------------------------------------ // Return the size in bytes that this object takes in memory. This returns the // size in bytes of this object, not any shared string values it may refer to. -//------------------------------------------------------------------ size_t FileSpec::MemorySize() const { return m_filename.MemorySize() + m_directory.MemorySize(); } @@ -516,15 +475,13 @@ } return false; } -//------------------------------------------------------------------ /// Returns true if the filespec represents an implementation source /// file (files with a ".c", ".cpp", ".m", ".mm" (many more) /// extension). /// -/// @return +/// \return /// \b true if the filespec represents an implementation source /// file, \b false otherwise. -//------------------------------------------------------------------ bool FileSpec::IsSourceImplementationFile() const { ConstString extension(GetFileNameExtension()); if (!extension) @@ -557,6 +514,11 @@ return llvm::sys::path::is_absolute(current_path, m_style); } +void FileSpec::MakeAbsolute(const FileSpec &dir) { + if (IsRelative()) + PrependPathComponent(dir); +} + void llvm::format_provider<FileSpec>::format(const FileSpec &F, raw_ostream &Stream, StringRef Style) {
diff --git a/src/llvm-project/lldb/source/Utility/IOObject.cpp b/src/llvm-project/lldb/source/Utility/IOObject.cpp index df7929c..5e3ccdd 100644 --- a/src/llvm-project/lldb/source/Utility/IOObject.cpp +++ b/src/llvm-project/lldb/source/Utility/IOObject.cpp
@@ -1,9 +1,8 @@ //===-- IOObject.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/JSON.cpp b/src/llvm-project/lldb/source/Utility/JSON.cpp index 725ea979..2c3f622 100644 --- a/src/llvm-project/lldb/source/Utility/JSON.cpp +++ b/src/llvm-project/lldb/source/Utility/JSON.cpp
@@ -1,9 +1,8 @@ //===--------------------- JSON.cpp -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -56,9 +55,9 @@ case DataType::Unsigned: return m_data.m_unsigned; case DataType::Signed: - return (uint64_t)m_data.m_signed; + return static_cast<uint64_t>(m_data.m_signed); case DataType::Double: - return (uint64_t)m_data.m_double; + return static_cast<uint64_t>(m_data.m_double); } llvm_unreachable("Unhandled data type"); } @@ -66,11 +65,11 @@ int64_t JSONNumber::GetAsSigned() const { switch (m_data_type) { case DataType::Unsigned: - return (int64_t)m_data.m_unsigned; + return static_cast<int64_t>(m_data.m_unsigned); case DataType::Signed: return m_data.m_signed; case DataType::Double: - return (int64_t)m_data.m_double; + return static_cast<int64_t>(m_data.m_double); } llvm_unreachable("Unhandled data type"); } @@ -78,9 +77,9 @@ double JSONNumber::GetAsDouble() const { switch (m_data_type) { case DataType::Unsigned: - return (double)m_data.m_unsigned; + return static_cast<double>(m_data.m_unsigned); case DataType::Signed: - return (double)m_data.m_signed; + return static_cast<double>(m_data.m_signed); case DataType::Double: return m_data.m_double; } @@ -239,7 +238,7 @@ break; case '"': { - while (1) { + while (true) { bool was_escaped = false; int escaped_ch = GetEscapedChar(was_escaped); if (escaped_ch == -1) { @@ -254,7 +253,7 @@ const bool is_null = escaped_ch == 0; if (was_escaped || (!is_end_quote && !is_null)) { if (CHAR_MIN <= escaped_ch && escaped_ch <= CHAR_MAX) { - value.append(1, (char)escaped_ch); + value.append(1, static_cast<char>(escaped_ch)); } else { error.Printf("error: wide character support is needed for unicode " "character 0x%4.4x at offset %" PRIu64, @@ -454,7 +453,7 @@ std::string value; std::string key; - while (1) { + while (true) { JSONParser::Token token = GetToken(value); if (token == JSONParser::Token::String) { @@ -485,7 +484,7 @@ std::string value; std::string key; - while (1) { + while (true) { JSONValue::SP value_sp = ParseJSONValue(); if (value_sp) array_up->AppendObject(value_sp);
diff --git a/src/llvm-project/lldb/source/Utility/LLDBAssert.cpp b/src/llvm-project/lldb/source/Utility/LLDBAssert.cpp index 3902c89..75530d8 100644 --- a/src/llvm-project/lldb/source/Utility/LLDBAssert.cpp +++ b/src/llvm-project/lldb/source/Utility/LLDBAssert.cpp
@@ -1,9 +1,8 @@ //===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -22,11 +21,16 @@ if (LLVM_LIKELY(expression)) return; + // In a Debug configuration lldb_assert() behaves like assert(0). + llvm_unreachable("lldb_assert failed"); + + // In a Release configuration it will print a warning and encourage the user + // to file a bug report, similar to LLVM’s crash handler, and then return + // execution. errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n", expr_text, func, file, line); errs() << "backtrace leading to the failure:\n"; llvm::sys::PrintStackTrace(errs()); errs() << "please file a bug report against lldb reporting this failure " "log, and as many details as possible\n"; - abort(); }
diff --git a/src/llvm-project/lldb/source/Utility/Listener.cpp b/src/llvm-project/lldb/source/Utility/Listener.cpp index a20859e..50c5640 100644 --- a/src/llvm-project/lldb/source/Utility/Listener.cpp +++ b/src/llvm-project/lldb/source/Utility/Listener.cpp
@@ -1,9 +1,8 @@ //===-- Listener.cpp --------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -28,8 +27,8 @@ class BroadcasterManagerWPMatcher { public: BroadcasterManagerWPMatcher(BroadcasterManagerSP manager_sp) - : m_manager_sp(manager_sp) {} - bool operator()(const BroadcasterManagerWP input_wp) const { + : m_manager_sp(std::move(manager_sp)) {} + bool operator()(const BroadcasterManagerWP &input_wp) const { BroadcasterManagerSP input_sp = input_wp.lock(); return (input_sp && input_sp == m_manager_sp); } @@ -192,7 +191,7 @@ end_iter = m_broadcaster_managers.end(); BroadcasterManagerWP manager_wp; - BroadcasterManagerWPMatcher matcher(manager_sp); + BroadcasterManagerWPMatcher matcher(std::move(manager_sp)); iter = std::find_if<broadcaster_manager_collection::iterator, BroadcasterManagerWPMatcher>( m_broadcaster_managers.begin(), end_iter, matcher); @@ -239,7 +238,7 @@ if (m_broadcaster_names) { bool found_source = false; - const ConstString &event_broadcaster_name = + ConstString event_broadcaster_name = event_sp->GetBroadcaster()->GetBroadcasterName(); for (uint32_t i = 0; i < m_num_broadcaster_names; ++i) { if (m_broadcaster_names[i] == event_broadcaster_name) { @@ -425,7 +424,7 @@ } uint32_t -Listener::StartListeningForEventSpec(BroadcasterManagerSP manager_sp, +Listener::StartListeningForEventSpec(const BroadcasterManagerSP &manager_sp, const BroadcastEventSpec &event_spec) { if (!manager_sp) return 0; @@ -453,7 +452,7 @@ return bits_acquired; } -bool Listener::StopListeningForEventSpec(BroadcasterManagerSP manager_sp, +bool Listener::StopListeningForEventSpec(const BroadcasterManagerSP &manager_sp, const BroadcastEventSpec &event_spec) { if (!manager_sp) return false;
diff --git a/src/llvm-project/lldb/source/Utility/Log.cpp b/src/llvm-project/lldb/source/Utility/Log.cpp index 2e8570b..217b0d2 100644 --- a/src/llvm-project/lldb/source/Utility/Log.cpp +++ b/src/llvm-project/lldb/source/Utility/Log.cpp
@@ -1,9 +1,8 @@ //===-- Log.cpp -------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -110,9 +109,7 @@ void Log::PutCString(const char *cstr) { Printf("%s", cstr); } void Log::PutString(llvm::StringRef str) { PutCString(str.str().c_str()); } -//---------------------------------------------------------------------- // Simple variable argument logging with flags. -//---------------------------------------------------------------------- void Log::Printf(const char *format, ...) { va_list args; va_start(args, format); @@ -120,11 +117,9 @@ va_end(args); } -//---------------------------------------------------------------------- // All logging eventually boils down to this function call. If we have a // callback registered, then we call the logging callback. If we have a valid // file handle, we also log to the file. -//---------------------------------------------------------------------- void Log::VAPrintf(const char *format, va_list args) { llvm::SmallString<64> FinalMessage; llvm::raw_svector_ostream Stream(FinalMessage); @@ -138,9 +133,7 @@ WriteMessage(FinalMessage.str()); } -//---------------------------------------------------------------------- // Printing of errors that are not fatal. -//---------------------------------------------------------------------- void Log::Error(const char *format, ...) { va_list args; va_start(args, format); @@ -155,9 +148,7 @@ Printf("error: %s", Content.c_str()); } -//---------------------------------------------------------------------- // Printing of warnings that are not fatal only if verbose mode is enabled. -//---------------------------------------------------------------------- void Log::Verbose(const char *format, ...) { if (!GetVerbose()) return; @@ -168,9 +159,7 @@ va_end(args); } -//---------------------------------------------------------------------- // Printing of warnings that are not fatal. -//---------------------------------------------------------------------- void Log::Warning(const char *format, ...) { llvm::SmallString<64> Content; va_list args;
diff --git a/src/llvm-project/lldb/source/Utility/Logging.cpp b/src/llvm-project/lldb/source/Utility/Logging.cpp index b97a88b..c0856e5 100644 --- a/src/llvm-project/lldb/source/Utility/Logging.cpp +++ b/src/llvm-project/lldb/source/Utility/Logging.cpp
@@ -1,9 +1,8 @@ //===-- Logging.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -18,6 +17,7 @@ static constexpr Log::Category g_categories[] = { {{"api"}, {"log API calls and return values"}, LIBLLDB_LOG_API}, + {{"ast"}, {"log AST"}, LIBLLDB_LOG_AST}, {{"break"}, {"log breakpoints"}, LIBLLDB_LOG_BREAKPOINTS}, {{"commands"}, {"log command argument parsing"}, LIBLLDB_LOG_COMMANDS}, {{"comm"}, {"log communication activities"}, LIBLLDB_LOG_COMMUNICATION},
diff --git a/src/llvm-project/lldb/source/Utility/NameMatches.cpp b/src/llvm-project/lldb/source/Utility/NameMatches.cpp index a76df3f..5c9579e 100644 --- a/src/llvm-project/lldb/source/Utility/NameMatches.cpp +++ b/src/llvm-project/lldb/source/Utility/NameMatches.cpp
@@ -1,9 +1,8 @@ //===-- NameMatches.cpp -----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/NameMatches.h"
diff --git a/src/llvm-project/lldb/source/Utility/PPC64LE_DWARF_Registers.h b/src/llvm-project/lldb/source/Utility/PPC64LE_DWARF_Registers.h index 1a75037..548c1fd 100644 --- a/src/llvm-project/lldb/source/Utility/PPC64LE_DWARF_Registers.h +++ b/src/llvm-project/lldb/source/Utility/PPC64LE_DWARF_Registers.h
@@ -1,9 +1,8 @@ //===-- PPC64LE_DWARF_Registers.h -------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/PPC64LE_ehframe_Registers.h b/src/llvm-project/lldb/source/Utility/PPC64LE_ehframe_Registers.h index c5763b3..77cb3e5 100644 --- a/src/llvm-project/lldb/source/Utility/PPC64LE_ehframe_Registers.h +++ b/src/llvm-project/lldb/source/Utility/PPC64LE_ehframe_Registers.h
@@ -1,9 +1,8 @@ //===-- PPC64LE_ehframe_Registers.h -----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/PPC64_DWARF_Registers.h b/src/llvm-project/lldb/source/Utility/PPC64_DWARF_Registers.h index 7e3619e..6ba5b6a 100644 --- a/src/llvm-project/lldb/source/Utility/PPC64_DWARF_Registers.h +++ b/src/llvm-project/lldb/source/Utility/PPC64_DWARF_Registers.h
@@ -1,9 +1,8 @@ //===-- PPC64_DWARF_Registers.h ---------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/ProcessInfo.cpp b/src/llvm-project/lldb/source/Utility/ProcessInfo.cpp new file mode 100644 index 0000000..b67ae87 --- /dev/null +++ b/src/llvm-project/lldb/source/Utility/ProcessInfo.cpp
@@ -0,0 +1,310 @@ +//===-- ProcessInfo.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/Utility/ProcessInfo.h" + +#include "lldb/Utility/ArchSpec.h" +#include "lldb/Utility/Stream.h" +#include "lldb/Utility/StreamString.h" +#include "lldb/Utility/UserIDResolver.h" +#include "llvm/ADT/SmallString.h" + +#include <climits> + +using namespace lldb; +using namespace lldb_private; + +ProcessInfo::ProcessInfo() + : m_executable(), m_arguments(), m_environment(), m_uid(UINT32_MAX), + m_gid(UINT32_MAX), m_arch(), m_pid(LLDB_INVALID_PROCESS_ID) {} + +ProcessInfo::ProcessInfo(const char *name, const ArchSpec &arch, + lldb::pid_t pid) + : m_executable(name), m_arguments(), m_environment(), m_uid(UINT32_MAX), + m_gid(UINT32_MAX), m_arch(arch), m_pid(pid) {} + +void ProcessInfo::Clear() { + m_executable.Clear(); + m_arguments.Clear(); + m_environment.clear(); + m_uid = UINT32_MAX; + m_gid = UINT32_MAX; + m_arch.Clear(); + m_pid = LLDB_INVALID_PROCESS_ID; +} + +const char *ProcessInfo::GetName() const { + return m_executable.GetFilename().GetCString(); +} + +size_t ProcessInfo::GetNameLength() const { + return m_executable.GetFilename().GetLength(); +} + +void ProcessInfo::Dump(Stream &s, Platform *platform) const { + s << "Executable: " << GetName() << "\n"; + s << "Triple: "; + m_arch.DumpTriple(s); + s << "\n"; + + s << "Arguments:\n"; + m_arguments.Dump(s); + + s.Format("Environment:\n{0}", m_environment); +} + +void ProcessInfo::SetExecutableFile(const FileSpec &exe_file, + bool add_exe_file_as_first_arg) { + if (exe_file) { + m_executable = exe_file; + if (add_exe_file_as_first_arg) { + llvm::SmallString<128> filename; + exe_file.GetPath(filename); + if (!filename.empty()) + m_arguments.InsertArgumentAtIndex(0, filename); + } + } else { + m_executable.Clear(); + } +} + +llvm::StringRef ProcessInfo::GetArg0() const { return m_arg0; } + +void ProcessInfo::SetArg0(llvm::StringRef arg) { m_arg0 = arg; } + +void ProcessInfo::SetArguments(char const **argv, + bool first_arg_is_executable) { + m_arguments.SetArguments(argv); + + // Is the first argument the executable? + if (first_arg_is_executable) { + const char *first_arg = m_arguments.GetArgumentAtIndex(0); + if (first_arg) { + // Yes the first argument is an executable, set it as the executable in + // the launch options. Don't resolve the file path as the path could be a + // remote platform path + m_executable.SetFile(first_arg, FileSpec::Style::native); + } + } +} + +void ProcessInfo::SetArguments(const Args &args, bool first_arg_is_executable) { + // Copy all arguments + m_arguments = args; + + // Is the first argument the executable? + if (first_arg_is_executable) { + const char *first_arg = m_arguments.GetArgumentAtIndex(0); + if (first_arg) { + // Yes the first argument is an executable, set it as the executable in + // the launch options. Don't resolve the file path as the path could be a + // remote platform path + m_executable.SetFile(first_arg, FileSpec::Style::native); + } + } +} + +void ProcessInstanceInfo::Dump(Stream &s, UserIDResolver &resolver) const { + if (m_pid != LLDB_INVALID_PROCESS_ID) + s.Printf(" pid = %" PRIu64 "\n", m_pid); + + if (m_parent_pid != LLDB_INVALID_PROCESS_ID) + s.Printf(" parent = %" PRIu64 "\n", m_parent_pid); + + if (m_executable) { + s.Printf(" name = %s\n", m_executable.GetFilename().GetCString()); + s.PutCString(" file = "); + m_executable.Dump(&s); + s.EOL(); + } + const uint32_t argc = m_arguments.GetArgumentCount(); + if (argc > 0) { + for (uint32_t i = 0; i < argc; i++) { + const char *arg = m_arguments.GetArgumentAtIndex(i); + if (i < 10) + s.Printf(" arg[%u] = %s\n", i, arg); + else + s.Printf("arg[%u] = %s\n", i, arg); + } + } + + s.Format("{0}", m_environment); + + if (m_arch.IsValid()) { + s.Printf(" arch = "); + m_arch.DumpTriple(s); + s.EOL(); + } + + if (UserIDIsValid()) { + s.Format(" uid = {0,-5} ({1})\n", GetUserID(), + resolver.GetUserName(GetUserID()).getValueOr("")); + } + if (GroupIDIsValid()) { + s.Format(" gid = {0,-5} ({1})\n", GetGroupID(), + resolver.GetGroupName(GetGroupID()).getValueOr("")); + } + if (EffectiveUserIDIsValid()) { + s.Format(" euid = {0,-5} ({1})\n", GetEffectiveUserID(), + resolver.GetUserName(GetEffectiveUserID()).getValueOr("")); + } + if (EffectiveGroupIDIsValid()) { + s.Format(" egid = {0,-5} ({1})\n", GetEffectiveGroupID(), + resolver.GetGroupName(GetEffectiveGroupID()).getValueOr("")); + } +} + +void ProcessInstanceInfo::DumpTableHeader(Stream &s, bool show_args, + bool verbose) { + const char *label; + if (show_args || verbose) + label = "ARGUMENTS"; + else + label = "NAME"; + + if (verbose) { + s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE " + " %s\n", + label); + s.PutCString("====== ====== ========== ========== ========== ========== " + "======================== ============================\n"); + } else { + s.Printf("PID PARENT USER TRIPLE %s\n", label); + s.PutCString("====== ====== ========== ======================== " + "============================\n"); + } +} + +void ProcessInstanceInfo::DumpAsTableRow(Stream &s, UserIDResolver &resolver, + bool show_args, bool verbose) const { + if (m_pid != LLDB_INVALID_PROCESS_ID) { + s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid); + + StreamString arch_strm; + if (m_arch.IsValid()) + m_arch.DumpTriple(arch_strm); + + auto print = [&](UserIDResolver::id_t id, + llvm::Optional<llvm::StringRef> (UserIDResolver::*get)( + UserIDResolver::id_t id)) { + if (auto name = (resolver.*get)(id)) + s.Format("{0,-10} ", *name); + else + s.Format("{0,-10} ", id); + }; + if (verbose) { + print(m_uid, &UserIDResolver::GetUserName); + print(m_gid, &UserIDResolver::GetGroupName); + print(m_euid, &UserIDResolver::GetUserName); + print(m_egid, &UserIDResolver::GetGroupName); + + s.Printf("%-24s ", arch_strm.GetData()); + } else { + print(m_euid, &UserIDResolver::GetUserName); + s.Printf(" %-24s ", arch_strm.GetData()); + } + + if (verbose || show_args) { + const uint32_t argc = m_arguments.GetArgumentCount(); + if (argc > 0) { + for (uint32_t i = 0; i < argc; i++) { + if (i > 0) + s.PutChar(' '); + s.PutCString(m_arguments.GetArgumentAtIndex(i)); + } + } + } else { + s.PutCString(GetName()); + } + + s.EOL(); + } +} + +bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const { + if (m_name_match_type == NameMatch::Ignore || process_name == nullptr) + return true; + const char *match_name = m_match_info.GetName(); + if (!match_name) + return true; + + return lldb_private::NameMatches(process_name, m_name_match_type, match_name); +} + +bool ProcessInstanceInfoMatch::Matches( + const ProcessInstanceInfo &proc_info) const { + if (!NameMatches(proc_info.GetName())) + return false; + + if (m_match_info.ProcessIDIsValid() && + m_match_info.GetProcessID() != proc_info.GetProcessID()) + return false; + + if (m_match_info.ParentProcessIDIsValid() && + m_match_info.GetParentProcessID() != proc_info.GetParentProcessID()) + return false; + + if (m_match_info.UserIDIsValid() && + m_match_info.GetUserID() != proc_info.GetUserID()) + return false; + + if (m_match_info.GroupIDIsValid() && + m_match_info.GetGroupID() != proc_info.GetGroupID()) + return false; + + if (m_match_info.EffectiveUserIDIsValid() && + m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID()) + return false; + + if (m_match_info.EffectiveGroupIDIsValid() && + m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID()) + return false; + + if (m_match_info.GetArchitecture().IsValid() && + !m_match_info.GetArchitecture().IsCompatibleMatch( + proc_info.GetArchitecture())) + return false; + return true; +} + +bool ProcessInstanceInfoMatch::MatchAllProcesses() const { + if (m_name_match_type != NameMatch::Ignore) + return false; + + if (m_match_info.ProcessIDIsValid()) + return false; + + if (m_match_info.ParentProcessIDIsValid()) + return false; + + if (m_match_info.UserIDIsValid()) + return false; + + if (m_match_info.GroupIDIsValid()) + return false; + + if (m_match_info.EffectiveUserIDIsValid()) + return false; + + if (m_match_info.EffectiveGroupIDIsValid()) + return false; + + if (m_match_info.GetArchitecture().IsValid()) + return false; + + if (m_match_all_users) + return false; + + return true; +} + +void ProcessInstanceInfoMatch::Clear() { + m_match_info.Clear(); + m_name_match_type = NameMatch::Ignore; + m_match_all_users = false; +}
diff --git a/src/llvm-project/lldb/source/Utility/RegisterValue.cpp b/src/llvm-project/lldb/source/Utility/RegisterValue.cpp index 27bffde..a01c35a 100644 --- a/src/llvm-project/lldb/source/Utility/RegisterValue.cpp +++ b/src/llvm-project/lldb/source/Utility/RegisterValue.cpp
@@ -1,9 +1,8 @@ //===-- RegisterValue.cpp ---------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -147,23 +146,25 @@ scalar = *(const uint8_t *)buffer.bytes; return true; case 2: - scalar = *(const uint16_t *)buffer.bytes; + scalar = *reinterpret_cast<const uint16_t *>(buffer.bytes); return true; case 4: - scalar = *(const uint32_t *)buffer.bytes; + scalar = *reinterpret_cast<const uint32_t *>(buffer.bytes); return true; case 8: - scalar = *(const uint64_t *)buffer.bytes; + scalar = *reinterpret_cast<const uint64_t *>(buffer.bytes); return true; case 16: case 32: + case 64: if (buffer.length % sizeof(uint64_t) == 0) { const auto length_in_bits = buffer.length * 8; const auto length_in_uint64 = buffer.length / sizeof(uint64_t); scalar = llvm::APInt(length_in_bits, - llvm::ArrayRef<uint64_t>((const uint64_t *)buffer.bytes, - length_in_uint64)); + llvm::ArrayRef<uint64_t>( + reinterpret_cast<const uint64_t *>(buffer.bytes), + length_in_uint64)); return true; } break; @@ -518,7 +519,7 @@ break; case 1: case 2: - return *(const uint16_t *)buffer.bytes; + return *reinterpret_cast<const uint16_t *>(buffer.bytes); } } break; } @@ -548,7 +549,7 @@ case 1: case 2: case 4: - return *(const uint32_t *)buffer.bytes; + return *reinterpret_cast<const uint32_t *>(buffer.bytes); } } break; } @@ -579,11 +580,11 @@ case 1: return *(const uint8_t *)buffer.bytes; case 2: - return *(const uint16_t *)buffer.bytes; + return *reinterpret_cast<const uint16_t *>(buffer.bytes); case 4: - return *(const uint32_t *)buffer.bytes; + return *reinterpret_cast<const uint32_t *>(buffer.bytes); case 8: - return *(const uint64_t *)buffer.bytes; + return *reinterpret_cast<const uint64_t *>(buffer.bytes); } } break; } @@ -618,7 +619,7 @@ case 8: case 16: return llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, - ((const type128 *)buffer.bytes)->x); + (reinterpret_cast<const type128 *>(buffer.bytes))->x); } } break; }
diff --git a/src/llvm-project/lldb/source/Utility/RegularExpression.cpp b/src/llvm-project/lldb/source/Utility/RegularExpression.cpp index 54f7733..0192e8b 100644 --- a/src/llvm-project/lldb/source/Utility/RegularExpression.cpp +++ b/src/llvm-project/lldb/source/Utility/RegularExpression.cpp
@@ -1,9 +1,8 @@ //===-- RegularExpression.cpp -----------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,10 +12,8 @@ #include <string> -//---------------------------------------------------------------------- // Enable enhanced mode if it is available. This allows for things like \d for // digit, \s for space, and many more, but it isn't available everywhere. -//---------------------------------------------------------------------- #if defined(REG_ENHANCED) #define DEFAULT_COMPILE_FLAGS (REG_ENHANCED | REG_EXTENDED) #else @@ -29,18 +26,15 @@ memset(&m_preg, 0, sizeof(m_preg)); } -//---------------------------------------------------------------------- // Constructor that compiles "re" using "flags" and stores the resulting // compiled regular expression into this object. -//---------------------------------------------------------------------- RegularExpression::RegularExpression(llvm::StringRef str) - : m_re(), m_comp_err(1), m_preg() { - memset(&m_preg, 0, sizeof(m_preg)); + : RegularExpression() { Compile(str); } -RegularExpression::RegularExpression(const RegularExpression &rhs) { - memset(&m_preg, 0, sizeof(m_preg)); +RegularExpression::RegularExpression(const RegularExpression &rhs) + : RegularExpression() { Compile(rhs.GetText()); } @@ -51,15 +45,12 @@ return *this; } -//---------------------------------------------------------------------- // Destructor // // Any previously compiled regular expression contained in this object will be // freed. -//---------------------------------------------------------------------- RegularExpression::~RegularExpression() { Free(); } -//---------------------------------------------------------------------- // Compile a regular expression using the supplied regular expression text and // flags. The compiled regular expression lives in this object so that it can // be readily used for regular expression matches. Execute() can be called @@ -69,7 +60,6 @@ // RETURNS // True if the regular expression compiles successfully, false // otherwise. -//---------------------------------------------------------------------- bool RegularExpression::Compile(llvm::StringRef str) { Free(); @@ -80,13 +70,11 @@ return m_comp_err == 0; } -//---------------------------------------------------------------------- // Execute a regular expression match using the compiled regular expression // that is already in this object against the match string "s". If any parens // are used for regular expression matches "match_count" should indicate the // number of regmatch_t values that are present in "match_ptr". The regular // expression will be executed using the "execute_flags". -//--------------------------------------------------------------------- bool RegularExpression::Execute(llvm::StringRef str, Match *match) const { int err = 1; if (m_comp_err == 0) { @@ -155,19 +143,13 @@ return false; } -//---------------------------------------------------------------------- // Returns true if the regular expression compiled and is ready for execution. -//---------------------------------------------------------------------- bool RegularExpression::IsValid() const { return m_comp_err == 0; } -//---------------------------------------------------------------------- // Returns the text that was used to compile the current regular expression. -//---------------------------------------------------------------------- llvm::StringRef RegularExpression::GetText() const { return m_re; } -//---------------------------------------------------------------------- // Free any contained compiled regular expressions. -//---------------------------------------------------------------------- void RegularExpression::Free() { if (m_comp_err == 0) { m_re.clear();
diff --git a/src/llvm-project/lldb/source/Utility/Reproducer.cpp b/src/llvm-project/lldb/source/Utility/Reproducer.cpp index 6e85ba4..479ed31 100644 --- a/src/llvm-project/lldb/source/Utility/Reproducer.cpp +++ b/src/llvm-project/lldb/source/Utility/Reproducer.cpp
@@ -1,9 +1,8 @@ //===-- Reproducer.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -52,6 +51,8 @@ return Error::success(); } +bool Reproducer::Initialized() { return InstanceImpl().operator bool(); } + void Reproducer::Terminate() { lldbassert(InstanceImpl() && "Already terminated."); InstanceImpl().reset(); @@ -178,10 +179,13 @@ sys::fs::OpenFlags::F_None); yaml::Output yout(*strm); + std::vector<std::string> files; + files.reserve(m_providers.size()); for (auto &provider : m_providers) { - auto &provider_info = provider.second->GetInfo(); - yout << const_cast<ProviderInfo &>(provider_info); + files.emplace_back(provider.second->GetFile()); } + + yout << files; } Loader::Loader(const FileSpec &root) : m_root(root), m_loaded(false) {} @@ -196,30 +200,86 @@ if (auto err = error_or_file.getError()) return make_error<StringError>("unable to load reproducer index", err); - std::vector<ProviderInfo> provider_info; yaml::Input yin((*error_or_file)->getBuffer()); - yin >> provider_info; - + yin >> m_files; if (auto err = yin.error()) return make_error<StringError>("unable to read reproducer index", err); - for (auto &info : provider_info) - m_provider_info[info.name] = info; + // Sort files to speed up search. + llvm::sort(m_files); + // Remember that we've loaded the index. m_loaded = true; return llvm::Error::success(); } -llvm::Optional<ProviderInfo> Loader::GetProviderInfo(StringRef name) { +bool Loader::HasFile(StringRef file) { assert(m_loaded); + auto it = std::lower_bound(m_files.begin(), m_files.end(), file.str()); + return (it != m_files.end()) && (*it == file); +} - auto it = m_provider_info.find(name); - if (it == m_provider_info.end()) - return llvm::None; +llvm::Expected<std::unique_ptr<DataRecorder>> +DataRecorder::Create(const FileSpec &filename) { + std::error_code ec; + auto recorder = llvm::make_unique<DataRecorder>(std::move(filename), ec); + if (ec) + return llvm::errorCodeToError(ec); + return std::move(recorder); +} - return it->second; +DataRecorder *CommandProvider::GetNewDataRecorder() { + std::size_t i = m_data_recorders.size() + 1; + std::string filename = (llvm::Twine(Info::name) + llvm::Twine("-") + + llvm::Twine(i) + llvm::Twine(".txt")) + .str(); + auto recorder_or_error = + DataRecorder::Create(GetRoot().CopyByAppendingPathComponent(filename)); + if (!recorder_or_error) { + llvm::consumeError(recorder_or_error.takeError()); + return nullptr; + } + + m_data_recorders.push_back(std::move(*recorder_or_error)); + return m_data_recorders.back().get(); +} + +void CommandProvider::Keep() { + std::vector<std::string> files; + for (auto &recorder : m_data_recorders) { + recorder->Stop(); + files.push_back(recorder->GetFilename().GetPath()); + } + + FileSpec file = GetRoot().CopyByAppendingPathComponent(Info::file); + std::error_code ec; + llvm::raw_fd_ostream os(file.GetPath(), ec, llvm::sys::fs::F_Text); + if (ec) + return; + yaml::Output yout(os); + yout << files; +} + +void CommandProvider::Discard() { m_data_recorders.clear(); } + +void VersionProvider::Keep() { + FileSpec file = GetRoot().CopyByAppendingPathComponent(Info::file); + std::error_code ec; + llvm::raw_fd_ostream os(file.GetPath(), ec, llvm::sys::fs::F_Text); + if (ec) + return; + os << m_version << "\n"; } void ProviderBase::anchor() {} char ProviderBase::ID = 0; +char CommandProvider::ID = 0; +char FileProvider::ID = 0; +char VersionProvider::ID = 0; +const char *CommandProvider::Info::file = "command-interpreter.yaml"; +const char *CommandProvider::Info::name = "command-interpreter"; +const char *FileProvider::Info::file = "files.yaml"; +const char *FileProvider::Info::name = "files"; +const char *VersionProvider::Info::file = "version.txt"; +const char *VersionProvider::Info::name = "version";
diff --git a/src/llvm-project/lldb/source/Utility/ReproducerInstrumentation.cpp b/src/llvm-project/lldb/source/Utility/ReproducerInstrumentation.cpp new file mode 100644 index 0000000..473786e --- /dev/null +++ b/src/llvm-project/lldb/source/Utility/ReproducerInstrumentation.cpp
@@ -0,0 +1,122 @@ +//===-- ReproducerInstrumentation.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/Utility/ReproducerInstrumentation.h" +#include "lldb/Utility/Reproducer.h" + +using namespace lldb_private; +using namespace lldb_private::repro; + +void *IndexToObject::GetObjectForIndexImpl(unsigned idx) { + return m_mapping.lookup(idx); +} + +void IndexToObject::AddObjectForIndexImpl(unsigned idx, void *object) { + assert(idx != 0 && "Cannot add object for sentinel"); + m_mapping[idx] = object; +} + +template <> char *Deserializer::Deserialize<char *>() { + return const_cast<char *>(Deserialize<const char *>()); +} + +template <> const char *Deserializer::Deserialize<const char *>() { + auto pos = m_buffer.find('\0'); + if (pos == llvm::StringRef::npos) + return nullptr; + const char *str = m_buffer.data(); + m_buffer = m_buffer.drop_front(pos + 1); + return str; +} + +bool Registry::Replay(const FileSpec &file) { + auto error_or_file = llvm::MemoryBuffer::getFile(file.GetPath()); + if (auto err = error_or_file.getError()) + return false; + + return Replay((*error_or_file)->getBuffer()); +} + +bool Registry::Replay(llvm::StringRef buffer) { +#ifndef LLDB_REPRO_INSTR_TRACE + Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); +#endif + + Deserializer deserializer(buffer); + while (deserializer.HasData(1)) { + unsigned id = deserializer.Deserialize<unsigned>(); + +#ifndef LLDB_REPRO_INSTR_TRACE + LLDB_LOG(log, "Replaying {0}: {1}", id, GetSignature(id)); +#else + llvm::errs() << "Replaying " << id << ": " << GetSignature(id) << "\n"; +#endif + + GetReplayer(id)->operator()(deserializer); + } + + return true; +} + +void Registry::DoRegister(uintptr_t RunID, std::unique_ptr<Replayer> replayer, + SignatureStr signature) { + const unsigned id = m_replayers.size() + 1; + assert(m_replayers.find(RunID) == m_replayers.end()); + m_replayers[RunID] = std::make_pair(std::move(replayer), id); + m_ids[id] = + std::make_pair(m_replayers[RunID].first.get(), std::move(signature)); +} + +unsigned Registry::GetID(uintptr_t addr) { + unsigned id = m_replayers[addr].second; + assert(id != 0 && "Forgot to add function to registry?"); + return id; +} + +std::string Registry::GetSignature(unsigned id) { + assert(m_ids.count(id) != 0 && "ID not in registry"); + return m_ids[id].second.ToString(); +} + +Replayer *Registry::GetReplayer(unsigned id) { + assert(m_ids.count(id) != 0 && "ID not in registry"); + return m_ids[id].first; +} + +std::string Registry::SignatureStr::ToString() const { + return (result + (result.empty() ? "" : " ") + scope + "::" + name + args) + .str(); +} + +unsigned ObjectToIndex::GetIndexForObjectImpl(const void *object) { + unsigned index = m_mapping.size() + 1; + auto it = m_mapping.find(object); + if (it == m_mapping.end()) + m_mapping[object] = index; + return m_mapping[object]; +} + +Recorder::Recorder(llvm::StringRef pretty_func, std::string &&pretty_args) + : m_serializer(nullptr), m_pretty_func(pretty_func), + m_pretty_args(pretty_args), m_local_boundary(false), + m_result_recorded(true) { + if (!g_global_boundary) { + g_global_boundary = true; + m_local_boundary = true; + + LLDB_LOG(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API), "{0} ({1})", + m_pretty_func, m_pretty_args); + } +} + +Recorder::~Recorder() { + assert(m_result_recorded && "Did you forget LLDB_RECORD_RESULT?"); + UpdateBoundary(); +} + +bool lldb_private::repro::Recorder::g_global_boundary;
diff --git a/src/llvm-project/lldb/source/Utility/Scalar.cpp b/src/llvm-project/lldb/source/Utility/Scalar.cpp index a2bb86f..23d50b9 100644 --- a/src/llvm-project/lldb/source/Utility/Scalar.cpp +++ b/src/llvm-project/lldb/source/Utility/Scalar.cpp
@@ -1,9 +1,8 @@ //===-- Scalar.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -13,6 +12,7 @@ #include "lldb/Utility/Endian.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/StreamString.h" #include "lldb/lldb-types.h" #include "llvm/ADT/SmallString.h" @@ -23,10 +23,8 @@ using namespace lldb; using namespace lldb_private; -//---------------------------------------------------------------------- // Promote to max type currently follows the ANSI C rule for type promotion in // expressions. -//---------------------------------------------------------------------- static Scalar::Type PromoteToMaxType( const Scalar &lhs, // The const left hand side object const Scalar &rhs, // The const right hand side object @@ -71,10 +69,7 @@ return Scalar::e_void; } -Scalar::Scalar() : m_type(e_void), m_float((float)0) {} - -Scalar::Scalar(const Scalar &rhs) - : m_type(rhs.m_type), m_integer(rhs.m_integer), m_float(rhs.m_float) {} +Scalar::Scalar() : m_type(e_void), m_float(static_cast<float>(0)) {} bool Scalar::GetData(DataExtractor &data, size_t limit_byte_size) const { size_t byte_size = GetByteSize(); @@ -107,7 +102,7 @@ const uint8_t *bytes; static float_t flt_val; static double_t dbl_val; - static uint64_t swapped_words[4]; + static uint64_t swapped_words[8]; switch (m_type) { case e_void: break; @@ -126,12 +121,12 @@ bytes += 8 - byte_size; } return bytes; + // getRawData always returns a pointer to an array of uint64_t values, + // where the least-significant word always comes first. On big-endian + // systems we need to swap the words. case e_sint128: case e_uint128: apint_words = m_integer.getRawData(); - // getRawData always returns a pointer to an array of two uint64_t values, - // where the least-significant word always comes first. On big-endian - // systems we need to swap the two words. if (endian::InlHostByteOrder() == eByteOrderBig) { swapped_words[0] = apint_words[1]; swapped_words[1] = apint_words[0]; @@ -141,9 +136,6 @@ case e_sint256: case e_uint256: apint_words = m_integer.getRawData(); - // getRawData always returns a pointer to an array of four uint64_t values, - // where the least-significant word always comes first. On big-endian - // systems we need to swap the four words. if (endian::InlHostByteOrder() == eByteOrderBig) { swapped_words[0] = apint_words[3]; swapped_words[1] = apint_words[2]; @@ -152,6 +144,21 @@ apint_words = swapped_words; } return reinterpret_cast<const void *>(apint_words); + case e_sint512: + case e_uint512: + apint_words = m_integer.getRawData(); + if (endian::InlHostByteOrder() == eByteOrderBig) { + swapped_words[0] = apint_words[7]; + swapped_words[1] = apint_words[6]; + swapped_words[2] = apint_words[5]; + swapped_words[3] = apint_words[4]; + swapped_words[4] = apint_words[3]; + swapped_words[5] = apint_words[2]; + swapped_words[6] = apint_words[1]; + swapped_words[7] = apint_words[0]; + apint_words = swapped_words; + } + return reinterpret_cast<const void *>(apint_words); case e_float: flt_val = m_float.convertToFloat(); return reinterpret_cast<const void *>(&flt_val); @@ -188,6 +195,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: return (m_integer.getBitWidth() / 8); case e_float: return sizeof(float_t); @@ -214,6 +223,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_uint512: + case e_sint512: return llvm::APInt::isSameValue(zero_int, m_integer); case e_float: case e_double: @@ -235,6 +246,7 @@ case e_slonglong: case e_sint128: case e_sint256: + case e_sint512: s->PutCString(m_integer.toString(10, true)); break; case e_uint: @@ -242,6 +254,7 @@ case e_ulonglong: case e_uint128: case e_uint256: + case e_uint512: s->PutCString(m_integer.toString(10, false)); break; case e_float: @@ -278,6 +291,10 @@ return "int256_t"; case e_uint256: return "unsigned int256_t"; + case e_sint512: + return "int512_t"; + case e_uint512: + return "unsigned int512_t"; case e_float: return "float"; case e_double: @@ -348,13 +365,13 @@ Scalar &Scalar::operator=(long double v) { m_type = e_long_double; if (m_ieee_quad) - m_float = llvm::APFloat( - llvm::APFloat::IEEEquad(), - llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, ((type128 *)&v)->x)); + m_float = llvm::APFloat(llvm::APFloat::IEEEquad(), + llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, + (reinterpret_cast<type128 *>(&v))->x)); else - m_float = llvm::APFloat( - llvm::APFloat::x87DoubleExtended(), - llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, ((type128 *)&v)->x)); + m_float = llvm::APFloat(llvm::APFloat::x87DoubleExtended(), + llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, + (reinterpret_cast<type128 *>(&v))->x)); return *this; } @@ -387,6 +404,12 @@ else m_type = e_uint256; break; + case 512: + if (m_integer.isSignedIntN(BITWIDTH_INT512)) + m_type = e_sint512; + else + m_type = e_uint512; + break; } return *this; } @@ -443,6 +466,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.sextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, true, @@ -507,6 +536,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.zextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, false, @@ -567,6 +602,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.sextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, true, @@ -623,6 +664,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.zextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, false, @@ -675,6 +722,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.sextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, true, @@ -723,6 +776,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.zextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, false, @@ -771,6 +830,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.sextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, true, @@ -815,6 +880,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.zextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, false, @@ -859,6 +930,12 @@ success = true; break; + case e_sint512: + case e_uint512: + m_integer = m_integer.zextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, true, @@ -899,6 +976,13 @@ case e_uint256: success = true; break; + + case e_sint512: + case e_uint512: + m_integer = m_integer.zextOrTrunc(BITWIDTH_INT512); + success = true; + break; + case e_float: m_float = llvm::APFloat(llvm::APFloat::IEEEsingle()); m_float.convertFromAPInt(m_integer, false, @@ -923,6 +1007,11 @@ } break; + case e_sint512: + case e_uint512: + lldbassert(false && "unimplemented"); + break; + case e_float: switch (type) { case e_void: @@ -936,12 +1025,14 @@ case e_uint128: case e_sint256: case e_uint256: + case e_uint512: + case e_sint512: break; case e_float: success = true; break; case e_double: - m_float = llvm::APFloat((double_t)m_float.convertToFloat()); + m_float = llvm::APFloat(static_cast<double_t>(m_float.convertToFloat())); success = true; break; @@ -969,6 +1060,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: case e_float: break; case e_double: @@ -998,6 +1091,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: case e_float: case e_double: break; @@ -1043,6 +1138,10 @@ return "int256_t"; case e_uint256: return "uint256_t"; + case e_sint512: + return "int512_t"; + case e_uint512: + return "uint512_t"; } return "???"; } @@ -1120,6 +1219,13 @@ m_type = e_sint256; success = true; break; + case e_sint512: + success = true; + break; + case e_uint512: + m_type = e_sint512; + success = true; + break; case e_float: success = true; break; @@ -1175,6 +1281,13 @@ case e_uint256: success = true; break; + case e_sint512: + m_type = e_uint512; + success = true; + break; + case e_uint512: + success = true; + break; case e_float: success = true; break; @@ -1203,14 +1316,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (schar_t)(m_integer.sextOrTrunc(sizeof(schar_t) * 8)).getSExtValue(); + case e_sint512: + case e_uint512: + return static_cast<schar_t>( + (m_integer.sextOrTrunc(sizeof(schar_t) * 8)).getSExtValue()); case e_float: - return (schar_t)m_float.convertToFloat(); + return static_cast<schar_t>(m_float.convertToFloat()); case e_double: - return (schar_t)m_float.convertToDouble(); + return static_cast<schar_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (schar_t)(ldbl_val.sextOrTrunc(sizeof(schar_t) * 8)).getSExtValue(); + return static_cast<schar_t>( + (ldbl_val.sextOrTrunc(sizeof(schar_t) * 8)).getSExtValue()); } return fail_value; } @@ -1229,14 +1346,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (uchar_t)(m_integer.zextOrTrunc(sizeof(uchar_t) * 8)).getZExtValue(); + case e_sint512: + case e_uint512: + return static_cast<uchar_t>( + (m_integer.zextOrTrunc(sizeof(uchar_t) * 8)).getZExtValue()); case e_float: - return (uchar_t)m_float.convertToFloat(); + return static_cast<uchar_t>(m_float.convertToFloat()); case e_double: - return (uchar_t)m_float.convertToDouble(); + return static_cast<uchar_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (uchar_t)(ldbl_val.zextOrTrunc(sizeof(uchar_t) * 8)).getZExtValue(); + return static_cast<uchar_t>( + (ldbl_val.zextOrTrunc(sizeof(uchar_t) * 8)).getZExtValue()); } return fail_value; } @@ -1255,16 +1376,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (sshort_t)(m_integer.sextOrTrunc(sizeof(sshort_t) * 8)) - .getSExtValue(); + case e_sint512: + case e_uint512: + return static_cast<sshort_t>( + (m_integer.sextOrTrunc(sizeof(sshort_t) * 8)).getSExtValue()); case e_float: - return (sshort_t)m_float.convertToFloat(); + return static_cast<sshort_t>(m_float.convertToFloat()); case e_double: - return (sshort_t)m_float.convertToDouble(); + return static_cast<sshort_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (sshort_t)(ldbl_val.sextOrTrunc(sizeof(sshort_t) * 8)) - .getSExtValue(); + return static_cast<sshort_t>( + (ldbl_val.sextOrTrunc(sizeof(sshort_t) * 8)).getSExtValue()); } return fail_value; } @@ -1283,16 +1406,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (ushort_t)(m_integer.zextOrTrunc(sizeof(ushort_t) * 8)) - .getZExtValue(); + case e_sint512: + case e_uint512: + return static_cast<ushort_t>( + (m_integer.zextOrTrunc(sizeof(ushort_t) * 8)).getZExtValue()); case e_float: - return (ushort_t)m_float.convertToFloat(); + return static_cast<ushort_t>(m_float.convertToFloat()); case e_double: - return (ushort_t)m_float.convertToDouble(); + return static_cast<ushort_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (ushort_t)(ldbl_val.zextOrTrunc(sizeof(ushort_t) * 8)) - .getZExtValue(); + return static_cast<ushort_t>( + (ldbl_val.zextOrTrunc(sizeof(ushort_t) * 8)).getZExtValue()); } return fail_value; } @@ -1311,14 +1436,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (sint_t)(m_integer.sextOrTrunc(sizeof(sint_t) * 8)).getSExtValue(); + case e_sint512: + case e_uint512: + return static_cast<sint_t>( + (m_integer.sextOrTrunc(sizeof(sint_t) * 8)).getSExtValue()); case e_float: - return (sint_t)m_float.convertToFloat(); + return static_cast<sint_t>(m_float.convertToFloat()); case e_double: - return (sint_t)m_float.convertToDouble(); + return static_cast<sint_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (sint_t)(ldbl_val.sextOrTrunc(sizeof(sint_t) * 8)).getSExtValue(); + return static_cast<sint_t>( + (ldbl_val.sextOrTrunc(sizeof(sint_t) * 8)).getSExtValue()); } return fail_value; } @@ -1337,14 +1466,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (uint_t)(m_integer.zextOrTrunc(sizeof(uint_t) * 8)).getZExtValue(); + case e_sint512: + case e_uint512: + return static_cast<uint_t>( + (m_integer.zextOrTrunc(sizeof(uint_t) * 8)).getZExtValue()); case e_float: - return (uint_t)m_float.convertToFloat(); + return static_cast<uint_t>(m_float.convertToFloat()); case e_double: - return (uint_t)m_float.convertToDouble(); + return static_cast<uint_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (uint_t)(ldbl_val.zextOrTrunc(sizeof(uint_t) * 8)).getZExtValue(); + return static_cast<uint_t>( + (ldbl_val.zextOrTrunc(sizeof(uint_t) * 8)).getZExtValue()); } return fail_value; } @@ -1363,14 +1496,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (slong_t)(m_integer.sextOrTrunc(sizeof(slong_t) * 8)).getSExtValue(); + case e_sint512: + case e_uint512: + return static_cast<slong_t>( + (m_integer.sextOrTrunc(sizeof(slong_t) * 8)).getSExtValue()); case e_float: - return (slong_t)m_float.convertToFloat(); + return static_cast<slong_t>(m_float.convertToFloat()); case e_double: - return (slong_t)m_float.convertToDouble(); + return static_cast<slong_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (slong_t)(ldbl_val.sextOrTrunc(sizeof(slong_t) * 8)).getSExtValue(); + return static_cast<slong_t>( + (ldbl_val.sextOrTrunc(sizeof(slong_t) * 8)).getSExtValue()); } return fail_value; } @@ -1389,14 +1526,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (ulong_t)(m_integer.zextOrTrunc(sizeof(ulong_t) * 8)).getZExtValue(); + case e_sint512: + case e_uint512: + return static_cast<ulong_t>( + (m_integer.zextOrTrunc(sizeof(ulong_t) * 8)).getZExtValue()); case e_float: - return (ulong_t)m_float.convertToFloat(); + return static_cast<ulong_t>(m_float.convertToFloat()); case e_double: - return (ulong_t)m_float.convertToDouble(); + return static_cast<ulong_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (ulong_t)(ldbl_val.zextOrTrunc(sizeof(ulong_t) * 8)).getZExtValue(); + return static_cast<ulong_t>( + (ldbl_val.zextOrTrunc(sizeof(ulong_t) * 8)).getZExtValue()); } return fail_value; } @@ -1415,16 +1556,18 @@ case e_uint128: case e_sint256: case e_uint256: - return (slonglong_t)(m_integer.sextOrTrunc(sizeof(slonglong_t) * 8)) - .getSExtValue(); + case e_sint512: + case e_uint512: + return static_cast<slonglong_t>( + (m_integer.sextOrTrunc(sizeof(slonglong_t) * 8)).getSExtValue()); case e_float: - return (slonglong_t)m_float.convertToFloat(); + return static_cast<slonglong_t>(m_float.convertToFloat()); case e_double: - return (slonglong_t)m_float.convertToDouble(); + return static_cast<slonglong_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (slonglong_t)(ldbl_val.sextOrTrunc(sizeof(slonglong_t) * 8)) - .getSExtValue(); + return static_cast<slonglong_t>( + (ldbl_val.sextOrTrunc(sizeof(slonglong_t) * 8)).getSExtValue()); } return fail_value; } @@ -1443,21 +1586,23 @@ case e_uint128: case e_sint256: case e_uint256: - return (ulonglong_t)(m_integer.zextOrTrunc(sizeof(ulonglong_t) * 8)) - .getZExtValue(); + case e_sint512: + case e_uint512: + return static_cast<ulonglong_t>( + (m_integer.zextOrTrunc(sizeof(ulonglong_t) * 8)).getZExtValue()); case e_float: - return (ulonglong_t)m_float.convertToFloat(); + return static_cast<ulonglong_t>(m_float.convertToFloat()); case e_double: { double d_val = m_float.convertToDouble(); llvm::APInt rounded_double = llvm::APIntOps::RoundDoubleToAPInt(d_val, sizeof(ulonglong_t) * 8); - return (ulonglong_t)(rounded_double.zextOrTrunc(sizeof(ulonglong_t) * 8)) - .getZExtValue(); + return static_cast<ulonglong_t>( + (rounded_double.zextOrTrunc(sizeof(ulonglong_t) * 8)).getZExtValue()); } case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (ulonglong_t)(ldbl_val.zextOrTrunc(sizeof(ulonglong_t) * 8)) - .getZExtValue(); + return static_cast<ulonglong_t>( + (ldbl_val.zextOrTrunc(sizeof(ulonglong_t) * 8)).getZExtValue()); } return fail_value; } @@ -1476,6 +1621,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: return m_integer; case e_float: case e_double: @@ -1499,52 +1646,8 @@ case e_uint128: case e_sint256: case e_uint256: - return m_integer; - case e_float: - case e_double: - case e_long_double: - return m_float.bitcastToAPInt(); - } - return fail_value; -} - -llvm::APInt Scalar::SInt256(llvm::APInt &fail_value) const { - switch (m_type) { - case e_void: - break; - case e_sint: - case e_uint: - case e_slong: - case e_ulong: - case e_slonglong: - case e_ulonglong: - case e_sint128: - case e_uint128: - case e_sint256: - case e_uint256: - return m_integer; - case e_float: - case e_double: - case e_long_double: - return m_float.bitcastToAPInt(); - } - return fail_value; -} - -llvm::APInt Scalar::UInt256(const llvm::APInt &fail_value) const { - switch (m_type) { - case e_void: - break; - case e_sint: - case e_uint: - case e_slong: - case e_ulong: - case e_slonglong: - case e_ulonglong: - case e_sint128: - case e_uint128: - case e_sint256: - case e_uint256: + case e_sint512: + case e_uint512: return m_integer; case e_float: case e_double: @@ -1568,11 +1671,13 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: return llvm::APIntOps::RoundAPIntToFloat(m_integer); case e_float: return m_float.convertToFloat(); case e_double: - return (float_t)m_float.convertToDouble(); + return static_cast<float_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); return ldbl_val.bitsToFloat(); @@ -1594,9 +1699,11 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: return llvm::APIntOps::RoundAPIntToDouble(m_integer); case e_float: - return (double_t)m_float.convertToFloat(); + return static_cast<double_t>(m_float.convertToFloat()); case e_double: return m_float.convertToDouble(); case e_long_double: @@ -1620,14 +1727,17 @@ case e_uint128: case e_sint256: case e_uint256: - return (long_double_t)llvm::APIntOps::RoundAPIntToDouble(m_integer); + case e_sint512: + case e_uint512: + return static_cast<long_double_t>( + llvm::APIntOps::RoundAPIntToDouble(m_integer)); case e_float: - return (long_double_t)m_float.convertToFloat(); + return static_cast<long_double_t>(m_float.convertToFloat()); case e_double: - return (long_double_t)m_float.convertToDouble(); + return static_cast<long_double_t>(m_float.convertToDouble()); case e_long_double: llvm::APInt ldbl_val = m_float.bitcastToAPInt(); - return (long_double_t)ldbl_val.bitsToDouble(); + return static_cast<long_double_t>(ldbl_val.bitsToDouble()); } return fail_value; } @@ -1651,6 +1761,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer = a->m_integer + b->m_integer; break; @@ -1683,6 +1795,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: switch (rhs.m_type) { case e_void: case e_float: @@ -1700,6 +1814,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer = m_integer << rhs.m_integer; break; } @@ -1727,6 +1843,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: switch (rhs.m_type) { case e_void: case e_float: @@ -1744,6 +1862,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer = m_integer.lshr(rhs.m_integer); break; } @@ -1771,6 +1891,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: switch (rhs.m_type) { case e_void: case e_float: @@ -1788,6 +1910,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer = m_integer.ashr(rhs.m_integer); break; } @@ -1815,6 +1939,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: switch (rhs.m_type) { case e_void: case e_float: @@ -1832,6 +1958,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer &= rhs.m_integer; break; } @@ -1850,6 +1978,7 @@ case e_slonglong: case e_sint128: case e_sint256: + case e_sint512: if (m_integer.isNegative()) m_integer = -m_integer; return true; @@ -1860,6 +1989,7 @@ return true; case e_uint128: case e_uint256: + case e_uint512: case e_float: case e_double: case e_long_double: @@ -1883,6 +2013,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer = -m_integer; return true; case e_float: @@ -1906,6 +2038,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer = ~m_integer; return true; @@ -1938,6 +2072,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: result.m_integer = a->m_integer + b->m_integer; break; case Scalar::e_float: @@ -1970,6 +2106,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: result.m_integer = a->m_integer - b->m_integer; break; case Scalar::e_float: @@ -1997,6 +2135,7 @@ case Scalar::e_slonglong: case Scalar::e_sint128: case Scalar::e_sint256: + case Scalar::e_sint512: if (b->m_integer != 0) { result.m_integer = a->m_integer.sdiv(b->m_integer); return result; @@ -2007,6 +2146,7 @@ case Scalar::e_ulonglong: case Scalar::e_uint128: case Scalar::e_uint256: + case Scalar::e_uint512: if (b->m_integer != 0) { result.m_integer = a->m_integer.udiv(b->m_integer); return result; @@ -2048,6 +2188,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: result.m_integer = a->m_integer * b->m_integer; break; case Scalar::e_float: @@ -2078,6 +2220,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: result.m_integer = a->m_integer & b->m_integer; break; case Scalar::e_void: @@ -2110,6 +2254,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: result.m_integer = a->m_integer | b->m_integer; break; @@ -2142,6 +2288,7 @@ case Scalar::e_slonglong: case Scalar::e_sint128: case Scalar::e_sint256: + case Scalar::e_sint512: if (b->m_integer != 0) { result.m_integer = a->m_integer.srem(b->m_integer); return result; @@ -2152,6 +2299,7 @@ case Scalar::e_ulonglong: case Scalar::e_uint128: case Scalar::e_uint256: + case Scalar::e_uint512: if (b->m_integer != 0) { result.m_integer = a->m_integer.urem(b->m_integer); return result; @@ -2181,6 +2329,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: result.m_integer = a->m_integer ^ b->m_integer; break; @@ -2227,10 +2377,10 @@ error.SetErrorStringWithFormat( "'%s' is not a valid unsigned integer string value", value_str); else if (!UIntValueIsValidForSize(uval64, byte_size)) - error.SetErrorStringWithFormat("value 0x%" PRIx64 - " is too large to fit in a %" PRIu64 - " byte unsigned integer value", - uval64, (uint64_t)byte_size); + error.SetErrorStringWithFormat( + "value 0x%" PRIx64 " is too large to fit in a %" PRIu64 + " byte unsigned integer value", + uval64, static_cast<uint64_t>(byte_size)); else { m_type = Scalar::GetValueTypeForUnsignedIntegerWithByteSize(byte_size); switch (m_type) { @@ -2246,14 +2396,14 @@ default: error.SetErrorStringWithFormat( "unsupported unsigned integer byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); break; } } } else { error.SetErrorStringWithFormat( "unsupported unsigned integer byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); return error; } break; @@ -2265,10 +2415,10 @@ error.SetErrorStringWithFormat( "'%s' is not a valid signed integer string value", value_str); else if (!SIntValueIsValidForSize(sval64, byte_size)) - error.SetErrorStringWithFormat("value 0x%" PRIx64 - " is too large to fit in a %" PRIu64 - " byte signed integer value", - sval64, (uint64_t)byte_size); + error.SetErrorStringWithFormat( + "value 0x%" PRIx64 " is too large to fit in a %" PRIu64 + " byte signed integer value", + sval64, static_cast<uint64_t>(byte_size)); else { m_type = Scalar::GetValueTypeForSignedIntegerWithByteSize(byte_size); switch (m_type) { @@ -2284,14 +2434,14 @@ default: error.SetErrorStringWithFormat( "unsupported signed integer byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); break; } } } else { error.SetErrorStringWithFormat( "unsupported signed integer byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); return error; } break; @@ -2316,17 +2466,17 @@ value_str); } else if (byte_size == sizeof(long double)) { if (::sscanf(value_str, "%Lf", &l_val) == 1) { - m_float = - llvm::APFloat(llvm::APFloat::x87DoubleExtended(), - llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, - ((type128 *)&l_val)->x)); + m_float = llvm::APFloat( + llvm::APFloat::x87DoubleExtended(), + llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, + (reinterpret_cast<type128 *>(&l_val))->x)); m_type = e_long_double; } else error.SetErrorStringWithFormat("'%s' is not a valid float string value", value_str); } else { error.SetErrorStringWithFormat("unsupported float byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); return error; } break; @@ -2359,45 +2509,45 @@ switch (byte_size) { case 1: - operator=((uint8_t)data.GetU8(&offset)); + operator=(data.GetU8(&offset)); break; case 2: - operator=((uint16_t)data.GetU16(&offset)); + operator=(data.GetU16(&offset)); break; case 4: - operator=((uint32_t)data.GetU32(&offset)); + operator=(data.GetU32(&offset)); break; case 8: - operator=((uint64_t)data.GetU64(&offset)); + operator=(data.GetU64(&offset)); break; case 16: if (data.GetByteOrder() == eByteOrderBig) { - int128.x[1] = (uint64_t)data.GetU64(&offset); - int128.x[0] = (uint64_t)data.GetU64(&offset); + int128.x[1] = data.GetU64(&offset); + int128.x[0] = data.GetU64(&offset); } else { - int128.x[0] = (uint64_t)data.GetU64(&offset); - int128.x[1] = (uint64_t)data.GetU64(&offset); + int128.x[0] = data.GetU64(&offset); + int128.x[1] = data.GetU64(&offset); } operator=(llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, int128.x)); break; case 32: if (data.GetByteOrder() == eByteOrderBig) { - int256.x[3] = (uint64_t)data.GetU64(&offset); - int256.x[2] = (uint64_t)data.GetU64(&offset); - int256.x[1] = (uint64_t)data.GetU64(&offset); - int256.x[0] = (uint64_t)data.GetU64(&offset); + int256.x[3] = data.GetU64(&offset); + int256.x[2] = data.GetU64(&offset); + int256.x[1] = data.GetU64(&offset); + int256.x[0] = data.GetU64(&offset); } else { - int256.x[0] = (uint64_t)data.GetU64(&offset); - int256.x[1] = (uint64_t)data.GetU64(&offset); - int256.x[2] = (uint64_t)data.GetU64(&offset); - int256.x[3] = (uint64_t)data.GetU64(&offset); + int256.x[0] = data.GetU64(&offset); + int256.x[1] = data.GetU64(&offset); + int256.x[2] = data.GetU64(&offset); + int256.x[3] = data.GetU64(&offset); } operator=(llvm::APInt(BITWIDTH_INT256, NUM_OF_WORDS_INT256, int256.x)); break; default: error.SetErrorStringWithFormat( "unsupported unsigned integer byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); break; } } break; @@ -2406,45 +2556,45 @@ switch (byte_size) { case 1: - operator=((int8_t)data.GetU8(&offset)); + operator=(static_cast<int8_t>(data.GetU8(&offset))); break; case 2: - operator=((int16_t)data.GetU16(&offset)); + operator=(static_cast<int16_t>(data.GetU16(&offset))); break; case 4: - operator=((int32_t)data.GetU32(&offset)); + operator=(static_cast<int32_t>(data.GetU32(&offset))); break; case 8: - operator=((int64_t)data.GetU64(&offset)); + operator=(static_cast<int64_t>(data.GetU64(&offset))); break; case 16: if (data.GetByteOrder() == eByteOrderBig) { - int128.x[1] = (uint64_t)data.GetU64(&offset); - int128.x[0] = (uint64_t)data.GetU64(&offset); + int128.x[1] = data.GetU64(&offset); + int128.x[0] = data.GetU64(&offset); } else { - int128.x[0] = (uint64_t)data.GetU64(&offset); - int128.x[1] = (uint64_t)data.GetU64(&offset); + int128.x[0] = data.GetU64(&offset); + int128.x[1] = data.GetU64(&offset); } operator=(llvm::APInt(BITWIDTH_INT128, NUM_OF_WORDS_INT128, int128.x)); break; case 32: if (data.GetByteOrder() == eByteOrderBig) { - int256.x[3] = (uint64_t)data.GetU64(&offset); - int256.x[2] = (uint64_t)data.GetU64(&offset); - int256.x[1] = (uint64_t)data.GetU64(&offset); - int256.x[0] = (uint64_t)data.GetU64(&offset); + int256.x[3] = data.GetU64(&offset); + int256.x[2] = data.GetU64(&offset); + int256.x[1] = data.GetU64(&offset); + int256.x[0] = data.GetU64(&offset); } else { - int256.x[0] = (uint64_t)data.GetU64(&offset); - int256.x[1] = (uint64_t)data.GetU64(&offset); - int256.x[2] = (uint64_t)data.GetU64(&offset); - int256.x[3] = (uint64_t)data.GetU64(&offset); + int256.x[0] = data.GetU64(&offset); + int256.x[1] = data.GetU64(&offset); + int256.x[2] = data.GetU64(&offset); + int256.x[3] = data.GetU64(&offset); } operator=(llvm::APInt(BITWIDTH_INT256, NUM_OF_WORDS_INT256, int256.x)); break; default: error.SetErrorStringWithFormat( "unsupported signed integer byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); break; } } break; @@ -2452,14 +2602,14 @@ lldb::offset_t offset = 0; if (byte_size == sizeof(float)) - operator=((float)data.GetFloat(&offset)); + operator=(data.GetFloat(&offset)); else if (byte_size == sizeof(double)) - operator=((double)data.GetDouble(&offset)); + operator=(data.GetDouble(&offset)); else if (byte_size == sizeof(long double)) - operator=((long double)data.GetLongDouble(&offset)); + operator=(data.GetLongDouble(&offset)); else error.SetErrorStringWithFormat("unsupported float byte size: %" PRIu64 "", - (uint64_t)byte_size); + static_cast<uint64_t>(byte_size)); } break; } @@ -2487,6 +2637,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: if (max_bit_pos == sign_bit_pos) return true; else if (sign_bit_pos < (max_bit_pos - 1)) { @@ -2546,6 +2698,7 @@ case Scalar::e_slonglong: case Scalar::e_sint128: case Scalar::e_sint256: + case Scalar::e_sint512: m_integer = m_integer.ashr(bit_offset) .sextOrTrunc(bit_size) .sextOrSelf(8 * GetByteSize()); @@ -2556,6 +2709,7 @@ case Scalar::e_ulonglong: case Scalar::e_uint128: case Scalar::e_uint256: + case Scalar::e_uint512: m_integer = m_integer.lshr(bit_offset) .zextOrTrunc(bit_size) .zextOrSelf(8 * GetByteSize()); @@ -2586,6 +2740,8 @@ case Scalar::e_uint128: case Scalar::e_sint256: case Scalar::e_uint256: + case Scalar::e_sint512: + case Scalar::e_uint512: return a->m_integer == b->m_integer; case Scalar::e_float: case Scalar::e_double: @@ -2617,6 +2773,8 @@ case Scalar::e_slonglong: case Scalar::e_sint128: case Scalar::e_sint256: + case Scalar::e_sint512: + case Scalar::e_uint512: return a->m_integer.slt(b->m_integer); case Scalar::e_uint: case Scalar::e_ulong: @@ -2660,6 +2818,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer.clearBit(bit); return true; case e_float: @@ -2684,6 +2844,8 @@ case e_uint128: case e_sint256: case e_uint256: + case e_sint512: + case e_uint512: m_integer.setBit(bit); return true; case e_float: @@ -2693,3 +2855,9 @@ } return false; } + +llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &os, const Scalar &scalar) { + StreamString s; + scalar.GetValue(&s, /*show_type*/ true); + return os << s.GetString(); +}
diff --git a/src/llvm-project/lldb/source/Utility/SelectHelper.cpp b/src/llvm-project/lldb/source/Utility/SelectHelper.cpp index 2979a67..ff21d99 100644 --- a/src/llvm-project/lldb/source/Utility/SelectHelper.cpp +++ b/src/llvm-project/lldb/source/Utility/SelectHelper.cpp
@@ -1,9 +1,8 @@ //===-- SelectHelper.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -133,9 +132,7 @@ fd_set *read_fdset_ptr = nullptr; fd_set *write_fdset_ptr = nullptr; fd_set *error_fdset_ptr = nullptr; -//---------------------------------------------------------------------- // Initialize and zero out the fdsets -//---------------------------------------------------------------------- #if defined(__APPLE__) llvm::SmallVector<fd_set, 1> read_fdset; llvm::SmallVector<fd_set, 1> write_fdset; @@ -177,9 +174,7 @@ error_fdset_ptr = &error_fdset; } #endif - //---------------------------------------------------------------------- // Set the FD bits in the fdsets for read/write/error - //---------------------------------------------------------------------- for (auto &pair : m_fd_map) { const lldb::socket_t fd = pair.first; @@ -193,17 +188,13 @@ FD_SET(fd, error_fdset_ptr); } - //---------------------------------------------------------------------- // Setup our timeout time value if needed - //---------------------------------------------------------------------- struct timeval *tv_ptr = nullptr; struct timeval tv = {0, 0}; - while (1) { + while (true) { using namespace std::chrono; - //------------------------------------------------------------------ // Setup out relative timeout based on the end time if we have one - //------------------------------------------------------------------ if (m_end_time.hasValue()) { tv_ptr = &tv; const auto remaining_dur = duration_cast<microseconds>(
diff --git a/src/llvm-project/lldb/source/Utility/SharingPtr.cpp b/src/llvm-project/lldb/source/Utility/SharingPtr.cpp index bdaedfb..45f2a77 100644 --- a/src/llvm-project/lldb/source/Utility/SharingPtr.cpp +++ b/src/llvm-project/lldb/source/Utility/SharingPtr.cpp
@@ -1,9 +1,8 @@ //===---------------------SharingPtr.cpp ------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/State.cpp b/src/llvm-project/lldb/source/Utility/State.cpp index 6ff8a49..51fe92b 100644 --- a/src/llvm-project/lldb/source/Utility/State.cpp +++ b/src/llvm-project/lldb/source/Utility/State.cpp
@@ -1,9 +1,8 @@ //===-- State.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/Status.cpp b/src/llvm-project/lldb/source/Utility/Status.cpp index 062bd26..3d64fb8 100644 --- a/src/llvm-project/lldb/source/Utility/Status.cpp +++ b/src/llvm-project/lldb/source/Utility/Status.cpp
@@ -1,10 +1,9 @@ //===-- Status.cpp -----------------------------------------------*- C++ //-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -48,8 +47,6 @@ : m_code(EC.value()), m_type(ErrorType::eErrorTypeGeneric), m_string(EC.message()) {} -Status::Status(const Status &rhs) = default; - Status::Status(const char *format, ...) : m_code(0), m_type(eErrorTypeInvalid), m_string() { va_list args; @@ -96,9 +93,7 @@ llvm::inconvertibleErrorCode()); } -//---------------------------------------------------------------------- // Assignment operator -//---------------------------------------------------------------------- const Status &Status::operator=(const Status &rhs) { if (this != &rhs) { m_code = rhs.m_code; @@ -127,11 +122,9 @@ } #endif -//---------------------------------------------------------------------- // Get the error value as a NULL C string. The error string will be fetched and // cached on demand. The cached error string value will remain until the error // value is changed or cleared. -//---------------------------------------------------------------------- const char *Status::AsCString(const char *default_error_str) const { if (Success()) return nullptr; @@ -168,35 +161,25 @@ return m_string.c_str(); } -//---------------------------------------------------------------------- // Clear the error and any cached error string that it might contain. -//---------------------------------------------------------------------- void Status::Clear() { m_code = 0; m_type = eErrorTypeInvalid; m_string.clear(); } -//---------------------------------------------------------------------- // Access the error value. -//---------------------------------------------------------------------- Status::ValueType Status::GetError() const { return m_code; } -//---------------------------------------------------------------------- // Access the error type. -//---------------------------------------------------------------------- ErrorType Status::GetType() const { return m_type; } -//---------------------------------------------------------------------- // Returns true if this object contains a value that describes an error or // otherwise non-success result. -//---------------------------------------------------------------------- bool Status::Fail() const { return m_code != 0; } -//---------------------------------------------------------------------- // Set accessor for the error value to "err" and the type to // "eErrorTypeMachKernel" -//---------------------------------------------------------------------- void Status::SetMachError(uint32_t err) { m_code = err; m_type = eErrorTypeMachKernel; @@ -227,40 +210,32 @@ return length; } -//---------------------------------------------------------------------- // Set accessor for the error value and type. -//---------------------------------------------------------------------- void Status::SetError(ValueType err, ErrorType type) { m_code = err; m_type = type; m_string.clear(); } -//---------------------------------------------------------------------- // Update the error value to be "errno" and update the type to be "POSIX". -//---------------------------------------------------------------------- void Status::SetErrorToErrno() { m_code = errno; m_type = eErrorTypePOSIX; m_string.clear(); } -//---------------------------------------------------------------------- // Update the error value to be LLDB_GENERIC_ERROR and update the type to be // "Generic". -//---------------------------------------------------------------------- void Status::SetErrorToGenericError() { m_code = LLDB_GENERIC_ERROR; m_type = eErrorTypeGeneric; m_string.clear(); } -//---------------------------------------------------------------------- // Set accessor for the error string value for a specific error. This allows // any string to be supplied as an error explanation. The error string value // will remain until the error value is cleared or a new error value/type is // assigned. -//---------------------------------------------------------------------- void Status::SetErrorString(llvm::StringRef err_str) { if (!err_str.empty()) { // If we have an error string, we should always at least have an error set @@ -271,12 +246,10 @@ m_string = err_str; } -//------------------------------------------------------------------ /// Set the current error string to a formatted error string. /// -/// @param format +/// \param format /// A printf style format string -//------------------------------------------------------------------ int Status::SetErrorStringWithFormat(const char *format, ...) { if (format != nullptr && format[0]) { va_list args; @@ -307,10 +280,8 @@ return 0; } -//---------------------------------------------------------------------- // Returns true if the error code in this object is considered a successful // return value. -//---------------------------------------------------------------------- bool Status::Success() const { return m_code == 0; } bool Status::WasInterrupted() const {
diff --git a/src/llvm-project/lldb/source/Utility/Stream.cpp b/src/llvm-project/lldb/source/Utility/Stream.cpp index 54691c7..c48a12a 100644 --- a/src/llvm-project/lldb/source/Utility/Stream.cpp +++ b/src/llvm-project/lldb/source/Utility/Stream.cpp
@@ -1,9 +1,8 @@ //===-- Stream.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -30,9 +29,7 @@ : m_flags(0), m_addr_size(4), m_byte_order(endian::InlHostByteOrder()), m_indent_level(0), m_forwarder(*this) {} -//------------------------------------------------------------------ // Destructor -//------------------------------------------------------------------ Stream::~Stream() {} ByteOrder Stream::SetByteOrder(ByteOrder byte_order) { @@ -41,14 +38,10 @@ return old_byte_order; } -//------------------------------------------------------------------ // Put an offset "uval" out to the stream using the printf format in "format". -//------------------------------------------------------------------ void Stream::Offset(uint32_t uval, const char *format) { Printf(format, uval); } -//------------------------------------------------------------------ // Put an SLEB128 "uval" out to the stream using the printf format in "format". -//------------------------------------------------------------------ size_t Stream::PutSLEB128(int64_t sval) { if (m_flags.Test(eBinary)) return llvm::encodeSLEB128(sval, m_forwarder); @@ -56,9 +49,7 @@ return Printf("0x%" PRIi64, sval); } -//------------------------------------------------------------------ // Put an ULEB128 "uval" out to the stream using the printf format in "format". -//------------------------------------------------------------------ size_t Stream::PutULEB128(uint64_t uval) { if (m_flags.Test(eBinary)) return llvm::encodeULEB128(uval, m_forwarder); @@ -66,9 +57,7 @@ return Printf("0x%" PRIx64, uval); } -//------------------------------------------------------------------ // Print a raw NULL terminated C string to the stream. -//------------------------------------------------------------------ size_t Stream::PutCString(llvm::StringRef str) { size_t bytes_written = 0; bytes_written = Write(str.data(), str.size()); @@ -79,18 +68,14 @@ return bytes_written; } -//------------------------------------------------------------------ // Print a double quoted NULL terminated C string to the stream using the // printf format in "format". -//------------------------------------------------------------------ void Stream::QuotedCString(const char *cstr, const char *format) { Printf(format, cstr); } -//------------------------------------------------------------------ // Put an address "addr" out to the stream with optional prefix and suffix // strings. -//------------------------------------------------------------------ void Stream::Address(uint64_t addr, uint32_t addr_size, const char *prefix, const char *suffix) { if (prefix == nullptr) @@ -99,13 +84,11 @@ suffix = ""; // int addr_width = m_addr_size << 1; // Printf ("%s0x%0*" PRIx64 "%s", prefix, addr_width, addr, suffix); - Printf("%s0x%0*" PRIx64 "%s", prefix, addr_size * 2, (uint64_t)addr, suffix); + Printf("%s0x%0*" PRIx64 "%s", prefix, addr_size * 2, addr, suffix); } -//------------------------------------------------------------------ // Put an address range out to the stream with optional prefix and suffix // strings. -//------------------------------------------------------------------ void Stream::AddressRange(uint64_t lo_addr, uint64_t hi_addr, uint32_t addr_size, const char *prefix, const char *suffix) { @@ -119,9 +102,7 @@ size_t Stream::PutChar(char ch) { return Write(&ch, 1); } -//------------------------------------------------------------------ // Print some formatted output to the stream. -//------------------------------------------------------------------ size_t Stream::Printf(const char *format, ...) { va_list args; va_start(args, format); @@ -130,9 +111,7 @@ return result; } -//------------------------------------------------------------------ // Print some formatted output to the stream. -//------------------------------------------------------------------ size_t Stream::PrintfVarArg(const char *format, va_list args) { llvm::SmallString<1024> buf; VASprintf(buf, format, args); @@ -144,15 +123,11 @@ return Write(buf.c_str(), length); } -//------------------------------------------------------------------ // Print and End of Line character to the stream -//------------------------------------------------------------------ size_t Stream::EOL() { return PutChar('\n'); } -//------------------------------------------------------------------ // Indent the current line using the current indentation level and print an // optional string following the indentation spaces. -//------------------------------------------------------------------ size_t Stream::Indent(const char *s) { return Printf("%*.*s%s", m_indent_level, m_indent_level, "", s ? s : ""); } @@ -162,17 +137,13 @@ str.str().c_str()); } -//------------------------------------------------------------------ // Stream a character "ch" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(char ch) { PutChar(ch); return *this; } -//------------------------------------------------------------------ // Stream the NULL terminated C string out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(const char *s) { Printf("%s", s); return *this; @@ -183,96 +154,70 @@ return *this; } -//------------------------------------------------------------------ // Stream the pointer value out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(const void *p) { - Printf("0x%.*tx", (int)sizeof(const void *) * 2, (ptrdiff_t)p); + Printf("0x%.*tx", static_cast<int>(sizeof(const void *)) * 2, (ptrdiff_t)p); return *this; } -//------------------------------------------------------------------ // Stream a uint8_t "uval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(uint8_t uval) { PutHex8(uval); return *this; } -//------------------------------------------------------------------ // Stream a uint16_t "uval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(uint16_t uval) { PutHex16(uval, m_byte_order); return *this; } -//------------------------------------------------------------------ // Stream a uint32_t "uval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(uint32_t uval) { PutHex32(uval, m_byte_order); return *this; } -//------------------------------------------------------------------ // Stream a uint64_t "uval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(uint64_t uval) { PutHex64(uval, m_byte_order); return *this; } -//------------------------------------------------------------------ // Stream a int8_t "sval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(int8_t sval) { - Printf("%i", (int)sval); + Printf("%i", static_cast<int>(sval)); return *this; } -//------------------------------------------------------------------ // Stream a int16_t "sval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(int16_t sval) { - Printf("%i", (int)sval); + Printf("%i", static_cast<int>(sval)); return *this; } -//------------------------------------------------------------------ // Stream a int32_t "sval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(int32_t sval) { - Printf("%i", (int)sval); + Printf("%i", static_cast<int>(sval)); return *this; } -//------------------------------------------------------------------ // Stream a int64_t "sval" out to this stream. -//------------------------------------------------------------------ Stream &Stream::operator<<(int64_t sval) { Printf("%" PRIi64, sval); return *this; } -//------------------------------------------------------------------ // Get the current indentation level -//------------------------------------------------------------------ int Stream::GetIndentLevel() const { return m_indent_level; } -//------------------------------------------------------------------ // Set the current indentation level -//------------------------------------------------------------------ void Stream::SetIndentLevel(int indent_level) { m_indent_level = indent_level; } -//------------------------------------------------------------------ // Increment the current indentation level -//------------------------------------------------------------------ void Stream::IndentMore(int amount) { m_indent_level += amount; } -//------------------------------------------------------------------ // Decrement the current indentation level -//------------------------------------------------------------------ void Stream::IndentLess(int amount) { if (m_indent_level >= amount) m_indent_level -= amount; @@ -280,29 +225,19 @@ m_indent_level = 0; } -//------------------------------------------------------------------ // Get the address size in bytes -//------------------------------------------------------------------ uint32_t Stream::GetAddressByteSize() const { return m_addr_size; } -//------------------------------------------------------------------ // Set the address size in bytes -//------------------------------------------------------------------ void Stream::SetAddressByteSize(uint32_t addr_size) { m_addr_size = addr_size; } -//------------------------------------------------------------------ // The flags get accessor -//------------------------------------------------------------------ Flags &Stream::GetFlags() { return m_flags; } -//------------------------------------------------------------------ // The flags const get accessor -//------------------------------------------------------------------ const Flags &Stream::GetFlags() const { return m_flags; } -//------------------------------------------------------------------ // The byte order get accessor -//------------------------------------------------------------------ lldb::ByteOrder Stream::GetByteOrder() const { return m_byte_order; } @@ -360,10 +295,10 @@ if (byte_order == eByteOrderLittle) { for (size_t byte = 0; byte < sizeof(uvalue); ++byte) - _PutHex8((uint8_t)(uvalue >> (byte * 8)), false); + _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false); } else { for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte) - _PutHex8((uint8_t)(uvalue >> (byte * 8)), false); + _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false); } return *delta; } @@ -376,10 +311,10 @@ if (byte_order == eByteOrderLittle) { for (size_t byte = 0; byte < sizeof(uvalue); ++byte) - _PutHex8((uint8_t)(uvalue >> (byte * 8)), false); + _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false); } else { for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte) - _PutHex8((uint8_t)(uvalue >> (byte * 8)), false); + _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false); } return *delta; } @@ -392,10 +327,10 @@ if (byte_order == eByteOrderLittle) { for (size_t byte = 0; byte < sizeof(uvalue); ++byte) - _PutHex8((uint8_t)(uvalue >> (byte * 8)), false); + _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false); } else { for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte) - _PutHex8((uint8_t)(uvalue >> (byte * 8)), false); + _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false); } return *delta; } @@ -404,11 +339,11 @@ lldb::ByteOrder byte_order) { switch (byte_size) { case 1: - return PutHex8((uint8_t)uvalue); + return PutHex8(static_cast<uint8_t>(uvalue)); case 2: - return PutHex16((uint16_t)uvalue, byte_order); + return PutHex16(static_cast<uint16_t>(uvalue), byte_order); case 4: - return PutHex32((uint32_t)uvalue, byte_order); + return PutHex32(static_cast<uint32_t>(uvalue), byte_order); case 8: return PutHex64(uvalue, byte_order); } @@ -451,7 +386,7 @@ if (dst_byte_order == eByteOrderInvalid) dst_byte_order = m_byte_order; - const uint8_t *src = (const uint8_t *)s; + const uint8_t *src = static_cast<const uint8_t *>(s); bool binary_was_set = m_flags.Test(eBinary); if (!binary_was_set) m_flags.Set(eBinary); @@ -478,7 +413,7 @@ if (dst_byte_order == eByteOrderInvalid) dst_byte_order = m_byte_order; - const uint8_t *src = (const uint8_t *)s; + const uint8_t *src = static_cast<const uint8_t *>(s); bool binary_is_set = m_flags.Test(eBinary); m_flags.Clear(eBinary); if (src_byte_order == dst_byte_order) { @@ -494,14 +429,12 @@ return *delta; } -size_t Stream::PutCStringAsRawHex8(const char *s) { +size_t Stream::PutStringAsRawHex8(llvm::StringRef s) { ByteDelta delta(*this); bool binary_is_set = m_flags.Test(eBinary); m_flags.Clear(eBinary); - while(*s) { - _PutHex8(*s, false); - ++s; - } + for (char c : s) + _PutHex8(c, false); if (binary_is_set) m_flags.Set(eBinary); return *delta;
diff --git a/src/llvm-project/lldb/source/Utility/StreamCallback.cpp b/src/llvm-project/lldb/source/Utility/StreamCallback.cpp index 9752843..b3d3ade 100644 --- a/src/llvm-project/lldb/source/Utility/StreamCallback.cpp +++ b/src/llvm-project/lldb/source/Utility/StreamCallback.cpp
@@ -1,9 +1,8 @@ //===-- StreamCallback.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/StreamGDBRemote.cpp b/src/llvm-project/lldb/source/Utility/StreamGDBRemote.cpp index 9304d84..c710bbe 100644 --- a/src/llvm-project/lldb/source/Utility/StreamGDBRemote.cpp +++ b/src/llvm-project/lldb/source/Utility/StreamGDBRemote.cpp
@@ -1,9 +1,8 @@ //===-- StreamGDBRemote.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -27,7 +26,7 @@ int StreamGDBRemote::PutEscapedBytes(const void *s, size_t src_len) { int bytes_written = 0; - const uint8_t *src = (const uint8_t *)s; + const uint8_t *src = static_cast<const uint8_t *>(s); bool binary_is_set = m_flags.Test(eBinary); m_flags.Clear(eBinary); while (src_len) {
diff --git a/src/llvm-project/lldb/source/Utility/StreamString.cpp b/src/llvm-project/lldb/source/Utility/StreamString.cpp index 1520961..bf9814d 100644 --- a/src/llvm-project/lldb/source/Utility/StreamString.cpp +++ b/src/llvm-project/lldb/source/Utility/StreamString.cpp
@@ -1,9 +1,8 @@ //===-- StreamString.cpp ----------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/StringExtractor.cpp b/src/llvm-project/lldb/source/Utility/StringExtractor.cpp index ddf4147..502f468 100644 --- a/src/llvm-project/lldb/source/Utility/StringExtractor.cpp +++ b/src/llvm-project/lldb/source/Utility/StringExtractor.cpp
@@ -1,9 +1,8 @@ //===-- StringExtractor.cpp -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -25,9 +24,7 @@ return -1; } -//---------------------------------------------------------------------- // StringExtractor constructor -//---------------------------------------------------------------------- StringExtractor::StringExtractor() : m_packet(), m_index(0) {} StringExtractor::StringExtractor(llvm::StringRef packet_str) @@ -41,26 +38,7 @@ m_packet.assign(packet_cstr); } -//---------------------------------------------------------------------- -// StringExtractor copy constructor -//---------------------------------------------------------------------- -StringExtractor::StringExtractor(const StringExtractor &rhs) - : m_packet(rhs.m_packet), m_index(rhs.m_index) {} - -//---------------------------------------------------------------------- -// StringExtractor assignment operator -//---------------------------------------------------------------------- -const StringExtractor &StringExtractor::operator=(const StringExtractor &rhs) { - if (this != &rhs) { - m_packet = rhs.m_packet; - m_index = rhs.m_index; - } - return *this; -} - -//---------------------------------------------------------------------- // Destructor -//---------------------------------------------------------------------- StringExtractor::~StringExtractor() {} char StringExtractor::GetChar(char fail_value) { @@ -73,13 +51,11 @@ return fail_value; } -//---------------------------------------------------------------------- // If a pair of valid hex digits exist at the head of the StringExtractor they // are decoded into an unsigned byte and returned by this function // // If there is not a pair of valid hex digits at the head of the // StringExtractor, it is left unchanged and -1 is returned -//---------------------------------------------------------------------- int StringExtractor::DecodeHexU8() { SkipSpaces(); if (GetBytesLeft() < 2) { @@ -91,13 +67,11 @@ return -1; } m_index += 2; - return (uint8_t)((hi_nibble << 4) + lo_nibble); + return static_cast<uint8_t>((hi_nibble << 4) + lo_nibble); } -//---------------------------------------------------------------------- // Extract an unsigned character from two hex ASCII chars in the packet string, // or return fail_value on failure -//---------------------------------------------------------------------- uint8_t StringExtractor::GetHexU8(uint8_t fail_value, bool set_eof_on_fail) { // On success, fail_value will be overwritten with the next character in the // stream @@ -113,7 +87,7 @@ // ch should not be changed in case of failure return false; } - ch = (uint8_t)byte; + ch = static_cast<uint8_t>(byte); return true; } @@ -198,12 +172,12 @@ if (m_index < m_packet.size() && ::isxdigit(m_packet[m_index])) { nibble_lo = xdigit_to_sint(m_packet[m_index]); ++m_index; - result |= ((uint32_t)nibble_hi << (shift_amount + 4)); - result |= ((uint32_t)nibble_lo << shift_amount); + result |= (static_cast<uint32_t>(nibble_hi) << (shift_amount + 4)); + result |= (static_cast<uint32_t>(nibble_lo) << shift_amount); nibble_count += 2; shift_amount += 8; } else { - result |= ((uint32_t)nibble_hi << shift_amount); + result |= (static_cast<uint32_t>(nibble_hi) << shift_amount); nibble_count += 1; shift_amount += 4; } @@ -249,12 +223,12 @@ if (m_index < m_packet.size() && ::isxdigit(m_packet[m_index])) { nibble_lo = xdigit_to_sint(m_packet[m_index]); ++m_index; - result |= ((uint64_t)nibble_hi << (shift_amount + 4)); - result |= ((uint64_t)nibble_lo << shift_amount); + result |= (static_cast<uint64_t>(nibble_hi) << (shift_amount + 4)); + result |= (static_cast<uint64_t>(nibble_lo) << shift_amount); nibble_count += 2; shift_amount += 8; } else { - result |= ((uint64_t)nibble_hi << shift_amount); + result |= (static_cast<uint64_t>(nibble_hi) << shift_amount); nibble_count += 1; shift_amount += 4; } @@ -305,19 +279,17 @@ return bytes_extracted; } -//---------------------------------------------------------------------- // Decodes all valid hex encoded bytes at the head of the StringExtractor, // limited by dst_len. // // Returns the number of bytes successfully decoded -//---------------------------------------------------------------------- size_t StringExtractor::GetHexBytesAvail(llvm::MutableArrayRef<uint8_t> dest) { size_t bytes_extracted = 0; while (!dest.empty()) { int decode = DecodeHexU8(); if (decode == -1) break; - dest[0] = (uint8_t)decode; + dest[0] = static_cast<uint8_t>(decode); dest = dest.drop_front(); ++bytes_extracted; } @@ -338,7 +310,7 @@ uint32_t shift_amount; for (i = 0, shift_amount = 0; i < byte_size && IsGood(); ++i, shift_amount += 8) { - result |= ((uint64_t)GetHexU8() << shift_amount); + result |= (static_cast<uint64_t>(GetHexU8()) << shift_amount); } } else { // Big Endian
diff --git a/src/llvm-project/lldb/source/Utility/StringExtractorGDBRemote.cpp b/src/llvm-project/lldb/source/Utility/StringExtractorGDBRemote.cpp index 2a8bd78..a011e92 100644 --- a/src/llvm-project/lldb/source/Utility/StringExtractorGDBRemote.cpp +++ b/src/llvm-project/lldb/source/Utility/StringExtractorGDBRemote.cpp
@@ -1,9 +1,8 @@ //===-- StringExtractorGDBRemote.cpp ----------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -286,8 +285,8 @@ break; case 'X': - if (PACKET_STARTS_WITH("qXfer:auxv:read::")) - return eServerPacketType_qXfer_auxv_read; + if (PACKET_STARTS_WITH("qXfer:")) + return eServerPacketType_qXfer; break; } break; @@ -378,9 +377,7 @@ break; case 'g': - if (packet_size == 1) - return eServerPacketType_g; - break; + return eServerPacketType_g; case 'G': return eServerPacketType_G;
diff --git a/src/llvm-project/lldb/source/Utility/StringLexer.cpp b/src/llvm-project/lldb/source/Utility/StringLexer.cpp index d5c7fc6..958a958 100644 --- a/src/llvm-project/lldb/source/Utility/StringLexer.cpp +++ b/src/llvm-project/lldb/source/Utility/StringLexer.cpp
@@ -1,9 +1,8 @@ //===--------------------- StringLexer.cpp -----------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,6 @@ StringLexer::StringLexer(std::string s) : m_data(s), m_position(0) {} -StringLexer::StringLexer(const StringLexer &rhs) - : m_data(rhs.m_data), m_position(rhs.m_position) {} - StringLexer::Character StringLexer::Peek() { return m_data[m_position]; } bool StringLexer::NextIf(Character c) {
diff --git a/src/llvm-project/lldb/source/Utility/StringList.cpp b/src/llvm-project/lldb/source/Utility/StringList.cpp index 20bde1a..fb0d9be 100644 --- a/src/llvm-project/lldb/source/Utility/StringList.cpp +++ b/src/llvm-project/lldb/source/Utility/StringList.cpp
@@ -1,9 +1,8 @@ //===-- StringList.cpp ------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/StructuredData.cpp b/src/llvm-project/lldb/source/Utility/StructuredData.cpp index 76a141a..0e203f9 100644 --- a/src/llvm-project/lldb/source/Utility/StructuredData.cpp +++ b/src/llvm-project/lldb/source/Utility/StructuredData.cpp
@@ -1,9 +1,8 @@ //===---------------------StructuredData.cpp ---------------------*- C++-*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -23,9 +22,7 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // Functions that use a JSONParser to parse JSON into StructuredData -//---------------------------------------------------------------------- static StructuredData::ObjectSP ParseJSONValue(JSONParser &json_parser); static StructuredData::ObjectSP ParseJSONObject(JSONParser &json_parser); static StructuredData::ObjectSP ParseJSONArray(JSONParser &json_parser); @@ -54,7 +51,7 @@ std::string value; std::string key; - while (1) { + while (true) { JSONParser::Token token = json_parser.GetToken(value); if (token == JSONParser::Token::String) { @@ -85,7 +82,7 @@ std::string value; std::string key; - while (1) { + while (true) { StructuredData::ObjectSP value_sp = ParseJSONValue(json_parser); if (value_sp) array_up->AddItem(value_sp);
diff --git a/src/llvm-project/lldb/source/Utility/TildeExpressionResolver.cpp b/src/llvm-project/lldb/source/Utility/TildeExpressionResolver.cpp index 4e2be77..b58f457 100644 --- a/src/llvm-project/lldb/source/Utility/TildeExpressionResolver.cpp +++ b/src/llvm-project/lldb/source/Utility/TildeExpressionResolver.cpp
@@ -1,9 +1,8 @@ //===--------------------- TildeExpressionResolver.cpp ----------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/Timer.cpp b/src/llvm-project/lldb/source/Utility/Timer.cpp index c56ac21..6b46d8b 100644 --- a/src/llvm-project/lldb/source/Utility/Timer.cpp +++ b/src/llvm-project/lldb/source/Utility/Timer.cpp
@@ -1,9 +1,8 @@ //===-- Timer.cpp -----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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/Timer.h" @@ -42,6 +41,8 @@ Timer::Category::Category(const char *cat) : m_name(cat) { m_nanos.store(0, std::memory_order_release); + m_nanos_total.store(0, std::memory_order_release); + m_count.store(0, std::memory_order_release); Category *expected = g_categories; do { m_next = expected; @@ -94,6 +95,8 @@ // Keep total results for each category so we can dump results. m_category.m_nanos += std::chrono::nanoseconds(timer_dur).count(); + m_category.m_nanos_total += std::chrono::nanoseconds(total_dur).count(); + m_category.m_count++; } void Timer::SetDisplayDepth(uint32_t depth) { g_display_depth = depth; } @@ -101,25 +104,38 @@ /* binary function predicate: * - returns whether a person is less than another person */ +namespace { +struct Stats { + const char *name; + uint64_t nanos; + uint64_t nanos_total; + uint64_t count; +}; +} // namespace -typedef std::pair<const char *, uint64_t> TimerEntry; - -static bool CategoryMapIteratorSortCriterion(const TimerEntry &lhs, - const TimerEntry &rhs) { - return lhs.second > rhs.second; +static bool CategoryMapIteratorSortCriterion(const Stats &lhs, + const Stats &rhs) { + return lhs.nanos > rhs.nanos; } void Timer::ResetCategoryTimes() { - for (Category *i = g_categories; i; i = i->m_next) + for (Category *i = g_categories; i; i = i->m_next) { i->m_nanos.store(0, std::memory_order_release); + i->m_nanos_total.store(0, std::memory_order_release); + i->m_count.store(0, std::memory_order_release); + } } void Timer::DumpCategoryTimes(Stream *s) { - std::vector<TimerEntry> sorted; + std::vector<Stats> sorted; for (Category *i = g_categories; i; i = i->m_next) { uint64_t nanos = i->m_nanos.load(std::memory_order_acquire); - if (nanos) - sorted.push_back(std::make_pair(i->m_name, nanos)); + if (nanos) { + uint64_t nanos_total = i->m_nanos_total.load(std::memory_order_acquire); + uint64_t count = i->m_count.load(std::memory_order_acquire); + Stats stats{i->m_name, nanos, nanos_total, count}; + sorted.push_back(stats); + } } if (sorted.empty()) return; // Later code will break without any elements. @@ -127,6 +143,10 @@ // Sort by time llvm::sort(sorted.begin(), sorted.end(), CategoryMapIteratorSortCriterion); - for (const auto &timer : sorted) - s->Printf("%.9f sec for %s\n", timer.second / 1000000000., timer.first); + for (const auto &stats : sorted) + s->Printf("%.9f sec (total: %.3fs; child: %.3fs; count: %" PRIu64 + ") for %s\n", + stats.nanos / 1000000000., stats.nanos_total / 1000000000., + (stats.nanos_total - stats.nanos) / 1000000000., stats.count, + stats.name); }
diff --git a/src/llvm-project/lldb/source/Utility/UUID.cpp b/src/llvm-project/lldb/source/Utility/UUID.cpp index b008787..2a73f9a 100644 --- a/src/llvm-project/lldb/source/Utility/UUID.cpp +++ b/src/llvm-project/lldb/source/Utility/UUID.cpp
@@ -1,9 +1,8 @@ //===-- UUID.cpp ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -110,3 +109,15 @@ // Else return zero to indicate we were not able to parse a UUID value return 0; } + +size_t UUID::SetFromOptionalStringRef(llvm::StringRef str, + uint32_t num_uuid_bytes) { + size_t num_chars_consumed = SetFromStringRef(str, num_uuid_bytes); + if (num_chars_consumed) { + if (llvm::all_of(m_bytes, [](uint8_t b) { return b == 0; })) + Clear(); + } + + return num_chars_consumed; +} +
diff --git a/src/llvm-project/lldb/source/Utility/UriParser.cpp b/src/llvm-project/lldb/source/Utility/UriParser.cpp index a6d81e7..b446958 100644 --- a/src/llvm-project/lldb/source/Utility/UriParser.cpp +++ b/src/llvm-project/lldb/source/Utility/UriParser.cpp
@@ -1,9 +1,8 @@ //===-- UriParser.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -16,9 +15,7 @@ using namespace lldb_private; -//---------------------------------------------------------------------- // UriParser::Parse -//---------------------------------------------------------------------- bool UriParser::Parse(llvm::StringRef uri, llvm::StringRef &scheme, llvm::StringRef &hostname, int &port, llvm::StringRef &path) {
diff --git a/src/llvm-project/lldb/source/Utility/UserID.cpp b/src/llvm-project/lldb/source/Utility/UserID.cpp index e65b8fa..b76a1cd 100644 --- a/src/llvm-project/lldb/source/Utility/UserID.cpp +++ b/src/llvm-project/lldb/source/Utility/UserID.cpp
@@ -1,9 +1,8 @@ //===-- UserID.cpp ----------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/UserIDResolver.cpp b/src/llvm-project/lldb/source/Utility/UserIDResolver.cpp new file mode 100644 index 0000000..8aac6f9 --- /dev/null +++ b/src/llvm-project/lldb/source/Utility/UserIDResolver.cpp
@@ -0,0 +1,44 @@ +//===-- UserIDResolver.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/Utility/UserIDResolver.h" +#include "llvm/Support/ManagedStatic.h" + +using namespace lldb_private; + +UserIDResolver::~UserIDResolver() = default; + +llvm::Optional<llvm::StringRef> UserIDResolver::Get( + id_t id, Map &cache, + llvm::Optional<std::string> (UserIDResolver::*do_get)(id_t)) { + + std::lock_guard<std::mutex> guard(m_mutex); + auto iter_bool = cache.try_emplace(id, llvm::None); + if (iter_bool.second) + iter_bool.first->second = (this->*do_get)(id); + if (iter_bool.first->second) + return llvm::StringRef(*iter_bool.first->second); + return llvm::None; +} + +namespace { +class NoopResolver : public UserIDResolver { +protected: + llvm::Optional<std::string> DoGetUserName(id_t uid) override { + return llvm::None; + } + + llvm::Optional<std::string> DoGetGroupName(id_t gid) override { + return llvm::None; + } +}; +} // namespace + +static llvm::ManagedStatic<NoopResolver> g_noop_resolver; + +UserIDResolver &UserIDResolver::GetNoopResolver() { return *g_noop_resolver; }
diff --git a/src/llvm-project/lldb/source/Utility/UuidCompatibility.h b/src/llvm-project/lldb/source/Utility/UuidCompatibility.h index df26f77..e992c0c 100644 --- a/src/llvm-project/lldb/source/Utility/UuidCompatibility.h +++ b/src/llvm-project/lldb/source/Utility/UuidCompatibility.h
@@ -1,9 +1,8 @@ //===-- UuidCompatibility.h -------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/VASprintf.cpp b/src/llvm-project/lldb/source/Utility/VASprintf.cpp index 4368a37..2ee0f66 100644 --- a/src/llvm-project/lldb/source/Utility/VASprintf.cpp +++ b/src/llvm-project/lldb/source/Utility/VASprintf.cpp
@@ -1,9 +1,8 @@ -//===-- VASPrintf.cpp -------------------------------------------*- C++ -*-===// +//===-- VASprintf.cpp -------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/Utility/VMRange.cpp b/src/llvm-project/lldb/source/Utility/VMRange.cpp index 20dc7db..f3f4ae7 100644 --- a/src/llvm-project/lldb/source/Utility/VMRange.cpp +++ b/src/llvm-project/lldb/source/Utility/VMRange.cpp
@@ -1,9 +1,8 @@ //===-- VMRange.cpp ---------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/lldb/source/lldb.cpp b/src/llvm-project/lldb/source/lldb.cpp index 1b4b3b8..c96f5d9 100644 --- a/src/llvm-project/lldb/source/lldb.cpp +++ b/src/llvm-project/lldb/source/lldb.cpp
@@ -1,9 +1,8 @@ //===-- lldb.cpp ------------------------------------------------*- C++ -*-===// // -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. +// 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 // //===----------------------------------------------------------------------===// @@ -14,12 +13,8 @@ #include "clang/Basic/Version.h" -#ifdef HAVE_SVN_VERSION_INC -#include "SVNVersion.inc" -#endif - -#ifdef HAVE_APPLE_VERSION_INC -#include "AppleVersion.inc" +#ifdef HAVE_VCS_VERSION_INC +#include "VCSVersion.inc" #endif static const char *GetLLDBRevision() { @@ -73,9 +68,5 @@ g_version_str += llvm_rev; } } - - // We don't have a version number (yet?). - g_version_str += "\n rust-enabled"; - return g_version_str.c_str(); }